diff options
author | Eike Stepper | 2012-07-19 08:22:04 +0000 |
---|---|---|
committer | Eike Stepper | 2012-07-19 08:22:04 +0000 |
commit | 1460904fd3c193ffaf809913b2983a400fce9d94 (patch) | |
tree | 72f3a17b75fedba3ae1060df1d32c9c7889be954 /plugins/org.eclipse.net4j.util/src | |
parent | 5f360965ae87478e0681899bf310a210cafc2c44 (diff) | |
download | cdo-1460904fd3c193ffaf809913b2983a400fce9d94.tar.gz cdo-1460904fd3c193ffaf809913b2983a400fce9d94.tar.xz cdo-1460904fd3c193ffaf809913b2983a400fce9d94.zip |
Fix line endings in master (dos2unix)
Diffstat (limited to 'plugins/org.eclipse.net4j.util/src')
280 files changed, 27727 insertions, 27727 deletions
diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java index d997a4969c..adfd4f55c1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractBundle.java @@ -1,456 +1,456 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.bundle;
-
-import org.eclipse.net4j.internal.util.om.pref.Preferences;
-import org.eclipse.net4j.util.ReflectUtil;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.om.OMBundle;
-import org.eclipse.net4j.util.om.OMPlatform;
-import org.eclipse.net4j.util.om.log.Logger;
-import org.eclipse.net4j.util.om.log.OMLogger;
-import org.eclipse.net4j.util.om.trace.OMTracer;
-import org.eclipse.net4j.util.om.trace.Tracer;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.text.MessageFormat;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.MissingResourceException;
-import java.util.Properties;
-import java.util.PropertyResourceBundle;
-import java.util.ResourceBundle;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Eike Stepper
- */
-public abstract class AbstractBundle implements OMBundle, OMBundle.DebugSupport, OMBundle.TranslationSupport
-{
- private static final String CLASS_EXTENSION = ".class";
-
- private AbstractPlatform platform;
-
- private String bundleID;
-
- private Class<?> accessor;
-
- private Object bundleContext;
-
- private boolean debugging;
-
- private boolean debuggingInitialized;
-
- private Map<String, Tracer> tracers = new ConcurrentHashMap<String, Tracer>(0);
-
- private OMLogger logger;
-
- private Preferences preferences;
-
- private ResourceBundle resourceBundle;
-
- private ResourceBundle untranslatedResourceBundle;
-
- private Map<String, String> strings = new HashMap<String, String>(0);
-
- private Map<String, String> untranslatedStrings = new HashMap<String, String>(0);
-
- private boolean shouldTranslate = true;
-
- public AbstractBundle(AbstractPlatform platform, String bundleID, Class<?> accessor)
- {
- this.platform = platform;
- this.bundleID = bundleID;
- this.accessor = accessor;
- }
-
- public OMPlatform getPlatform()
- {
- return platform;
- }
-
- public String getBundleID()
- {
- return bundleID;
- }
-
- public Class<?> getAccessor()
- {
- return accessor;
- }
-
- public Object getBundleContext()
- {
- return bundleContext;
- }
-
- @Deprecated
- public void setBundleContext(Object bundleContext)
- {
- this.bundleContext = bundleContext;
- }
-
- public DebugSupport getDebugSupport()
- {
- return this;
- }
-
- public TranslationSupport getTranslationSupport()
- {
- return this;
- }
-
- public boolean isDebugging()
- {
- if (!platform.isDebugging())
- {
- return false;
- }
-
- if (!debuggingInitialized)
- {
- debugging = getDebugOption("debug", false); //$NON-NLS-1$
- debuggingInitialized = true;
- }
-
- return debugging;
- }
-
- public void setDebugging(boolean debugging)
- {
- this.debugging = debugging;
- }
-
- public String getDebugOption(String option, String defaultValue)
- {
- String value = getDebugOption(option);
- return value == null ? defaultValue : value;
- }
-
- public boolean getDebugOption(String option, boolean defaultValue)
- {
- String value = getDebugOption(option);
- return value == null ? defaultValue : Boolean.parseBoolean(value);
- }
-
- public void setDebugOption(String option, boolean value)
- {
- setDebugOption(option, Boolean.toString(value));
- }
-
- public int getDebugOption(String option, int defaultValue)
- {
- try
- {
- String value = getDebugOption(option);
- return value == null ? defaultValue : Integer.parseInt(value);
- }
- catch (NumberFormatException e)
- {
- return defaultValue;
- }
- }
-
- public void setDebugOption(String option, int value)
- {
- setDebugOption(option, Integer.toString(value));
- }
-
- public String getDebugOption(String option)
- {
- return platform.getDebugOption(bundleID, option);
- }
-
- public void setDebugOption(String option, String value)
- {
- platform.setDebugOption(bundleID, option, value);
- }
-
- public synchronized OMTracer tracer(String name)
- {
- OMTracer tracer = tracers.get(name);
- if (tracer == null)
- {
- tracer = createTracer(name);
- }
-
- return tracer;
- }
-
- public synchronized OMLogger logger()
- {
- if (logger == null)
- {
- logger = createLogger();
- }
-
- return logger;
- }
-
- public File getConfigFile()
- {
- return platform.getConfigFile(getConfigFileName());
- }
-
- public Properties getConfigProperties()
- {
- return platform.getConfigProperties(getConfigFileName());
- }
-
- public synchronized Preferences preferences()
- {
- if (preferences == null)
- {
- preferences = new Preferences(this);
- }
-
- return preferences;
- }
-
- public InputStream getInputStream(String path) throws IOException
- {
- String base = getBaseURL().toString();
- if (!base.endsWith("/")) //$NON-NLS-1$
- {
- base += "/"; //$NON-NLS-1$
- }
-
- if (path.startsWith("/")) //$NON-NLS-1$
- {
- path = path.substring(1);
- }
-
- URL url = new URL(base + path);
- return url.openStream();
- }
-
- public boolean shouldTranslate()
- {
- return shouldTranslate;
- }
-
- public void setShouldTranslate(boolean shouldTranslate)
- {
- this.shouldTranslate = shouldTranslate;
- }
-
- public String getString(String key, boolean translate)
- {
- Map<String, String> stringMap = translate ? strings : untranslatedStrings;
- String result = stringMap.get(key);
- if (result == null)
- {
- ResourceBundle bundle = translate ? resourceBundle : untranslatedResourceBundle;
- if (bundle == null)
- {
- String packageName = ReflectUtil.getPackageName(accessor);
- if (translate)
- {
- try
- {
- bundle = resourceBundle = ResourceBundle.getBundle(packageName + ".plugin"); //$NON-NLS-1$
- }
- catch (MissingResourceException exception)
- {
- // If the bundle can't be found the normal way, try to find it as
- // the base URL. If that also doesn't work, rethrow the original
- // exception.
- InputStream inputStream = null;
- try
- {
- inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$
- bundle = new PropertyResourceBundle(inputStream);
- untranslatedResourceBundle = resourceBundle = bundle;
- inputStream.close();
- }
- catch (IOException ignore)
- {
- }
- finally
- {
- IOUtil.closeSilent(inputStream);
- }
-
- if (resourceBundle == null)
- {
- throw exception;
- }
- }
- }
- else
- {
- InputStream inputStream = null;
-
- try
- {
- inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$
- bundle = untranslatedResourceBundle = new PropertyResourceBundle(inputStream);
- inputStream.close();
- }
- catch (IOException ioException)
- {
- throw new MissingResourceException("Missing resource: plugin.properties", accessor //$NON-NLS-1$
- .getName(), key);
- }
- finally
- {
- IOUtil.closeSilent(inputStream);
- }
- }
- }
-
- result = bundle.getString(key);
- stringMap.put(key, result);
- }
-
- return result;
- }
-
- public String getString(String key)
- {
- return getString(key, shouldTranslate());
- }
-
- public String getString(String key, Object... args)
- {
- return getString(key, shouldTranslate(), args);
- }
-
- public String getString(String key, boolean translate, Object... args)
- {
- return MessageFormat.format(getString(key, translate), args);
- }
-
- @Override
- public String toString()
- {
- return bundleID;
- }
-
- public void start() throws Exception
- {
- invokeMethod("start"); //$NON-NLS-1$
- }
-
- public void stop() throws Exception
- {
- try
- {
- if (preferences != null)
- {
- preferences.save();
- }
- }
- catch (RuntimeException ex)
- {
- OM.LOG.error(ex);
- }
-
- invokeMethod("stop"); //$NON-NLS-1$
- }
-
- protected OMTracer createTracer(String name)
- {
- return new Tracer(this, name);
- }
-
- protected OMLogger createLogger()
- {
- return new Logger(this);
- }
-
- protected String getConfigFileName()
- {
- return bundleID + ".properties"; //$NON-NLS-1$
- }
-
- protected final Class<?> getClassFromBundle(String path)
- {
- if (path.endsWith(CLASS_EXTENSION))
- {
- int start = path.startsWith("/") ? 1 : 0;
- int end = path.length() - CLASS_EXTENSION.length();
- String className = path.substring(start, end).replace('/', '.');
-
- for (;;)
- {
- try
- {
- ClassLoader classLoader = getAccessor().getClassLoader();
- Class<?> c = classLoader.loadClass(className);
- if (c != null)
- {
- return c;
- }
- }
- catch (NoClassDefFoundError ex)
- {
- //$FALL-THROUGH$
- }
- catch (ClassNotFoundException ex)
- {
- //$FALL-THROUGH$
- }
-
- int dot = className.indexOf('.');
- if (dot == -1)
- {
- break;
- }
-
- className = className.substring(dot + 1);
- }
- }
-
- return null;
- }
-
- private void invokeMethod(String name) throws Exception
- {
- try
- {
- Method method = accessor.getDeclaredMethod(name, ReflectUtil.NO_PARAMETERS);
- if (!method.isAccessible())
- {
- method.setAccessible(true);
- }
-
- method.invoke(null, ReflectUtil.NO_ARGUMENTS);
- }
- catch (NoSuchMethodException ignore)
- {
- }
- catch (IllegalAccessException ignore)
- {
- }
- catch (InvocationTargetException ex)
- {
- Throwable targetException = ex.getTargetException();
- if (targetException instanceof Exception)
- {
- throw (Exception)targetException;
- }
- else if (targetException instanceof Error)
- {
- throw (Error)targetException;
- }
- else
- {
- OM.LOG.error(targetException);
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.bundle; + +import org.eclipse.net4j.internal.util.om.pref.Preferences; +import org.eclipse.net4j.util.ReflectUtil; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.om.OMBundle; +import org.eclipse.net4j.util.om.OMPlatform; +import org.eclipse.net4j.util.om.log.Logger; +import org.eclipse.net4j.util.om.log.OMLogger; +import org.eclipse.net4j.util.om.trace.OMTracer; +import org.eclipse.net4j.util.om.trace.Tracer; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.URL; +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.Properties; +import java.util.PropertyResourceBundle; +import java.util.ResourceBundle; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author Eike Stepper + */ +public abstract class AbstractBundle implements OMBundle, OMBundle.DebugSupport, OMBundle.TranslationSupport +{ + private static final String CLASS_EXTENSION = ".class"; + + private AbstractPlatform platform; + + private String bundleID; + + private Class<?> accessor; + + private Object bundleContext; + + private boolean debugging; + + private boolean debuggingInitialized; + + private Map<String, Tracer> tracers = new ConcurrentHashMap<String, Tracer>(0); + + private OMLogger logger; + + private Preferences preferences; + + private ResourceBundle resourceBundle; + + private ResourceBundle untranslatedResourceBundle; + + private Map<String, String> strings = new HashMap<String, String>(0); + + private Map<String, String> untranslatedStrings = new HashMap<String, String>(0); + + private boolean shouldTranslate = true; + + public AbstractBundle(AbstractPlatform platform, String bundleID, Class<?> accessor) + { + this.platform = platform; + this.bundleID = bundleID; + this.accessor = accessor; + } + + public OMPlatform getPlatform() + { + return platform; + } + + public String getBundleID() + { + return bundleID; + } + + public Class<?> getAccessor() + { + return accessor; + } + + public Object getBundleContext() + { + return bundleContext; + } + + @Deprecated + public void setBundleContext(Object bundleContext) + { + this.bundleContext = bundleContext; + } + + public DebugSupport getDebugSupport() + { + return this; + } + + public TranslationSupport getTranslationSupport() + { + return this; + } + + public boolean isDebugging() + { + if (!platform.isDebugging()) + { + return false; + } + + if (!debuggingInitialized) + { + debugging = getDebugOption("debug", false); //$NON-NLS-1$ + debuggingInitialized = true; + } + + return debugging; + } + + public void setDebugging(boolean debugging) + { + this.debugging = debugging; + } + + public String getDebugOption(String option, String defaultValue) + { + String value = getDebugOption(option); + return value == null ? defaultValue : value; + } + + public boolean getDebugOption(String option, boolean defaultValue) + { + String value = getDebugOption(option); + return value == null ? defaultValue : Boolean.parseBoolean(value); + } + + public void setDebugOption(String option, boolean value) + { + setDebugOption(option, Boolean.toString(value)); + } + + public int getDebugOption(String option, int defaultValue) + { + try + { + String value = getDebugOption(option); + return value == null ? defaultValue : Integer.parseInt(value); + } + catch (NumberFormatException e) + { + return defaultValue; + } + } + + public void setDebugOption(String option, int value) + { + setDebugOption(option, Integer.toString(value)); + } + + public String getDebugOption(String option) + { + return platform.getDebugOption(bundleID, option); + } + + public void setDebugOption(String option, String value) + { + platform.setDebugOption(bundleID, option, value); + } + + public synchronized OMTracer tracer(String name) + { + OMTracer tracer = tracers.get(name); + if (tracer == null) + { + tracer = createTracer(name); + } + + return tracer; + } + + public synchronized OMLogger logger() + { + if (logger == null) + { + logger = createLogger(); + } + + return logger; + } + + public File getConfigFile() + { + return platform.getConfigFile(getConfigFileName()); + } + + public Properties getConfigProperties() + { + return platform.getConfigProperties(getConfigFileName()); + } + + public synchronized Preferences preferences() + { + if (preferences == null) + { + preferences = new Preferences(this); + } + + return preferences; + } + + public InputStream getInputStream(String path) throws IOException + { + String base = getBaseURL().toString(); + if (!base.endsWith("/")) //$NON-NLS-1$ + { + base += "/"; //$NON-NLS-1$ + } + + if (path.startsWith("/")) //$NON-NLS-1$ + { + path = path.substring(1); + } + + URL url = new URL(base + path); + return url.openStream(); + } + + public boolean shouldTranslate() + { + return shouldTranslate; + } + + public void setShouldTranslate(boolean shouldTranslate) + { + this.shouldTranslate = shouldTranslate; + } + + public String getString(String key, boolean translate) + { + Map<String, String> stringMap = translate ? strings : untranslatedStrings; + String result = stringMap.get(key); + if (result == null) + { + ResourceBundle bundle = translate ? resourceBundle : untranslatedResourceBundle; + if (bundle == null) + { + String packageName = ReflectUtil.getPackageName(accessor); + if (translate) + { + try + { + bundle = resourceBundle = ResourceBundle.getBundle(packageName + ".plugin"); //$NON-NLS-1$ + } + catch (MissingResourceException exception) + { + // If the bundle can't be found the normal way, try to find it as + // the base URL. If that also doesn't work, rethrow the original + // exception. + InputStream inputStream = null; + try + { + inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$ + bundle = new PropertyResourceBundle(inputStream); + untranslatedResourceBundle = resourceBundle = bundle; + inputStream.close(); + } + catch (IOException ignore) + { + } + finally + { + IOUtil.closeSilent(inputStream); + } + + if (resourceBundle == null) + { + throw exception; + } + } + } + else + { + InputStream inputStream = null; + + try + { + inputStream = getInputStream("plugin.properties"); //$NON-NLS-1$ + bundle = untranslatedResourceBundle = new PropertyResourceBundle(inputStream); + inputStream.close(); + } + catch (IOException ioException) + { + throw new MissingResourceException("Missing resource: plugin.properties", accessor //$NON-NLS-1$ + .getName(), key); + } + finally + { + IOUtil.closeSilent(inputStream); + } + } + } + + result = bundle.getString(key); + stringMap.put(key, result); + } + + return result; + } + + public String getString(String key) + { + return getString(key, shouldTranslate()); + } + + public String getString(String key, Object... args) + { + return getString(key, shouldTranslate(), args); + } + + public String getString(String key, boolean translate, Object... args) + { + return MessageFormat.format(getString(key, translate), args); + } + + @Override + public String toString() + { + return bundleID; + } + + public void start() throws Exception + { + invokeMethod("start"); //$NON-NLS-1$ + } + + public void stop() throws Exception + { + try + { + if (preferences != null) + { + preferences.save(); + } + } + catch (RuntimeException ex) + { + OM.LOG.error(ex); + } + + invokeMethod("stop"); //$NON-NLS-1$ + } + + protected OMTracer createTracer(String name) + { + return new Tracer(this, name); + } + + protected OMLogger createLogger() + { + return new Logger(this); + } + + protected String getConfigFileName() + { + return bundleID + ".properties"; //$NON-NLS-1$ + } + + protected final Class<?> getClassFromBundle(String path) + { + if (path.endsWith(CLASS_EXTENSION)) + { + int start = path.startsWith("/") ? 1 : 0; + int end = path.length() - CLASS_EXTENSION.length(); + String className = path.substring(start, end).replace('/', '.'); + + for (;;) + { + try + { + ClassLoader classLoader = getAccessor().getClassLoader(); + Class<?> c = classLoader.loadClass(className); + if (c != null) + { + return c; + } + } + catch (NoClassDefFoundError ex) + { + //$FALL-THROUGH$ + } + catch (ClassNotFoundException ex) + { + //$FALL-THROUGH$ + } + + int dot = className.indexOf('.'); + if (dot == -1) + { + break; + } + + className = className.substring(dot + 1); + } + } + + return null; + } + + private void invokeMethod(String name) throws Exception + { + try + { + Method method = accessor.getDeclaredMethod(name, ReflectUtil.NO_PARAMETERS); + if (!method.isAccessible()) + { + method.setAccessible(true); + } + + method.invoke(null, ReflectUtil.NO_ARGUMENTS); + } + catch (NoSuchMethodException ignore) + { + } + catch (IllegalAccessException ignore) + { + } + catch (InvocationTargetException ex) + { + Throwable targetException = ex.getTargetException(); + if (targetException instanceof Exception) + { + throw (Exception)targetException; + } + else if (targetException instanceof Error) + { + throw (Error)targetException; + } + else + { + OM.LOG.error(targetException); + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java index 7d0aef5db7..dd5f24bd8e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/AbstractPlatform.java @@ -1,380 +1,380 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.bundle;
-
-import org.eclipse.net4j.internal.util.om.LegacyPlatform;
-import org.eclipse.net4j.internal.util.om.OSGiPlatform;
-import org.eclipse.net4j.util.collection.ConcurrentArray;
-import org.eclipse.net4j.util.io.IORuntimeException;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.om.OMBundle;
-import org.eclipse.net4j.util.om.OMPlatform;
-import org.eclipse.net4j.util.om.log.OMLogFilter;
-import org.eclipse.net4j.util.om.log.OMLogHandler;
-import org.eclipse.net4j.util.om.log.OMLogger;
-import org.eclipse.net4j.util.om.log.OMLogger.Level;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-import org.eclipse.net4j.util.om.trace.OMTraceHandler;
-import org.eclipse.net4j.util.om.trace.OMTraceHandlerEvent;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.URI;
-import java.util.Map;
-import java.util.Properties;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Eike Stepper
- */
-public abstract class AbstractPlatform implements OMPlatform
-{
- public static final String SYSTEM_PROPERTY_OSGI_STATE = "osgi.instance.area"; //$NON-NLS-1$
-
- public static final String SYSTEM_PROPERTY_NET4J_STATE = "net4j.state"; //$NON-NLS-1$
-
- public static final String SYSTEM_PROPERTY_NET4J_CONFIG = "net4j.config"; //$NON-NLS-1$
-
- static Object systemContext;
-
- private static ContextTracer __TRACER__;
-
- private Map<String, AbstractBundle> bundles = new ConcurrentHashMap<String, AbstractBundle>(0);
-
- private ConcurrentArray<OMLogFilter> logFilters = new ConcurrentArray.Unique<OMLogFilter>()
- {
- @Override
- protected OMLogFilter[] newArray(int length)
- {
- return new OMLogFilter[length];
- }
- };
-
- private ConcurrentArray<OMLogHandler> logHandlers = new ConcurrentArray.Unique<OMLogHandler>()
- {
- @Override
- protected OMLogHandler[] newArray(int length)
- {
- return new OMLogHandler[length];
- }
- };
-
- private ConcurrentArray<OMTraceHandler> traceHandlers = new ConcurrentArray.Unique<OMTraceHandler>()
- {
- @Override
- protected OMTraceHandler[] newArray(int length)
- {
- return new OMTraceHandler[length];
- }
- };
-
- private boolean debugging;
-
- protected AbstractPlatform()
- {
- debugging = Boolean.parseBoolean(getProperty("debug", "false")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public synchronized OMBundle bundle(String bundleID, Class<?> accessor)
- {
- OMBundle bundle = bundles.get(bundleID);
- if (bundle == null)
- {
- bundle = createBundle(bundleID, accessor);
- }
-
- return bundle;
- }
-
- public void addLogFilter(OMLogFilter logFilter)
- {
- logFilters.add(logFilter);
- }
-
- public void removeLogFilter(OMLogFilter logFilter)
- {
- logFilters.remove(logFilter);
- }
-
- public void addLogHandler(OMLogHandler logHandler)
- {
- logHandlers.add(logHandler);
- }
-
- public void removeLogHandler(OMLogHandler logHandler)
- {
- logHandlers.remove(logHandler);
- }
-
- public void addTraceHandler(OMTraceHandler traceHandler)
- {
- traceHandlers.add(traceHandler);
- }
-
- public void removeTraceHandler(OMTraceHandler traceHandler)
- {
- traceHandlers.remove(traceHandler);
- }
-
- public boolean isExtensionRegistryAvailable()
- {
- try
- {
- return internalExtensionRegistryAvailable();
- }
- catch (Throwable ex)
- {
- return false;
- }
- }
-
- public boolean isDebugging()
- {
- return debugging;
- }
-
- public void setDebugging(boolean debugging)
- {
- this.debugging = debugging;
- }
-
- public File getStateFolder()
- {
- String state = getProperty(SYSTEM_PROPERTY_NET4J_STATE);
- if (state == null)
- {
- state = getProperty(SYSTEM_PROPERTY_OSGI_STATE);
- if (state == null)
- {
- state = "state"; //$NON-NLS-1$
- }
- else
- {
- try
- {
- URI uri = new URI(state);
- state = new File(new File(uri), ".metadata").getAbsolutePath(); //$NON-NLS-1$;
- }
- catch (Exception ex)
- {
- OM.LOG.error("Property " + SYSTEM_PROPERTY_OSGI_STATE + " is not a proper file URI: " + state); //$NON-NLS-1$ //$NON-NLS-2$
- state = "state"; //$NON-NLS-1$
- }
- }
- }
-
- File stateFolder = new File(state);
- if (!stateFolder.exists())
- {
- if (!stateFolder.mkdirs())
- {
- throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- if (!stateFolder.isDirectory())
- {
- throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return stateFolder;
- }
-
- public File getConfigFolder()
- {
- String config = getProperty(SYSTEM_PROPERTY_NET4J_CONFIG, "config"); //$NON-NLS-1$
- File configFolder = new File(config);
- if (!configFolder.exists())
- {
- if (!configFolder.mkdirs())
- {
- OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$
- return null;
- }
- }
-
- if (!configFolder.isDirectory())
- {
- OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$
- return null;
- }
-
- return configFolder;
- }
-
- public File getConfigFile(String name)
- {
- File configFolder = getConfigFolder();
- if (configFolder == null)
- {
- return null;
- }
-
- return new File(configFolder, name);
- }
-
- public Properties getConfigProperties(String name)
- {
- File configFile = getConfigFile(name);
- if (configFile == null)
- {
- return null;
- }
-
- FileInputStream fis = null;
- try
- {
- fis = new FileInputStream(configFile);
- Properties properties = new Properties();
- properties.load(fis);
- return properties;
- }
- catch (IOException ex)
- {
- OM.LOG.error("Config file " + configFile.getAbsolutePath() + " could not be read"); //$NON-NLS-1$ //$NON-NLS-2$
- return null;
- }
- finally
- {
- IOUtil.closeSilent(fis);
- }
- }
-
- public void log(OMLogger logger, Level level, String msg, Throwable t)
- {
- if (!logFilters.isEmpty())
- {
- for (OMLogFilter logFilter : logFilters.get())
- {
- try
- {
- if (logFilter.filter(logger, level, msg, t))
- {
- if (TRACER().isEnabled())
- {
- TRACER().format("Filtered log event: logger={0}, level={1}, msg={2}\n{3}", logger, level, msg, t);
- }
-
- return;
- }
- }
- catch (Exception ex)
- {
- if (TRACER().isEnabled())
- {
- TRACER().trace(ex);
- }
- }
- }
- }
-
- if (!logHandlers.isEmpty())
- {
- for (OMLogHandler logHandler : logHandlers.get())
- {
- try
- {
- logHandler.logged(logger, level, msg, t);
- }
- catch (Exception ex)
- {
- if (TRACER().isEnabled())
- {
- TRACER().trace(ex);
- }
- }
- }
- }
- }
-
- public void trace(OMTraceHandlerEvent event)
- {
- if (!traceHandlers.isEmpty())
- {
- for (OMTraceHandler traceHandler : traceHandlers.get())
- {
- try
- {
- traceHandler.traced(event);
- }
- catch (Exception ex)
- {
- if (TRACER().isEnabled())
- {
- TRACER().trace(ex);
- }
- }
- }
- }
- }
-
- protected Map<String, AbstractBundle> getBundles()
- {
- return bundles;
- }
-
- public String getProperty(String key)
- {
- return System.getProperty(key);
- }
-
- public String getProperty(String key, String defaultValue)
- {
- return System.getProperty(key, defaultValue);
- }
-
- protected abstract OMBundle createBundle(String bundleID, Class<?> accessor);
-
- protected abstract String getDebugOption(String bundleID, String option);
-
- protected abstract void setDebugOption(String bundleID, String option, String value);
-
- /**
- * TODO Make configurable via system property
- */
- public static synchronized OMPlatform createPlatform()
- {
- try
- {
- if (systemContext != null)
- {
- return new OSGiPlatform(systemContext);
- }
-
- return new LegacyPlatform();
- }
- catch (Exception ex)
- {
- if (TRACER().isEnabled())
- {
- TRACER().trace(ex);
- }
- }
-
- return null;
- }
-
- private static ContextTracer TRACER()
- {
- if (__TRACER__ == null)
- {
- __TRACER__ = new ContextTracer(OM.DEBUG_OM, AbstractPlatform.class);
- }
-
- return __TRACER__;
- }
-
- private static boolean internalExtensionRegistryAvailable() throws Throwable
- {
- return org.eclipse.core.runtime.Platform.getExtensionRegistry() != null;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.bundle; + +import org.eclipse.net4j.internal.util.om.LegacyPlatform; +import org.eclipse.net4j.internal.util.om.OSGiPlatform; +import org.eclipse.net4j.util.collection.ConcurrentArray; +import org.eclipse.net4j.util.io.IORuntimeException; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.om.OMBundle; +import org.eclipse.net4j.util.om.OMPlatform; +import org.eclipse.net4j.util.om.log.OMLogFilter; +import org.eclipse.net4j.util.om.log.OMLogHandler; +import org.eclipse.net4j.util.om.log.OMLogger; +import org.eclipse.net4j.util.om.log.OMLogger.Level; +import org.eclipse.net4j.util.om.trace.ContextTracer; +import org.eclipse.net4j.util.om.trace.OMTraceHandler; +import org.eclipse.net4j.util.om.trace.OMTraceHandlerEvent; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author Eike Stepper + */ +public abstract class AbstractPlatform implements OMPlatform +{ + public static final String SYSTEM_PROPERTY_OSGI_STATE = "osgi.instance.area"; //$NON-NLS-1$ + + public static final String SYSTEM_PROPERTY_NET4J_STATE = "net4j.state"; //$NON-NLS-1$ + + public static final String SYSTEM_PROPERTY_NET4J_CONFIG = "net4j.config"; //$NON-NLS-1$ + + static Object systemContext; + + private static ContextTracer __TRACER__; + + private Map<String, AbstractBundle> bundles = new ConcurrentHashMap<String, AbstractBundle>(0); + + private ConcurrentArray<OMLogFilter> logFilters = new ConcurrentArray.Unique<OMLogFilter>() + { + @Override + protected OMLogFilter[] newArray(int length) + { + return new OMLogFilter[length]; + } + }; + + private ConcurrentArray<OMLogHandler> logHandlers = new ConcurrentArray.Unique<OMLogHandler>() + { + @Override + protected OMLogHandler[] newArray(int length) + { + return new OMLogHandler[length]; + } + }; + + private ConcurrentArray<OMTraceHandler> traceHandlers = new ConcurrentArray.Unique<OMTraceHandler>() + { + @Override + protected OMTraceHandler[] newArray(int length) + { + return new OMTraceHandler[length]; + } + }; + + private boolean debugging; + + protected AbstractPlatform() + { + debugging = Boolean.parseBoolean(getProperty("debug", "false")); //$NON-NLS-1$ //$NON-NLS-2$ + } + + public synchronized OMBundle bundle(String bundleID, Class<?> accessor) + { + OMBundle bundle = bundles.get(bundleID); + if (bundle == null) + { + bundle = createBundle(bundleID, accessor); + } + + return bundle; + } + + public void addLogFilter(OMLogFilter logFilter) + { + logFilters.add(logFilter); + } + + public void removeLogFilter(OMLogFilter logFilter) + { + logFilters.remove(logFilter); + } + + public void addLogHandler(OMLogHandler logHandler) + { + logHandlers.add(logHandler); + } + + public void removeLogHandler(OMLogHandler logHandler) + { + logHandlers.remove(logHandler); + } + + public void addTraceHandler(OMTraceHandler traceHandler) + { + traceHandlers.add(traceHandler); + } + + public void removeTraceHandler(OMTraceHandler traceHandler) + { + traceHandlers.remove(traceHandler); + } + + public boolean isExtensionRegistryAvailable() + { + try + { + return internalExtensionRegistryAvailable(); + } + catch (Throwable ex) + { + return false; + } + } + + public boolean isDebugging() + { + return debugging; + } + + public void setDebugging(boolean debugging) + { + this.debugging = debugging; + } + + public File getStateFolder() + { + String state = getProperty(SYSTEM_PROPERTY_NET4J_STATE); + if (state == null) + { + state = getProperty(SYSTEM_PROPERTY_OSGI_STATE); + if (state == null) + { + state = "state"; //$NON-NLS-1$ + } + else + { + try + { + URI uri = new URI(state); + state = new File(new File(uri), ".metadata").getAbsolutePath(); //$NON-NLS-1$; + } + catch (Exception ex) + { + OM.LOG.error("Property " + SYSTEM_PROPERTY_OSGI_STATE + " is not a proper file URI: " + state); //$NON-NLS-1$ //$NON-NLS-2$ + state = "state"; //$NON-NLS-1$ + } + } + } + + File stateFolder = new File(state); + if (!stateFolder.exists()) + { + if (!stateFolder.mkdirs()) + { + throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + if (!stateFolder.isDirectory()) + { + throw new IORuntimeException("State folder " + stateFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + return stateFolder; + } + + public File getConfigFolder() + { + String config = getProperty(SYSTEM_PROPERTY_NET4J_CONFIG, "config"); //$NON-NLS-1$ + File configFolder = new File(config); + if (!configFolder.exists()) + { + if (!configFolder.mkdirs()) + { + OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " could not be created"); //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } + } + + if (!configFolder.isDirectory()) + { + OM.LOG.error("Config folder " + configFolder.getAbsolutePath() + " is not a directoy"); //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } + + return configFolder; + } + + public File getConfigFile(String name) + { + File configFolder = getConfigFolder(); + if (configFolder == null) + { + return null; + } + + return new File(configFolder, name); + } + + public Properties getConfigProperties(String name) + { + File configFile = getConfigFile(name); + if (configFile == null) + { + return null; + } + + FileInputStream fis = null; + try + { + fis = new FileInputStream(configFile); + Properties properties = new Properties(); + properties.load(fis); + return properties; + } + catch (IOException ex) + { + OM.LOG.error("Config file " + configFile.getAbsolutePath() + " could not be read"); //$NON-NLS-1$ //$NON-NLS-2$ + return null; + } + finally + { + IOUtil.closeSilent(fis); + } + } + + public void log(OMLogger logger, Level level, String msg, Throwable t) + { + if (!logFilters.isEmpty()) + { + for (OMLogFilter logFilter : logFilters.get()) + { + try + { + if (logFilter.filter(logger, level, msg, t)) + { + if (TRACER().isEnabled()) + { + TRACER().format("Filtered log event: logger={0}, level={1}, msg={2}\n{3}", logger, level, msg, t); + } + + return; + } + } + catch (Exception ex) + { + if (TRACER().isEnabled()) + { + TRACER().trace(ex); + } + } + } + } + + if (!logHandlers.isEmpty()) + { + for (OMLogHandler logHandler : logHandlers.get()) + { + try + { + logHandler.logged(logger, level, msg, t); + } + catch (Exception ex) + { + if (TRACER().isEnabled()) + { + TRACER().trace(ex); + } + } + } + } + } + + public void trace(OMTraceHandlerEvent event) + { + if (!traceHandlers.isEmpty()) + { + for (OMTraceHandler traceHandler : traceHandlers.get()) + { + try + { + traceHandler.traced(event); + } + catch (Exception ex) + { + if (TRACER().isEnabled()) + { + TRACER().trace(ex); + } + } + } + } + } + + protected Map<String, AbstractBundle> getBundles() + { + return bundles; + } + + public String getProperty(String key) + { + return System.getProperty(key); + } + + public String getProperty(String key, String defaultValue) + { + return System.getProperty(key, defaultValue); + } + + protected abstract OMBundle createBundle(String bundleID, Class<?> accessor); + + protected abstract String getDebugOption(String bundleID, String option); + + protected abstract void setDebugOption(String bundleID, String option, String value); + + /** + * TODO Make configurable via system property + */ + public static synchronized OMPlatform createPlatform() + { + try + { + if (systemContext != null) + { + return new OSGiPlatform(systemContext); + } + + return new LegacyPlatform(); + } + catch (Exception ex) + { + if (TRACER().isEnabled()) + { + TRACER().trace(ex); + } + } + + return null; + } + + private static ContextTracer TRACER() + { + if (__TRACER__ == null) + { + __TRACER__ = new ContextTracer(OM.DEBUG_OM, AbstractPlatform.class); + } + + return __TRACER__; + } + + private static boolean internalExtensionRegistryAvailable() throws Throwable + { + return org.eclipse.core.runtime.Platform.getExtensionRegistry() != null; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java index d9cb9960d5..7e50f80d26 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/bundle/OM.java @@ -1,105 +1,105 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.bundle;
-
-import org.eclipse.net4j.internal.util.container.PluginContainer;
-import org.eclipse.net4j.internal.util.om.OSGiBundle;
-import org.eclipse.net4j.util.container.IPluginContainer;
-import org.eclipse.net4j.util.om.OMBundle;
-import org.eclipse.net4j.util.om.OMPlatform;
-import org.eclipse.net4j.util.om.OSGiActivator;
-import org.eclipse.net4j.util.om.log.EclipseLoggingBridge;
-import org.eclipse.net4j.util.om.log.OMLogger;
-import org.eclipse.net4j.util.om.log.PrintLogHandler;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-import org.eclipse.net4j.util.om.trace.OMTracer;
-import org.eclipse.net4j.util.om.trace.PrintTraceHandler;
-
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-/**
- * The <em>Operations & Maintenance</em> class of this bundle.
- *
- * @author Eike Stepper
- */
-public abstract class OM
-{
- public static final String BUNDLE_ID = "org.eclipse.net4j.util"; //$NON-NLS-1$
-
- public static final OMBundle BUNDLE = OMPlatform.INSTANCE.bundle(BUNDLE_ID, OM.class);
-
- public static final OMTracer DEBUG = BUNDLE.tracer("debug"); //$NON-NLS-1$
-
- public static final OMTracer DEBUG_LIFECYCLE = DEBUG.tracer("lifecycle"); //$NON-NLS-1$
-
- public static final OMTracer DEBUG_LIFECYCLE_DUMP = DEBUG_LIFECYCLE.tracer("dump"); //$NON-NLS-1$
-
- public static final OMTracer DEBUG_CONCURRENCY = DEBUG.tracer("concurrency"); //$NON-NLS-1$
-
- public static final OMTracer DEBUG_REGISTRY = DEBUG.tracer("registry"); //$NON-NLS-1$
-
- public static final OMTracer DEBUG_OM = DEBUG.tracer("om"); //$NON-NLS-1$
-
- public static final OMTracer DEBUG_MONITOR = DEBUG_OM.tracer("monitor"); //$NON-NLS-1$
-
- public static final OMLogger LOG = BUNDLE.logger();
-
- public static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OM.class);
-
- /**
- * @author Eike Stepper
- */
- public static final class Activator implements BundleActivator
- {
- public void start(BundleContext context) throws Exception
- {
- AbstractPlatform.systemContext = context;
- setBundleContext(context);
- ((OSGiBundle)OM.BUNDLE).start();
-
- // TODO Make configurable
- PrintTraceHandler.CONSOLE.setPattern("{6} [{0}] {5}"); //$NON-NLS-1$
- AbstractPlatform.INSTANCE.addTraceHandler(PrintTraceHandler.CONSOLE);
- AbstractPlatform.INSTANCE.addLogHandler(PrintLogHandler.CONSOLE);
-
- try
- {
- AbstractPlatform.INSTANCE.addLogHandler(EclipseLoggingBridge.INSTANCE);
- }
- catch (Throwable ignore)
- {
- }
-
- OSGiActivator.traceStart(context);
- IPluginContainer container = IPluginContainer.INSTANCE;
- if (TRACER.isEnabled())
- {
- TRACER.format("Plugin container created: {0}", container); //$NON-NLS-1$
- }
- }
-
- public void stop(BundleContext context) throws Exception
- {
- OSGiActivator.traceStop(context);
- ((OSGiBundle)OM.BUNDLE).stop();
- PluginContainer.dispose();
- setBundleContext(null);
- AbstractPlatform.systemContext = null;
- }
-
- @SuppressWarnings("deprecation")
- private void setBundleContext(BundleContext context)
- {
- OM.BUNDLE.setBundleContext(context);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.bundle; + +import org.eclipse.net4j.internal.util.container.PluginContainer; +import org.eclipse.net4j.internal.util.om.OSGiBundle; +import org.eclipse.net4j.util.container.IPluginContainer; +import org.eclipse.net4j.util.om.OMBundle; +import org.eclipse.net4j.util.om.OMPlatform; +import org.eclipse.net4j.util.om.OSGiActivator; +import org.eclipse.net4j.util.om.log.EclipseLoggingBridge; +import org.eclipse.net4j.util.om.log.OMLogger; +import org.eclipse.net4j.util.om.log.PrintLogHandler; +import org.eclipse.net4j.util.om.trace.ContextTracer; +import org.eclipse.net4j.util.om.trace.OMTracer; +import org.eclipse.net4j.util.om.trace.PrintTraceHandler; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** + * The <em>Operations & Maintenance</em> class of this bundle. + * + * @author Eike Stepper + */ +public abstract class OM +{ + public static final String BUNDLE_ID = "org.eclipse.net4j.util"; //$NON-NLS-1$ + + public static final OMBundle BUNDLE = OMPlatform.INSTANCE.bundle(BUNDLE_ID, OM.class); + + public static final OMTracer DEBUG = BUNDLE.tracer("debug"); //$NON-NLS-1$ + + public static final OMTracer DEBUG_LIFECYCLE = DEBUG.tracer("lifecycle"); //$NON-NLS-1$ + + public static final OMTracer DEBUG_LIFECYCLE_DUMP = DEBUG_LIFECYCLE.tracer("dump"); //$NON-NLS-1$ + + public static final OMTracer DEBUG_CONCURRENCY = DEBUG.tracer("concurrency"); //$NON-NLS-1$ + + public static final OMTracer DEBUG_REGISTRY = DEBUG.tracer("registry"); //$NON-NLS-1$ + + public static final OMTracer DEBUG_OM = DEBUG.tracer("om"); //$NON-NLS-1$ + + public static final OMTracer DEBUG_MONITOR = DEBUG_OM.tracer("monitor"); //$NON-NLS-1$ + + public static final OMLogger LOG = BUNDLE.logger(); + + public static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OM.class); + + /** + * @author Eike Stepper + */ + public static final class Activator implements BundleActivator + { + public void start(BundleContext context) throws Exception + { + AbstractPlatform.systemContext = context; + setBundleContext(context); + ((OSGiBundle)OM.BUNDLE).start(); + + // TODO Make configurable + PrintTraceHandler.CONSOLE.setPattern("{6} [{0}] {5}"); //$NON-NLS-1$ + AbstractPlatform.INSTANCE.addTraceHandler(PrintTraceHandler.CONSOLE); + AbstractPlatform.INSTANCE.addLogHandler(PrintLogHandler.CONSOLE); + + try + { + AbstractPlatform.INSTANCE.addLogHandler(EclipseLoggingBridge.INSTANCE); + } + catch (Throwable ignore) + { + } + + OSGiActivator.traceStart(context); + IPluginContainer container = IPluginContainer.INSTANCE; + if (TRACER.isEnabled()) + { + TRACER.format("Plugin container created: {0}", container); //$NON-NLS-1$ + } + } + + public void stop(BundleContext context) throws Exception + { + OSGiActivator.traceStop(context); + ((OSGiBundle)OM.BUNDLE).stop(); + PluginContainer.dispose(); + setBundleContext(null); + AbstractPlatform.systemContext = null; + } + + @SuppressWarnings("deprecation") + private void setBundleContext(BundleContext context) + { + OM.BUNDLE.setBundleContext(context); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java index 8fa5704f59..1c1e5349d8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginElementProcessorList.java @@ -1,253 +1,253 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.container;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.container.IElementProcessor;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-
-import org.eclipse.core.runtime.CoreException;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-
-/**
- * @author Eike Stepper
- */
-public class PluginElementProcessorList extends Lifecycle implements List<IElementProcessor>
-{
- private static final String ATTR_CLASS = "class"; //$NON-NLS-1$
-
- public static final String NAMESPACE = OM.BUNDLE_ID;
-
- public static final String EXT_POINT = "elementProcessors"; //$NON-NLS-1$
-
- private List<IElementProcessor> processors = new ArrayList<IElementProcessor>();
-
- private Object extensionRegistryListener;
-
- public PluginElementProcessorList()
- {
- }
-
- public boolean add(IElementProcessor o)
- {
- return processors.add(o);
- }
-
- public void add(int index, IElementProcessor element)
- {
- processors.add(index, element);
- }
-
- public boolean addAll(Collection<? extends IElementProcessor> c)
- {
- return processors.addAll(c);
- }
-
- public boolean addAll(int index, Collection<? extends IElementProcessor> c)
- {
- return processors.addAll(index, c);
- }
-
- public void clear()
- {
- processors.clear();
- }
-
- public boolean contains(Object o)
- {
- return processors.contains(o);
- }
-
- public boolean containsAll(Collection<?> c)
- {
- return processors.containsAll(c);
- }
-
- @Override
- public boolean equals(Object o)
- {
- return processors.equals(o);
- }
-
- public IElementProcessor get(int index)
- {
- return processors.get(index);
- }
-
- @Override
- public int hashCode()
- {
- return processors.hashCode();
- }
-
- public int indexOf(Object o)
- {
- return processors.indexOf(o);
- }
-
- public boolean isEmpty()
- {
- return processors.isEmpty();
- }
-
- public Iterator<IElementProcessor> iterator()
- {
- return processors.iterator();
- }
-
- public int lastIndexOf(Object o)
- {
- return processors.lastIndexOf(o);
- }
-
- public ListIterator<IElementProcessor> listIterator()
- {
- return processors.listIterator();
- }
-
- public ListIterator<IElementProcessor> listIterator(int index)
- {
- return processors.listIterator(index);
- }
-
- public IElementProcessor remove(int index)
- {
- return processors.remove(index);
- }
-
- public boolean remove(Object o)
- {
- return processors.remove(o);
- }
-
- public boolean removeAll(Collection<?> c)
- {
- return processors.removeAll(c);
- }
-
- public boolean retainAll(Collection<?> c)
- {
- return processors.retainAll(c);
- }
-
- public IElementProcessor set(int index, IElementProcessor element)
- {
- return processors.set(index, element);
- }
-
- public int size()
- {
- return processors.size();
- }
-
- public List<IElementProcessor> subList(int fromIndex, int toIndex)
- {
- return processors.subList(fromIndex, toIndex);
- }
-
- public Object[] toArray()
- {
- return processors.toArray();
- }
-
- public <T> T[] toArray(T[] a)
- {
- return processors.toArray(a);
- }
-
- @Override
- public String toString()
- {
- return processors.toString();
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- try
- {
- doActivateOSGi();
- }
- catch (Throwable t)
- {
- OM.LOG.warn(t);
- }
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- try
- {
- doDeactivateOSGi();
- }
- catch (Throwable t)
- {
- OM.LOG.warn(t);
- }
-
- processors.clear();
- super.doDeactivate();
- }
-
- private void doActivateOSGi() throws CoreException
- {
- org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
- .getExtensionRegistry();
- if (extensionRegistry == null)
- {
- return;
- }
-
- org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor(
- NAMESPACE, EXT_POINT);
- for (org.eclipse.core.runtime.IConfigurationElement element : elements)
- {
- IElementProcessor processor = (IElementProcessor)element.createExecutableExtension(ATTR_CLASS);
- processors.add(processor);
- }
-
- org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener()
- {
- public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event)
- {
- org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT);
- for (org.eclipse.core.runtime.IExtensionDelta delta : deltas)
- {
- // TODO Handle ExtensionDelta
- OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$
- }
- }
- };
-
- extensionRegistry.addRegistryChangeListener(listener, NAMESPACE);
- extensionRegistryListener = listener;
- }
-
- private void doDeactivateOSGi()
- {
- org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
- .getExtensionRegistry();
- if (extensionRegistry == null)
- {
- return;
- }
-
- extensionRegistry
- .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.container; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.container.IElementProcessor; +import org.eclipse.net4j.util.lifecycle.Lifecycle; + +import org.eclipse.core.runtime.CoreException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +/** + * @author Eike Stepper + */ +public class PluginElementProcessorList extends Lifecycle implements List<IElementProcessor> +{ + private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ + + public static final String NAMESPACE = OM.BUNDLE_ID; + + public static final String EXT_POINT = "elementProcessors"; //$NON-NLS-1$ + + private List<IElementProcessor> processors = new ArrayList<IElementProcessor>(); + + private Object extensionRegistryListener; + + public PluginElementProcessorList() + { + } + + public boolean add(IElementProcessor o) + { + return processors.add(o); + } + + public void add(int index, IElementProcessor element) + { + processors.add(index, element); + } + + public boolean addAll(Collection<? extends IElementProcessor> c) + { + return processors.addAll(c); + } + + public boolean addAll(int index, Collection<? extends IElementProcessor> c) + { + return processors.addAll(index, c); + } + + public void clear() + { + processors.clear(); + } + + public boolean contains(Object o) + { + return processors.contains(o); + } + + public boolean containsAll(Collection<?> c) + { + return processors.containsAll(c); + } + + @Override + public boolean equals(Object o) + { + return processors.equals(o); + } + + public IElementProcessor get(int index) + { + return processors.get(index); + } + + @Override + public int hashCode() + { + return processors.hashCode(); + } + + public int indexOf(Object o) + { + return processors.indexOf(o); + } + + public boolean isEmpty() + { + return processors.isEmpty(); + } + + public Iterator<IElementProcessor> iterator() + { + return processors.iterator(); + } + + public int lastIndexOf(Object o) + { + return processors.lastIndexOf(o); + } + + public ListIterator<IElementProcessor> listIterator() + { + return processors.listIterator(); + } + + public ListIterator<IElementProcessor> listIterator(int index) + { + return processors.listIterator(index); + } + + public IElementProcessor remove(int index) + { + return processors.remove(index); + } + + public boolean remove(Object o) + { + return processors.remove(o); + } + + public boolean removeAll(Collection<?> c) + { + return processors.removeAll(c); + } + + public boolean retainAll(Collection<?> c) + { + return processors.retainAll(c); + } + + public IElementProcessor set(int index, IElementProcessor element) + { + return processors.set(index, element); + } + + public int size() + { + return processors.size(); + } + + public List<IElementProcessor> subList(int fromIndex, int toIndex) + { + return processors.subList(fromIndex, toIndex); + } + + public Object[] toArray() + { + return processors.toArray(); + } + + public <T> T[] toArray(T[] a) + { + return processors.toArray(a); + } + + @Override + public String toString() + { + return processors.toString(); + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + try + { + doActivateOSGi(); + } + catch (Throwable t) + { + OM.LOG.warn(t); + } + } + + @Override + protected void doDeactivate() throws Exception + { + try + { + doDeactivateOSGi(); + } + catch (Throwable t) + { + OM.LOG.warn(t); + } + + processors.clear(); + super.doDeactivate(); + } + + private void doActivateOSGi() throws CoreException + { + org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform + .getExtensionRegistry(); + if (extensionRegistry == null) + { + return; + } + + org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor( + NAMESPACE, EXT_POINT); + for (org.eclipse.core.runtime.IConfigurationElement element : elements) + { + IElementProcessor processor = (IElementProcessor)element.createExecutableExtension(ATTR_CLASS); + processors.add(processor); + } + + org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener() + { + public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event) + { + org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT); + for (org.eclipse.core.runtime.IExtensionDelta delta : deltas) + { + // TODO Handle ExtensionDelta + OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$ + } + } + }; + + extensionRegistry.addRegistryChangeListener(listener, NAMESPACE); + extensionRegistryListener = listener; + } + + private void doDeactivateOSGi() + { + org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform + .getExtensionRegistry(); + if (extensionRegistry == null) + { + return; + } + + extensionRegistry + .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java index 04f569d54e..19491cd3e0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/factory/PluginFactoryRegistry.java @@ -1,127 +1,127 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.factory;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.factory.FactoryDescriptor;
-import org.eclipse.net4j.util.factory.IFactory;
-import org.eclipse.net4j.util.factory.IFactoryKey;
-import org.eclipse.net4j.util.registry.HashMapRegistry;
-
-/**
- * @author Eike Stepper
- */
-public class PluginFactoryRegistry extends HashMapRegistry<IFactoryKey, IFactory>
-{
- public static final String NAMESPACE = OM.BUNDLE_ID;
-
- public static final String EXT_POINT = "factories"; //$NON-NLS-1$
-
- private Object extensionRegistryListener;
-
- public PluginFactoryRegistry()
- {
- }
-
- @Override
- public IFactory get(Object key)
- {
- IFactory factory = super.get(key);
- if (factory instanceof FactoryDescriptor)
- {
- FactoryDescriptor descriptor = (FactoryDescriptor)factory;
- factory = descriptor.createFactory();
- }
-
- return factory;
- }
-
- public void registerFactory(FactoryDescriptor factory)
- {
- put(factory.getKey(), factory);
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- try
- {
- doActivateOSGi();
- }
- catch (Throwable t)
- {
- OM.LOG.warn(t);
- }
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- try
- {
- doDeactivateOSGi();
- }
- catch (Throwable t)
- {
- OM.LOG.warn(t);
- }
-
- clear();
- super.doDeactivate();
- }
-
- private void doActivateOSGi()
- {
- org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
- .getExtensionRegistry();
- if (extensionRegistry == null)
- {
- return;
- }
-
- org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor(
- NAMESPACE, EXT_POINT);
- for (org.eclipse.core.runtime.IConfigurationElement element : elements)
- {
- registerFactory(new FactoryDescriptor(element));
- }
-
- org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener()
- {
- public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event)
- {
- org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT);
- for (org.eclipse.core.runtime.IExtensionDelta delta : deltas)
- {
- // TODO Handle ExtensionDelta
- OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$
- }
- }
- };
-
- extensionRegistry.addRegistryChangeListener(listener, NAMESPACE);
- extensionRegistryListener = listener;
- }
-
- private void doDeactivateOSGi()
- {
- org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform
- .getExtensionRegistry();
- if (extensionRegistry == null)
- {
- return;
- }
-
- extensionRegistry
- .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.factory; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.factory.FactoryDescriptor; +import org.eclipse.net4j.util.factory.IFactory; +import org.eclipse.net4j.util.factory.IFactoryKey; +import org.eclipse.net4j.util.registry.HashMapRegistry; + +/** + * @author Eike Stepper + */ +public class PluginFactoryRegistry extends HashMapRegistry<IFactoryKey, IFactory> +{ + public static final String NAMESPACE = OM.BUNDLE_ID; + + public static final String EXT_POINT = "factories"; //$NON-NLS-1$ + + private Object extensionRegistryListener; + + public PluginFactoryRegistry() + { + } + + @Override + public IFactory get(Object key) + { + IFactory factory = super.get(key); + if (factory instanceof FactoryDescriptor) + { + FactoryDescriptor descriptor = (FactoryDescriptor)factory; + factory = descriptor.createFactory(); + } + + return factory; + } + + public void registerFactory(FactoryDescriptor factory) + { + put(factory.getKey(), factory); + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + try + { + doActivateOSGi(); + } + catch (Throwable t) + { + OM.LOG.warn(t); + } + } + + @Override + protected void doDeactivate() throws Exception + { + try + { + doDeactivateOSGi(); + } + catch (Throwable t) + { + OM.LOG.warn(t); + } + + clear(); + super.doDeactivate(); + } + + private void doActivateOSGi() + { + org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform + .getExtensionRegistry(); + if (extensionRegistry == null) + { + return; + } + + org.eclipse.core.runtime.IConfigurationElement[] elements = extensionRegistry.getConfigurationElementsFor( + NAMESPACE, EXT_POINT); + for (org.eclipse.core.runtime.IConfigurationElement element : elements) + { + registerFactory(new FactoryDescriptor(element)); + } + + org.eclipse.core.runtime.IRegistryChangeListener listener = new org.eclipse.core.runtime.IRegistryChangeListener() + { + public void registryChanged(org.eclipse.core.runtime.IRegistryChangeEvent event) + { + org.eclipse.core.runtime.IExtensionDelta[] deltas = event.getExtensionDeltas(NAMESPACE, EXT_POINT); + for (org.eclipse.core.runtime.IExtensionDelta delta : deltas) + { + // TODO Handle ExtensionDelta + OM.LOG.warn("ExtensionDelta not handled: " + delta); //$NON-NLS-1$ + } + } + }; + + extensionRegistry.addRegistryChangeListener(listener, NAMESPACE); + extensionRegistryListener = listener; + } + + private void doDeactivateOSGi() + { + org.eclipse.core.runtime.IExtensionRegistry extensionRegistry = org.eclipse.core.runtime.Platform + .getExtensionRegistry(); + if (extensionRegistry == null) + { + return; + } + + extensionRegistry + .removeRegistryChangeListener((org.eclipse.core.runtime.IRegistryChangeListener)extensionRegistryListener); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java index 2cfb67bb15..4905a122a6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyBundle.java @@ -1,343 +1,343 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
-import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
-import org.eclipse.net4j.util.ReflectUtil;
-import org.eclipse.net4j.util.StringUtil;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.io.IOUtil;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.MissingResourceException;
-import java.util.Properties;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-
-/**
- * @author Eike Stepper
- */
-public class LegacyBundle extends AbstractBundle
-{
- private URL baseURL;
-
- public LegacyBundle(AbstractPlatform platform, String bundleID, Class<?> accessor)
- {
- super(platform, bundleID, accessor);
-
- try
- {
- computeBaseURL(accessor);
- if (baseURL == null)
- {
- throw new IllegalStateException("No base URL");
- }
-
- loadOptions();
- }
- catch (Exception ex)
- {
- IOUtil.print(ex);
- }
- }
-
- public String getStateLocation()
- {
- return new File(getPlatform().getStateFolder(), ".plugins/" + getBundleID()).getAbsolutePath(); //$NON-NLS-1$
- }
-
- public URL getBaseURL()
- {
- return baseURL;
- }
-
- public Iterator<Class<?>> getClasses()
- {
- List<Class<?>> result = new ArrayList<Class<?>>();
-
- if (isArchiveProtocol(baseURL.getProtocol()))
- {
- JarFile jarFile = null;
-
- try
- {
- jarFile = new JarFile(baseURL.getFile());
-
- Enumeration<JarEntry> entries = jarFile.entries();
- while (entries.hasMoreElements())
- {
- JarEntry jarEntry = entries.nextElement();
- if (!jarEntry.isDirectory())
- {
- Class<?> c = getClassFromBundle(jarEntry.getName());
- if (c != null)
- {
- result.add(c);
- }
- }
- }
- }
- catch (IOException ex)
- {
- throw WrappedException.wrap(ex);
- }
- finally
- {
- if (jarFile != null)
- {
- try
- {
- jarFile.close();
- }
- catch (IOException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
- }
- }
- else
- {
- try
- {
- URL url = getClassesURL(getAccessor());
- File folder = new File(url.getFile());
- collectFileClasses(folder, null, result);
- }
- catch (MalformedURLException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- return result.iterator();
- }
-
- private void collectFileClasses(File folder, String path, List<Class<?>> result)
- {
- File file = folder;
- if (path == null)
- {
- path = "";
- }
- else
- {
- file = new File(folder, path);
- }
-
- if (file.isDirectory())
- {
- for (String child : file.list())
- {
- collectFileClasses(folder, path + "/" + child, result);
- }
- }
- else
- {
- Class<?> c = getClassFromBundle(path);
- if (c != null)
- {
- result.add(c);
- }
- }
- }
-
- private void loadOptions()
- {
- InputStream inputStream = null;
- Properties properties = new Properties();
-
- try
- {
- final String prefix = getBundleID() + "/"; //$NON-NLS-1$
- final int length = prefix.length();
-
- inputStream = getInputStream(".options"); //$NON-NLS-1$
- properties.load(inputStream);
-
- for (Entry<Object, Object> entry : properties.entrySet())
- {
- try
- {
- String key = (String)entry.getKey();
- if (key.startsWith(prefix))
- {
- String value = (String)entry.getValue();
- setDebugOption(key.substring(length), value);
- }
- }
- catch (RuntimeException ignore)
- {
- }
- }
- }
- catch (IOException ignore)
- {
- }
- finally
- {
- IOUtil.closeSilent(inputStream);
- }
- }
-
- private void computeBaseURL(Class<?> accessor) throws MalformedURLException
- {
- // Determine the URL for the class itself. The URL will be of one of the
- // following forms, so there are a few good places to consider looking for
- // the plugin.properties.
- //
- // For a plugin.xml with runtime="common.jar":
- // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/common.jar!/org/eclipse/common/
- // CommonPlugin.class
- //
- // For a plugin.xml with runtime="runtime/common.jar":
- // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/runtime/common.jar!/org/eclipse/common
- // /CommonPlugin.class
- //
- // For a plugin.xml with runtime="." where the plugin is jarred:
- // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common.jar!/org/eclipse/common/CommonPlugin.
- // class
- //
- // For a plugin.xml with runtime="." where the plugin is not jarred.
- // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/org/eclipse/emf/common/CommonPlugin.class
- //
- // Running in PDE with bin on classpath:
- // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/bin/org/eclipse/emf/common/CommonPlugin.
- // class
-
- URL url = getClassesURL(accessor);
-
- // For an archive URI, check for the plugin.properties in the archive.
- if (isArchiveProtocol(url.getProtocol()))
- {
- try
- {
- // If we can open an input stream, then the plugin.properties is there,
- // and we have a good base URL.
- URL u = new URL(url.toString() + "plugin.properties");
- InputStream inputStream = null;
-
- try
- {
- inputStream = u.openStream();
- }
- finally
- {
- IOUtil.close(inputStream);
- }
-
- baseURL = url;
- }
- catch (IOException exception)
- {
- // If the plugin.properties isn't within the root of the archive, create
- // a new URI for the folder location of the archive, so we can look in
- // the folder that contains it.
- url = trimSegments(new URL(url.getFile()), 1);
- }
- }
-
- // If we didn't find the plugin.properties in the usual place nor in the
- // archive...
- if (baseURL == null)
- {
- // Trim off the "bin" or "runtime" segment.
- String lastSegment = lastSegment(url);
- if ("bin".equals(lastSegment) || "runtime".equals(lastSegment)) //$NON-NLS-1$ //$NON-NLS-2$
- {
- url = trimSegments(url, 1);
- }
-
- try
- {
- // If we can open an input stream, then the plugin.properties is in the
- // folder, and we have a good base URL.
- InputStream inputStream = new URL(url.toString() + "plugin.properties").openStream(); //$NON-NLS-1$
- inputStream.close();
- baseURL = url;
- }
- catch (IOException exception)
- {
- }
- }
-
- // If we still don't have a good base URL, complain about it.
- if (baseURL == null)
- {
- throw new MissingResourceException("Missing properties: " + accessor.getName(), accessor.getName(), //$NON-NLS-1$
- "plugin.properties"); //$NON-NLS-1$
- }
- }
-
- private static URL getClassesURL(Class<?> accessor) throws MalformedURLException
- {
- String className = accessor.getName();
- URL url = accessor.getResource(ReflectUtil.getSimpleName(accessor) + ".class"); //$NON-NLS-1$
-
- int segmentsToTrim = 1 + StringUtil.occurrences(className, '.');
- return trimSegments(url, segmentsToTrim);
- }
-
- private static String lastSegment(URL url)
- {
- String path = url.getPath();
- if (path.endsWith("/")) //$NON-NLS-1$
- {
- path = path.substring(0, path.length() - 1);
- }
-
- int pos = path.lastIndexOf('/');
- return pos == -1 ? path : path.substring(pos + 1);
- }
-
- private static URL trimSegments(URL url, int count) throws MalformedURLException
- {
- String path = url.getPath();
- if (path.endsWith("/")) //$NON-NLS-1$
- {
- ++count;
- }
-
- for (int i = 0; i < count; i++)
- {
- int pos = path.lastIndexOf('/');
- if (pos == -1)
- {
- break;
- }
-
- // TODO Optimize
- path = path.substring(0, pos);
- }
-
- return new URL(url.getProtocol() + ":" + path + "/"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * TODO Make configurable
- *
- * @see org.eclipse.emf.common.util.URI#isArchiveScheme(String)
- */
- private static boolean isArchiveProtocol(String scheme)
- {
- return "jar".equalsIgnoreCase(scheme); //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om; + +import org.eclipse.net4j.internal.util.bundle.AbstractBundle; +import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; +import org.eclipse.net4j.util.ReflectUtil; +import org.eclipse.net4j.util.StringUtil; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.io.IOUtil; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.MissingResourceException; +import java.util.Properties; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +/** + * @author Eike Stepper + */ +public class LegacyBundle extends AbstractBundle +{ + private URL baseURL; + + public LegacyBundle(AbstractPlatform platform, String bundleID, Class<?> accessor) + { + super(platform, bundleID, accessor); + + try + { + computeBaseURL(accessor); + if (baseURL == null) + { + throw new IllegalStateException("No base URL"); + } + + loadOptions(); + } + catch (Exception ex) + { + IOUtil.print(ex); + } + } + + public String getStateLocation() + { + return new File(getPlatform().getStateFolder(), ".plugins/" + getBundleID()).getAbsolutePath(); //$NON-NLS-1$ + } + + public URL getBaseURL() + { + return baseURL; + } + + public Iterator<Class<?>> getClasses() + { + List<Class<?>> result = new ArrayList<Class<?>>(); + + if (isArchiveProtocol(baseURL.getProtocol())) + { + JarFile jarFile = null; + + try + { + jarFile = new JarFile(baseURL.getFile()); + + Enumeration<JarEntry> entries = jarFile.entries(); + while (entries.hasMoreElements()) + { + JarEntry jarEntry = entries.nextElement(); + if (!jarEntry.isDirectory()) + { + Class<?> c = getClassFromBundle(jarEntry.getName()); + if (c != null) + { + result.add(c); + } + } + } + } + catch (IOException ex) + { + throw WrappedException.wrap(ex); + } + finally + { + if (jarFile != null) + { + try + { + jarFile.close(); + } + catch (IOException ex) + { + throw WrappedException.wrap(ex); + } + } + } + } + else + { + try + { + URL url = getClassesURL(getAccessor()); + File folder = new File(url.getFile()); + collectFileClasses(folder, null, result); + } + catch (MalformedURLException ex) + { + throw WrappedException.wrap(ex); + } + } + + return result.iterator(); + } + + private void collectFileClasses(File folder, String path, List<Class<?>> result) + { + File file = folder; + if (path == null) + { + path = ""; + } + else + { + file = new File(folder, path); + } + + if (file.isDirectory()) + { + for (String child : file.list()) + { + collectFileClasses(folder, path + "/" + child, result); + } + } + else + { + Class<?> c = getClassFromBundle(path); + if (c != null) + { + result.add(c); + } + } + } + + private void loadOptions() + { + InputStream inputStream = null; + Properties properties = new Properties(); + + try + { + final String prefix = getBundleID() + "/"; //$NON-NLS-1$ + final int length = prefix.length(); + + inputStream = getInputStream(".options"); //$NON-NLS-1$ + properties.load(inputStream); + + for (Entry<Object, Object> entry : properties.entrySet()) + { + try + { + String key = (String)entry.getKey(); + if (key.startsWith(prefix)) + { + String value = (String)entry.getValue(); + setDebugOption(key.substring(length), value); + } + } + catch (RuntimeException ignore) + { + } + } + } + catch (IOException ignore) + { + } + finally + { + IOUtil.closeSilent(inputStream); + } + } + + private void computeBaseURL(Class<?> accessor) throws MalformedURLException + { + // Determine the URL for the class itself. The URL will be of one of the + // following forms, so there are a few good places to consider looking for + // the plugin.properties. + // + // For a plugin.xml with runtime="common.jar": + // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/common.jar!/org/eclipse/common/ + // CommonPlugin.class + // + // For a plugin.xml with runtime="runtime/common.jar": + // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/runtime/common.jar!/org/eclipse/common + // /CommonPlugin.class + // + // For a plugin.xml with runtime="." where the plugin is jarred: + // jar:file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common.jar!/org/eclipse/common/CommonPlugin. + // class + // + // For a plugin.xml with runtime="." where the plugin is not jarred. + // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/org/eclipse/emf/common/CommonPlugin.class + // + // Running in PDE with bin on classpath: + // file:/D:/sandbox/unpackage1-3.1M7/eclipse/plugins/org.eclipse.emf.common/bin/org/eclipse/emf/common/CommonPlugin. + // class + + URL url = getClassesURL(accessor); + + // For an archive URI, check for the plugin.properties in the archive. + if (isArchiveProtocol(url.getProtocol())) + { + try + { + // If we can open an input stream, then the plugin.properties is there, + // and we have a good base URL. + URL u = new URL(url.toString() + "plugin.properties"); + InputStream inputStream = null; + + try + { + inputStream = u.openStream(); + } + finally + { + IOUtil.close(inputStream); + } + + baseURL = url; + } + catch (IOException exception) + { + // If the plugin.properties isn't within the root of the archive, create + // a new URI for the folder location of the archive, so we can look in + // the folder that contains it. + url = trimSegments(new URL(url.getFile()), 1); + } + } + + // If we didn't find the plugin.properties in the usual place nor in the + // archive... + if (baseURL == null) + { + // Trim off the "bin" or "runtime" segment. + String lastSegment = lastSegment(url); + if ("bin".equals(lastSegment) || "runtime".equals(lastSegment)) //$NON-NLS-1$ //$NON-NLS-2$ + { + url = trimSegments(url, 1); + } + + try + { + // If we can open an input stream, then the plugin.properties is in the + // folder, and we have a good base URL. + InputStream inputStream = new URL(url.toString() + "plugin.properties").openStream(); //$NON-NLS-1$ + inputStream.close(); + baseURL = url; + } + catch (IOException exception) + { + } + } + + // If we still don't have a good base URL, complain about it. + if (baseURL == null) + { + throw new MissingResourceException("Missing properties: " + accessor.getName(), accessor.getName(), //$NON-NLS-1$ + "plugin.properties"); //$NON-NLS-1$ + } + } + + private static URL getClassesURL(Class<?> accessor) throws MalformedURLException + { + String className = accessor.getName(); + URL url = accessor.getResource(ReflectUtil.getSimpleName(accessor) + ".class"); //$NON-NLS-1$ + + int segmentsToTrim = 1 + StringUtil.occurrences(className, '.'); + return trimSegments(url, segmentsToTrim); + } + + private static String lastSegment(URL url) + { + String path = url.getPath(); + if (path.endsWith("/")) //$NON-NLS-1$ + { + path = path.substring(0, path.length() - 1); + } + + int pos = path.lastIndexOf('/'); + return pos == -1 ? path : path.substring(pos + 1); + } + + private static URL trimSegments(URL url, int count) throws MalformedURLException + { + String path = url.getPath(); + if (path.endsWith("/")) //$NON-NLS-1$ + { + ++count; + } + + for (int i = 0; i < count; i++) + { + int pos = path.lastIndexOf('/'); + if (pos == -1) + { + break; + } + + // TODO Optimize + path = path.substring(0, pos); + } + + return new URL(url.getProtocol() + ":" + path + "/"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * TODO Make configurable + * + * @see org.eclipse.emf.common.util.URI#isArchiveScheme(String) + */ + private static boolean isArchiveProtocol(String scheme) + { + return "jar".equalsIgnoreCase(scheme); //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java index f5df96131d..c16e7dcdd5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/LegacyPlatform.java @@ -1,58 +1,58 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
-import org.eclipse.net4j.util.om.LegacyUtil;
-import org.eclipse.net4j.util.om.OMBundle;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Eike Stepper
- */
-public class LegacyPlatform extends AbstractPlatform
-{
- private Map<String, String> debugOptions = new ConcurrentHashMap<String, String>(0);
-
- public LegacyPlatform()
- {
- }
-
- public boolean isOSGiRunning()
- {
- return false;
- }
-
- @Override
- protected OMBundle createBundle(String bundleID, Class<?> accessor)
- {
- return new LegacyBundle(this, bundleID, accessor);
- }
-
- @Override
- protected String getDebugOption(String bundleID, String option)
- {
- return debugOptions.get(bundleID + "/" + option); //$NON-NLS-1$
- }
-
- @Override
- protected void setDebugOption(String bundleID, String option, String value)
- {
- debugOptions.put(bundleID + "/" + option, value); //$NON-NLS-1$
- }
-
- public String[] getCommandLineArgs()
- {
- return LegacyUtil.getCommandLineArgs();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om; + +import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; +import org.eclipse.net4j.util.om.LegacyUtil; +import org.eclipse.net4j.util.om.OMBundle; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author Eike Stepper + */ +public class LegacyPlatform extends AbstractPlatform +{ + private Map<String, String> debugOptions = new ConcurrentHashMap<String, String>(0); + + public LegacyPlatform() + { + } + + public boolean isOSGiRunning() + { + return false; + } + + @Override + protected OMBundle createBundle(String bundleID, Class<?> accessor) + { + return new LegacyBundle(this, bundleID, accessor); + } + + @Override + protected String getDebugOption(String bundleID, String option) + { + return debugOptions.get(bundleID + "/" + option); //$NON-NLS-1$ + } + + @Override + protected void setDebugOption(String bundleID, String option, String value) + { + debugOptions.put(bundleID + "/" + option, value); //$NON-NLS-1$ + } + + public String[] getCommandLineArgs() + { + return LegacyUtil.getCommandLineArgs(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java index ed6d5bd4d1..29887d84ae 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiBundle.java @@ -1,116 +1,116 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
-import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.collection.AbstractIterator;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.Platform;
-
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.Queue;
-
-/**
- * @author Eike Stepper
- */
-public class OSGiBundle extends AbstractBundle
-{
- public OSGiBundle(AbstractPlatform platform, String bundleID, Class<?> accessor)
- {
- super(platform, bundleID, accessor);
- }
-
- @Override
- public BundleContext getBundleContext()
- {
- return (BundleContext)super.getBundleContext();
- }
-
- public URL getBaseURL()
- {
- try
- {
- URL entry = getBundleContext().getBundle().getEntry("/"); //$NON-NLS-1$
- URL baseURL = FileLocator.resolve(entry);
- String str = baseURL.toExternalForm();
- if (str.endsWith("/./")) //$NON-NLS-1$
- {
- baseURL = new URL(str.substring(0, str.length() - 2));
- }
-
- return baseURL;
- }
- catch (IOException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- public Iterator<Class<?>> getClasses()
- {
- final Queue<String> folders = new LinkedList<String>();
- folders.offer("/");
-
- return new AbstractIterator<Class<?>>()
- {
- private Enumeration<String> entryPaths;
-
- @Override
- protected Object computeNextElement()
- {
- for (;;)
- {
- while (entryPaths != null && entryPaths.hasMoreElements())
- {
- String entryPath = entryPaths.nextElement();
- if (entryPath.endsWith("/"))
- {
- folders.offer(entryPath);
- }
- else
- {
- Class<?> c = getClassFromBundle(entryPath);
- if (c != null)
- {
- return c;
- }
- }
- }
-
- String folder = folders.poll();
- if (folder == null)
- {
- return END_OF_DATA;
- }
-
- Bundle bundle = getBundleContext().getBundle();
- entryPaths = bundle.getEntryPaths(folder);
- }
- }
- };
- }
-
- public String getStateLocation()
- {
- Bundle bundle = getBundleContext().getBundle();
- return Platform.getStateLocation(bundle).toString();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om; + +import org.eclipse.net4j.internal.util.bundle.AbstractBundle; +import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.collection.AbstractIterator; + +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.Platform; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +import java.io.IOException; +import java.net.URL; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.Queue; + +/** + * @author Eike Stepper + */ +public class OSGiBundle extends AbstractBundle +{ + public OSGiBundle(AbstractPlatform platform, String bundleID, Class<?> accessor) + { + super(platform, bundleID, accessor); + } + + @Override + public BundleContext getBundleContext() + { + return (BundleContext)super.getBundleContext(); + } + + public URL getBaseURL() + { + try + { + URL entry = getBundleContext().getBundle().getEntry("/"); //$NON-NLS-1$ + URL baseURL = FileLocator.resolve(entry); + String str = baseURL.toExternalForm(); + if (str.endsWith("/./")) //$NON-NLS-1$ + { + baseURL = new URL(str.substring(0, str.length() - 2)); + } + + return baseURL; + } + catch (IOException ex) + { + throw WrappedException.wrap(ex); + } + } + + public Iterator<Class<?>> getClasses() + { + final Queue<String> folders = new LinkedList<String>(); + folders.offer("/"); + + return new AbstractIterator<Class<?>>() + { + private Enumeration<String> entryPaths; + + @Override + protected Object computeNextElement() + { + for (;;) + { + while (entryPaths != null && entryPaths.hasMoreElements()) + { + String entryPath = entryPaths.nextElement(); + if (entryPath.endsWith("/")) + { + folders.offer(entryPath); + } + else + { + Class<?> c = getClassFromBundle(entryPath); + if (c != null) + { + return c; + } + } + } + + String folder = folders.poll(); + if (folder == null) + { + return END_OF_DATA; + } + + Bundle bundle = getBundleContext().getBundle(); + entryPaths = bundle.getEntryPaths(folder); + } + } + }; + } + + public String getStateLocation() + { + Bundle bundle = getBundleContext().getBundle(); + return Platform.getStateLocation(bundle).toString(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java index e32483f1c9..fa52602b4c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/OSGiPlatform.java @@ -1,109 +1,109 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
-import org.eclipse.net4j.util.om.OMBundle;
-
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.osgi.service.debug.DebugOptions;
-
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-/**
- * @author Eike Stepper
- */
-public class OSGiPlatform extends AbstractPlatform
-{
- BundleContext systemContext;
-
- public OSGiPlatform(Object systemContext)
- {
- this.systemContext = (BundleContext)systemContext;
-
- try
- {
- setDebugging(Platform.inDebugMode());
- }
- catch (Throwable ignore)
- {
- }
- }
-
- public boolean isOSGiRunning()
- {
- return true;
- }
-
- @Override
- public String getProperty(String key)
- {
- return systemContext != null ? systemContext.getProperty(key) : null;
- }
-
- @Override
- public String getProperty(String key, String defaultValue)
- {
- String property = getProperty(key);
- return property != null ? property : defaultValue;
- }
-
- public String[] getCommandLineArgs()
- {
- return Platform.getCommandLineArgs();
- }
-
- public void setCommandLineArgs(String[] args)
- {
- throw new UnsupportedOperationException("Set command line arguements inside the OSGi enviorment is not needed.");
- }
-
- @Override
- protected OMBundle createBundle(String bundleID, Class<?> accessor)
- {
- return new OSGiBundle(this, bundleID, accessor);
- }
-
- @Override
- protected String getDebugOption(String bundleID, String option)
- {
- try
- {
- DebugOptions debugOptions = getDebugOptions();
- return debugOptions.getOption(bundleID + "/" + option); //$NON-NLS-1$
- }
- catch (RuntimeException ex)
- {
- return null;
- }
- }
-
- @Override
- protected void setDebugOption(String bundleID, String option, String value)
- {
- try
- {
- DebugOptions debugOptions = getDebugOptions();
- debugOptions.setOption(bundleID + "/" + option, value); //$NON-NLS-1$
- }
- catch (RuntimeException ex)
- {
- }
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- protected DebugOptions getDebugOptions() throws NoClassDefFoundError, NullPointerException
- {
- ServiceReference ref = systemContext.getServiceReference(DebugOptions.class.getName());
- return (DebugOptions)systemContext.getService(ref);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om; + +import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; +import org.eclipse.net4j.util.om.OMBundle; + +import org.eclipse.core.runtime.Platform; +import org.eclipse.osgi.service.debug.DebugOptions; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; + +/** + * @author Eike Stepper + */ +public class OSGiPlatform extends AbstractPlatform +{ + BundleContext systemContext; + + public OSGiPlatform(Object systemContext) + { + this.systemContext = (BundleContext)systemContext; + + try + { + setDebugging(Platform.inDebugMode()); + } + catch (Throwable ignore) + { + } + } + + public boolean isOSGiRunning() + { + return true; + } + + @Override + public String getProperty(String key) + { + return systemContext != null ? systemContext.getProperty(key) : null; + } + + @Override + public String getProperty(String key, String defaultValue) + { + String property = getProperty(key); + return property != null ? property : defaultValue; + } + + public String[] getCommandLineArgs() + { + return Platform.getCommandLineArgs(); + } + + public void setCommandLineArgs(String[] args) + { + throw new UnsupportedOperationException("Set command line arguements inside the OSGi enviorment is not needed."); + } + + @Override + protected OMBundle createBundle(String bundleID, Class<?> accessor) + { + return new OSGiBundle(this, bundleID, accessor); + } + + @Override + protected String getDebugOption(String bundleID, String option) + { + try + { + DebugOptions debugOptions = getDebugOptions(); + return debugOptions.getOption(bundleID + "/" + option); //$NON-NLS-1$ + } + catch (RuntimeException ex) + { + return null; + } + } + + @Override + protected void setDebugOption(String bundleID, String option, String value) + { + try + { + DebugOptions debugOptions = getDebugOptions(); + debugOptions.setOption(bundleID + "/" + option, value); //$NON-NLS-1$ + } + catch (RuntimeException ex) + { + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + protected DebugOptions getDebugOptions() throws NoClassDefFoundError, NullPointerException + { + ServiceReference ref = systemContext.getServiceReference(DebugOptions.class.getName()); + return (DebugOptions)systemContext.getService(ref); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java index cf413fb9a6..46475d7bd5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/ArrayPreference.java @@ -1,95 +1,95 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-
-/**
- * @author Eike Stepper
- */
-public final class ArrayPreference extends Preference<String[]>
-{
- private static final String SEPARATOR = ","; //$NON-NLS-1$
-
- private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$
-
- public ArrayPreference(Preferences preferences, String name, String[] defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- String[] array = getValue();
- if (array == null || array.length == 0)
- {
- return null;
- }
-
- StringBuilder builder = new StringBuilder();
- for (String element : array)
- {
- if (builder.length() != 0)
- {
- builder.append(SEPARATOR);
- builder.append(" "); //$NON-NLS-1$
- }
-
- try
- {
- String encoded = URLEncoder.encode(element, UTF_8);
- builder.append(encoded);
- }
- catch (UnsupportedEncodingException ex)
- {
- OM.LOG.error(ex);
- return null;
- }
- }
-
- return builder.toString();
- }
-
- @Override
- protected String[] convert(String value)
- {
- String[] array = value.split(SEPARATOR);
- if (array == null || array.length == 0)
- {
- return Preferences.DEFAULT_ARRAY;
- }
-
- for (int i = 0; i < array.length; i++)
- {
- try
- {
- array[i] = URLDecoder.decode(array[i].trim(), UTF_8);
- }
- catch (UnsupportedEncodingException ex)
- {
- OM.LOG.error(ex);
- return null;
- }
- }
-
- return array;
- }
-
- public Type getType()
- {
- return Type.ARRAY;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +import org.eclipse.net4j.internal.util.bundle.OM; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; + +/** + * @author Eike Stepper + */ +public final class ArrayPreference extends Preference<String[]> +{ + private static final String SEPARATOR = ","; //$NON-NLS-1$ + + private static final String UTF_8 = "UTF-8"; //$NON-NLS-1$ + + public ArrayPreference(Preferences preferences, String name, String[] defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + String[] array = getValue(); + if (array == null || array.length == 0) + { + return null; + } + + StringBuilder builder = new StringBuilder(); + for (String element : array) + { + if (builder.length() != 0) + { + builder.append(SEPARATOR); + builder.append(" "); //$NON-NLS-1$ + } + + try + { + String encoded = URLEncoder.encode(element, UTF_8); + builder.append(encoded); + } + catch (UnsupportedEncodingException ex) + { + OM.LOG.error(ex); + return null; + } + } + + return builder.toString(); + } + + @Override + protected String[] convert(String value) + { + String[] array = value.split(SEPARATOR); + if (array == null || array.length == 0) + { + return Preferences.DEFAULT_ARRAY; + } + + for (int i = 0; i < array.length; i++) + { + try + { + array[i] = URLDecoder.decode(array[i].trim(), UTF_8); + } + catch (UnsupportedEncodingException ex) + { + OM.LOG.error(ex); + return null; + } + } + + return array; + } + + public Type getType() + { + return Type.ARRAY; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java index 1167003eab..e02336314a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BooleanPreference.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-/**
- * @author Eike Stepper
- */
-public final class BooleanPreference extends Preference<Boolean>
-{
- public BooleanPreference(Preferences preferences, String name, Boolean defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return Boolean.toString(getValue());
- }
-
- @Override
- protected Boolean convert(String value)
- {
- return Boolean.parseBoolean(value);
- }
-
- public Type getType()
- {
- return Type.BOOLEAN;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +/** + * @author Eike Stepper + */ +public final class BooleanPreference extends Preference<Boolean> +{ + public BooleanPreference(Preferences preferences, String name, Boolean defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return Boolean.toString(getValue()); + } + + @Override + protected Boolean convert(String value) + { + return Boolean.parseBoolean(value); + } + + public Type getType() + { + return Type.BOOLEAN; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java index bec70ea622..5ccdb748ef 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/BytesPreference.java @@ -1,41 +1,41 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-import org.eclipse.net4j.util.HexUtil;
-
-/**
- * @author Eike Stepper
- */
-public final class BytesPreference extends Preference<byte[]>
-{
- public BytesPreference(Preferences preferences, String name, byte[] defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return HexUtil.bytesToHex(getValue());
- }
-
- @Override
- protected byte[] convert(String value)
- {
- return HexUtil.hexToBytes(value);
- }
-
- public Type getType()
- {
- return Type.BYTES;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +import org.eclipse.net4j.util.HexUtil; + +/** + * @author Eike Stepper + */ +public final class BytesPreference extends Preference<byte[]> +{ + public BytesPreference(Preferences preferences, String name, byte[] defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return HexUtil.bytesToHex(getValue()); + } + + @Override + protected byte[] convert(String value) + { + return HexUtil.hexToBytes(value); + } + + public Type getType() + { + return Type.BYTES; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java index e3d9617f70..3872c09cbb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/DoublePreference.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-/**
- * @author Eike Stepper
- */
-public final class DoublePreference extends Preference<Double>
-{
- public DoublePreference(Preferences preferences, String name, Double defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return Double.toString(getValue());
- }
-
- @Override
- protected Double convert(String value)
- {
- return Double.parseDouble(value);
- }
-
- public Type getType()
- {
- return Type.DOUBLE;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +/** + * @author Eike Stepper + */ +public final class DoublePreference extends Preference<Double> +{ + public DoublePreference(Preferences preferences, String name, Double defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return Double.toString(getValue()); + } + + @Override + protected Double convert(String value) + { + return Double.parseDouble(value); + } + + public Type getType() + { + return Type.DOUBLE; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java index ae5b951b62..3dd19e31fe 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/FloatPreference.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-/**
- * @author Eike Stepper
- */
-public final class FloatPreference extends Preference<Float>
-{
- public FloatPreference(Preferences preferences, String name, Float defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return Float.toString(getValue());
- }
-
- @Override
- protected Float convert(String value)
- {
- return Float.parseFloat(value);
- }
-
- public Type getType()
- {
- return Type.FLOAT;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +/** + * @author Eike Stepper + */ +public final class FloatPreference extends Preference<Float> +{ + public FloatPreference(Preferences preferences, String name, Float defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return Float.toString(getValue()); + } + + @Override + protected Float convert(String value) + { + return Float.parseFloat(value); + } + + public Type getType() + { + return Type.FLOAT; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java index bd5fe357ef..45838472ef 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/IntegerPreference.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-/**
- * @author Eike Stepper
- */
-public final class IntegerPreference extends Preference<Integer>
-{
- public IntegerPreference(Preferences preferences, String name, Integer defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return Integer.toString(getValue());
- }
-
- @Override
- protected Integer convert(String value)
- {
- return Integer.parseInt(value);
- }
-
- public Type getType()
- {
- return Type.INTEGER;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +/** + * @author Eike Stepper + */ +public final class IntegerPreference extends Preference<Integer> +{ + public IntegerPreference(Preferences preferences, String name, Integer defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return Integer.toString(getValue()); + } + + @Override + protected Integer convert(String value) + { + return Integer.parseInt(value); + } + + public Type getType() + { + return Type.INTEGER; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java index 6607f71f4b..9c0aca0927 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/LongPreference.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-/**
- * @author Eike Stepper
- */
-public final class LongPreference extends Preference<Long>
-{
- public LongPreference(Preferences preferences, String name, Long defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return Long.toString(getValue());
- }
-
- @Override
- protected Long convert(String value)
- {
- return Long.parseLong(value);
- }
-
- public Type getType()
- {
- return Type.LONG;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +/** + * @author Eike Stepper + */ +public final class LongPreference extends Preference<Long> +{ + public LongPreference(Preferences preferences, String name, Long defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return Long.toString(getValue()); + } + + @Override + protected Long convert(String value) + { + return Long.parseLong(value); + } + + public Type getType() + { + return Type.LONG; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java index 1c7edf0d14..9220d6d23c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preference.java @@ -1,121 +1,121 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-import org.eclipse.net4j.util.ObjectUtil;
-import org.eclipse.net4j.util.om.pref.OMPreference;
-
-/**
- * @author Eike Stepper
- */
-public abstract class Preference<T> implements OMPreference<T>
-{
- private Preferences preferences;
-
- private String name;
-
- private T defaultValue;
-
- private T value;
-
- public Preference(Preferences preferences, String name, T defaultValue)
- {
- if (defaultValue == null)
- {
- throw new IllegalArgumentException("defaultValue == null"); //$NON-NLS-1$
- }
-
- this.preferences = preferences;
- this.name = name;
- this.defaultValue = defaultValue;
- }
-
- public Preferences getPreferences()
- {
- return preferences;
- }
-
- public String getName()
- {
- return name;
- }
-
- public T getDefaultValue()
- {
- return defaultValue;
- }
-
- public T getValue()
- {
- load();
- return value;
- }
-
- public T setValue(T value)
- {
- if (value == null)
- {
- throw new IllegalArgumentException("value == null"); //$NON-NLS-1$
- }
-
- load();
- T oldValue = this.value;
- if (!equals(oldValue, value))
- {
- if (equals(defaultValue, value))
- {
- value = defaultValue;
- }
-
- this.value = value;
- preferences.fireChangeEvent(this, oldValue, value);
- return oldValue;
- }
-
- return null;
- }
-
- public boolean isSet()
- {
- return !equals(defaultValue, value);
- }
-
- public T unSet()
- {
- return setValue(defaultValue);
- }
-
- protected boolean equals(T v1, T v2)
- {
- return ObjectUtil.equals(v1, v2);
- }
-
- protected void init(String value)
- {
- if (value == null)
- {
- this.value = defaultValue;
- }
- else
- {
- this.value = convert(value);
- }
- }
-
- protected abstract T convert(String value);
-
- protected abstract String getString();
-
- private void load()
- {
- preferences.load();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +import org.eclipse.net4j.util.ObjectUtil; +import org.eclipse.net4j.util.om.pref.OMPreference; + +/** + * @author Eike Stepper + */ +public abstract class Preference<T> implements OMPreference<T> +{ + private Preferences preferences; + + private String name; + + private T defaultValue; + + private T value; + + public Preference(Preferences preferences, String name, T defaultValue) + { + if (defaultValue == null) + { + throw new IllegalArgumentException("defaultValue == null"); //$NON-NLS-1$ + } + + this.preferences = preferences; + this.name = name; + this.defaultValue = defaultValue; + } + + public Preferences getPreferences() + { + return preferences; + } + + public String getName() + { + return name; + } + + public T getDefaultValue() + { + return defaultValue; + } + + public T getValue() + { + load(); + return value; + } + + public T setValue(T value) + { + if (value == null) + { + throw new IllegalArgumentException("value == null"); //$NON-NLS-1$ + } + + load(); + T oldValue = this.value; + if (!equals(oldValue, value)) + { + if (equals(defaultValue, value)) + { + value = defaultValue; + } + + this.value = value; + preferences.fireChangeEvent(this, oldValue, value); + return oldValue; + } + + return null; + } + + public boolean isSet() + { + return !equals(defaultValue, value); + } + + public T unSet() + { + return setValue(defaultValue); + } + + protected boolean equals(T v1, T v2) + { + return ObjectUtil.equals(v1, v2); + } + + protected void init(String value) + { + if (value == null) + { + this.value = defaultValue; + } + else + { + this.value = convert(value); + } + } + + protected abstract T convert(String value); + + protected abstract String getString(); + + private void load() + { + preferences.load(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java index 18f650667b..65f0249fa6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/Preferences.java @@ -1,297 +1,297 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.event.Notifier;
-import org.eclipse.net4j.util.io.IORunnable;
-import org.eclipse.net4j.util.io.IORuntimeException;
-import org.eclipse.net4j.util.io.IOUtil;
-import org.eclipse.net4j.util.om.pref.OMPreference;
-import org.eclipse.net4j.util.om.pref.OMPreferences;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * @author Eike Stepper
- */
-public class Preferences extends Notifier implements OMPreferences
-{
- private AbstractBundle bundle;
-
- private Map<String, Preference<?>> prefs = new HashMap<String, Preference<?>>();
-
- private boolean loaded;
-
- private boolean dirty;
-
- public Preferences(AbstractBundle bundle)
- {
- this.bundle = bundle;
- }
-
- public AbstractBundle getBundle()
- {
- return bundle;
- }
-
- public synchronized void load()
- {
- if (!loaded)
- {
- loaded = true;
- final Properties properties = new Properties();
-
- File file = getFile();
- if (file.exists())
- {
- IOUtil.safeInput(file, new IORunnable<FileInputStream>()
- {
- public void run(FileInputStream io) throws IOException
- {
- properties.load(io);
- }
- });
- }
-
- for (Preference<?> preference : prefs.values())
- {
- String name = preference.getName();
- String value = properties.getProperty(name);
- preference.init(value);
- }
- }
- }
-
- public synchronized void save()
- {
- if (dirty)
- {
- final Properties properties = new Properties();
- for (Preference<?> preference : prefs.values())
- {
- if (preference.isSet())
- {
- String name = preference.getName();
- String value = preference.getString();
- if (value != null)
- {
- properties.put(name, value);
- }
- }
- }
-
- File file = getFile();
- if (properties.isEmpty())
- {
- if (file.exists())
- {
- file.delete();
- }
- }
- else
- {
- IOUtil.safeOutput(file, new IORunnable<FileOutputStream>()
- {
- public void run(FileOutputStream io) throws IOException
- {
- properties.store(io, "Preferences of " + bundle.getBundleID()); //$NON-NLS-1$
- }
- });
- }
-
- dirty = false;
- }
- }
-
- public boolean isDirty()
- {
- return dirty;
- }
-
- public OMPreference<Boolean> init(String name, boolean defaultValue)
- {
- return init(new BooleanPreference(this, name, defaultValue));
- }
-
- public OMPreference<Integer> init(String name, int defaultValue)
- {
- return init(new IntegerPreference(this, name, defaultValue));
- }
-
- public OMPreference<Long> init(String name, long defaultValue)
- {
- return init(new LongPreference(this, name, defaultValue));
- }
-
- public OMPreference<Float> init(String name, float defaultValue)
- {
- return init(new FloatPreference(this, name, defaultValue));
- }
-
- public OMPreference<Double> init(String name, double defaultValue)
- {
- return init(new DoublePreference(this, name, defaultValue));
- }
-
- public OMPreference<String> init(String name, String defaultValue)
- {
- return init(new StringPreference(this, name, defaultValue));
- }
-
- public OMPreference<String[]> init(String name, String[] defaultValue)
- {
- return init(new ArrayPreference(this, name, defaultValue));
- }
-
- public OMPreference<byte[]> init(String name, byte[] defaultValue)
- {
- return init(new BytesPreference(this, name, defaultValue));
- }
-
- public OMPreference<Boolean> initBoolean(String name)
- {
- return init(name, DEFAULT_BOOLEAN);
- }
-
- public OMPreference<Integer> initInteger(String name)
- {
- return init(name, DEFAULT_INTEGER);
- }
-
- public OMPreference<Long> initLong(String name)
- {
- return init(name, DEFAULT_LONG);
- }
-
- public OMPreference<Float> initFloat(String name)
- {
- return init(name, DEFAULT_FLOAT);
- }
-
- public OMPreference<Double> initDouble(String name)
- {
- return init(name, DEFAULT_DOUBLE);
- }
-
- public OMPreference<String> initString(String name)
- {
- return init(name, DEFAULT_STRING);
- }
-
- public OMPreference<String[]> initArray(String name)
- {
- return init(name, DEFAULT_ARRAY);
- }
-
- public OMPreference<byte[]> initBytes(String name)
- {
- return init(name, DEFAULT_BYTES);
- }
-
- public boolean contains(String name)
- {
- return prefs.containsKey(name);
- }
-
- public OMPreference<?> get(String name)
- {
- return prefs.get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<Boolean> getBoolean(String name)
- {
- return (OMPreference<Boolean>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<Integer> getInteger(String name)
- {
- return (OMPreference<Integer>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<Long> getLong(String name)
- {
- return (OMPreference<Long>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<Float> getFloat(String name)
- {
- return (OMPreference<Float>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<Double> getDouble(String name)
- {
- return (OMPreference<Double>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<String> getString(String name)
- {
- return (OMPreference<String>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<String[]> getArray(String name)
- {
- return (OMPreference<String[]>)get(name);
- }
-
- @SuppressWarnings("unchecked")
- public OMPreference<byte[]> getBytes(String name)
- {
- return (OMPreference<byte[]>)get(name);
- }
-
- public <T> void fireChangeEvent(Preference<T> preference, T oldValue, T newValue)
- {
- dirty = true;
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(new PreferencesChangeEvent<T>(preference, oldValue, newValue), listeners);
- }
- }
-
- private <T> OMPreference<T> init(Preference<T> preference)
- {
- String name = preference.getName();
- if (prefs.containsKey(name))
- {
- throw new IllegalArgumentException("Duplicate name: " + name); //$NON-NLS-1$
- }
-
- prefs.put(name, preference);
- return preference;
- }
-
- private File getFile()
- {
- File file = new File(bundle.getStateLocation(), ".prefs"); //$NON-NLS-1$
- if (file.exists() && !file.isFile())
- {
- throw new IORuntimeException("Not a file: " + file.getAbsolutePath()); //$NON-NLS-1$
- }
-
- return file;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +import org.eclipse.net4j.internal.util.bundle.AbstractBundle; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.event.Notifier; +import org.eclipse.net4j.util.io.IORunnable; +import org.eclipse.net4j.util.io.IORuntimeException; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.om.pref.OMPreference; +import org.eclipse.net4j.util.om.pref.OMPreferences; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * @author Eike Stepper + */ +public class Preferences extends Notifier implements OMPreferences +{ + private AbstractBundle bundle; + + private Map<String, Preference<?>> prefs = new HashMap<String, Preference<?>>(); + + private boolean loaded; + + private boolean dirty; + + public Preferences(AbstractBundle bundle) + { + this.bundle = bundle; + } + + public AbstractBundle getBundle() + { + return bundle; + } + + public synchronized void load() + { + if (!loaded) + { + loaded = true; + final Properties properties = new Properties(); + + File file = getFile(); + if (file.exists()) + { + IOUtil.safeInput(file, new IORunnable<FileInputStream>() + { + public void run(FileInputStream io) throws IOException + { + properties.load(io); + } + }); + } + + for (Preference<?> preference : prefs.values()) + { + String name = preference.getName(); + String value = properties.getProperty(name); + preference.init(value); + } + } + } + + public synchronized void save() + { + if (dirty) + { + final Properties properties = new Properties(); + for (Preference<?> preference : prefs.values()) + { + if (preference.isSet()) + { + String name = preference.getName(); + String value = preference.getString(); + if (value != null) + { + properties.put(name, value); + } + } + } + + File file = getFile(); + if (properties.isEmpty()) + { + if (file.exists()) + { + file.delete(); + } + } + else + { + IOUtil.safeOutput(file, new IORunnable<FileOutputStream>() + { + public void run(FileOutputStream io) throws IOException + { + properties.store(io, "Preferences of " + bundle.getBundleID()); //$NON-NLS-1$ + } + }); + } + + dirty = false; + } + } + + public boolean isDirty() + { + return dirty; + } + + public OMPreference<Boolean> init(String name, boolean defaultValue) + { + return init(new BooleanPreference(this, name, defaultValue)); + } + + public OMPreference<Integer> init(String name, int defaultValue) + { + return init(new IntegerPreference(this, name, defaultValue)); + } + + public OMPreference<Long> init(String name, long defaultValue) + { + return init(new LongPreference(this, name, defaultValue)); + } + + public OMPreference<Float> init(String name, float defaultValue) + { + return init(new FloatPreference(this, name, defaultValue)); + } + + public OMPreference<Double> init(String name, double defaultValue) + { + return init(new DoublePreference(this, name, defaultValue)); + } + + public OMPreference<String> init(String name, String defaultValue) + { + return init(new StringPreference(this, name, defaultValue)); + } + + public OMPreference<String[]> init(String name, String[] defaultValue) + { + return init(new ArrayPreference(this, name, defaultValue)); + } + + public OMPreference<byte[]> init(String name, byte[] defaultValue) + { + return init(new BytesPreference(this, name, defaultValue)); + } + + public OMPreference<Boolean> initBoolean(String name) + { + return init(name, DEFAULT_BOOLEAN); + } + + public OMPreference<Integer> initInteger(String name) + { + return init(name, DEFAULT_INTEGER); + } + + public OMPreference<Long> initLong(String name) + { + return init(name, DEFAULT_LONG); + } + + public OMPreference<Float> initFloat(String name) + { + return init(name, DEFAULT_FLOAT); + } + + public OMPreference<Double> initDouble(String name) + { + return init(name, DEFAULT_DOUBLE); + } + + public OMPreference<String> initString(String name) + { + return init(name, DEFAULT_STRING); + } + + public OMPreference<String[]> initArray(String name) + { + return init(name, DEFAULT_ARRAY); + } + + public OMPreference<byte[]> initBytes(String name) + { + return init(name, DEFAULT_BYTES); + } + + public boolean contains(String name) + { + return prefs.containsKey(name); + } + + public OMPreference<?> get(String name) + { + return prefs.get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<Boolean> getBoolean(String name) + { + return (OMPreference<Boolean>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<Integer> getInteger(String name) + { + return (OMPreference<Integer>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<Long> getLong(String name) + { + return (OMPreference<Long>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<Float> getFloat(String name) + { + return (OMPreference<Float>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<Double> getDouble(String name) + { + return (OMPreference<Double>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<String> getString(String name) + { + return (OMPreference<String>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<String[]> getArray(String name) + { + return (OMPreference<String[]>)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference<byte[]> getBytes(String name) + { + return (OMPreference<byte[]>)get(name); + } + + public <T> void fireChangeEvent(Preference<T> preference, T oldValue, T newValue) + { + dirty = true; + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new PreferencesChangeEvent<T>(preference, oldValue, newValue), listeners); + } + } + + private <T> OMPreference<T> init(Preference<T> preference) + { + String name = preference.getName(); + if (prefs.containsKey(name)) + { + throw new IllegalArgumentException("Duplicate name: " + name); //$NON-NLS-1$ + } + + prefs.put(name, preference); + return preference; + } + + private File getFile() + { + File file = new File(bundle.getStateLocation(), ".prefs"); //$NON-NLS-1$ + if (file.exists() && !file.isFile()) + { + throw new IORuntimeException("Not a file: " + file.getAbsolutePath()); //$NON-NLS-1$ + } + + return file; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java index ff56a8291d..98ae17b5ba 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/PreferencesChangeEvent.java @@ -1,57 +1,57 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-import org.eclipse.net4j.util.event.Event;
-import org.eclipse.net4j.util.om.pref.OMPreferencesChangeEvent;
-
-/**
- * @author Eike Stepper
- */
-public final class PreferencesChangeEvent<T> extends Event implements OMPreferencesChangeEvent<T>
-{
- private static final long serialVersionUID = 1L;
-
- private Preference<T> preference;
-
- private T oldValue;
-
- private T newValue;
-
- public PreferencesChangeEvent(Preference<T> preference, T oldValue, T newValue)
- {
- super(preference.getPreferences());
- this.preference = preference;
- this.oldValue = oldValue;
- this.newValue = newValue;
- }
-
- @Override
- public Preferences getSource()
- {
- return (Preferences)super.getSource();
- }
-
- public Preference<T> getPreference()
- {
- return preference;
- }
-
- public T getOldValue()
- {
- return oldValue;
- }
-
- public T getNewValue()
- {
- return newValue;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +import org.eclipse.net4j.util.event.Event; +import org.eclipse.net4j.util.om.pref.OMPreferencesChangeEvent; + +/** + * @author Eike Stepper + */ +public final class PreferencesChangeEvent<T> extends Event implements OMPreferencesChangeEvent<T> +{ + private static final long serialVersionUID = 1L; + + private Preference<T> preference; + + private T oldValue; + + private T newValue; + + public PreferencesChangeEvent(Preference<T> preference, T oldValue, T newValue) + { + super(preference.getPreferences()); + this.preference = preference; + this.oldValue = oldValue; + this.newValue = newValue; + } + + @Override + public Preferences getSource() + { + return (Preferences)super.getSource(); + } + + public Preference<T> getPreference() + { + return preference; + } + + public T getOldValue() + { + return oldValue; + } + + public T getNewValue() + { + return newValue; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java index 8038862b37..40240985df 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/om/pref/StringPreference.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.internal.util.om.pref;
-
-/**
- * @author Eike Stepper
- */
-public final class StringPreference extends Preference<String>
-{
- public StringPreference(Preferences preferences, String name, String defaultValue)
- {
- super(preferences, name, defaultValue);
- }
-
- @Override
- protected String getString()
- {
- return getValue();
- }
-
- @Override
- protected String convert(String value)
- {
- return value;
- }
-
- public Type getType()
- {
- return Type.STRING;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.internal.util.om.pref; + +/** + * @author Eike Stepper + */ +public final class StringPreference extends Preference<String> +{ + public StringPreference(Preferences preferences, String name, String defaultValue) + { + super(preferences, name, defaultValue); + } + + @Override + protected String getString() + { + return getValue(); + } + + @Override + protected String convert(String value) + { + return value; + } + + public Type getType() + { + return Type.STRING; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java index d7604fa61b..99c94b3a15 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/AdapterUtil.java @@ -1,95 +1,95 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-/**
- * Provides a single static {@link #adapt(Object, Class) adapt()} method that conveniently and safely wraps the
- * Platform's adaptation framework.
- *
- * @author Eike Stepper
- */
-public final class AdapterUtil
-{
- private AdapterUtil()
- {
- }
-
- public static <TYPE> TYPE adapt(Object object, Class<TYPE> type)
- {
- if (object == null)
- {
- return null;
- }
-
- Object adapter = null;
- if (type.isInstance(object))
- {
- adapter = object;
- }
- else
- {
- try
- {
- adapter = AdaptableHelper.adapt(object, type);
- if (adapter == null)
- {
- adapter = AdapterManagerHelper.adapt(object, type);
- }
- }
- catch (Throwable ignore)
- {
- }
- }
-
- @SuppressWarnings("unchecked")
- TYPE result = (TYPE)adapter;
- return result;
- }
-
- /**
- * Nested class to factor out dependencies on org.eclipse.core.runtime
- *
- * @author Eike Stepper
- */
- private static final class AdaptableHelper
- {
- public static Object adapt(Object object, Class<?> type)
- {
- if (object instanceof org.eclipse.core.runtime.IAdaptable)
- {
- return ((org.eclipse.core.runtime.IAdaptable)object).getAdapter(type);
- }
-
- return null;
- }
- }
-
- /**
- * Nested class to factor out dependencies on org.eclipse.core.runtime
- *
- * @author Eike Stepper
- */
- private static final class AdapterManagerHelper
- {
- private static org.eclipse.core.runtime.IAdapterManager adapterManager = org.eclipse.core.runtime.Platform
- .getAdapterManager();
-
- public static Object adapt(Object object, Class<?> type)
- {
- if (adapterManager != null)
- {
- return adapterManager.getAdapter(object, type);
- }
-
- return null;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +/** + * Provides a single static {@link #adapt(Object, Class) adapt()} method that conveniently and safely wraps the + * Platform's adaptation framework. + * + * @author Eike Stepper + */ +public final class AdapterUtil +{ + private AdapterUtil() + { + } + + public static <TYPE> TYPE adapt(Object object, Class<TYPE> type) + { + if (object == null) + { + return null; + } + + Object adapter = null; + if (type.isInstance(object)) + { + adapter = object; + } + else + { + try + { + adapter = AdaptableHelper.adapt(object, type); + if (adapter == null) + { + adapter = AdapterManagerHelper.adapt(object, type); + } + } + catch (Throwable ignore) + { + } + } + + @SuppressWarnings("unchecked") + TYPE result = (TYPE)adapter; + return result; + } + + /** + * Nested class to factor out dependencies on org.eclipse.core.runtime + * + * @author Eike Stepper + */ + private static final class AdaptableHelper + { + public static Object adapt(Object object, Class<?> type) + { + if (object instanceof org.eclipse.core.runtime.IAdaptable) + { + return ((org.eclipse.core.runtime.IAdaptable)object).getAdapter(type); + } + + return null; + } + } + + /** + * Nested class to factor out dependencies on org.eclipse.core.runtime + * + * @author Eike Stepper + */ + private static final class AdapterManagerHelper + { + private static org.eclipse.core.runtime.IAdapterManager adapterManager = org.eclipse.core.runtime.Platform + .getAdapterManager(); + + public static Object adapt(Object object, Class<?> type) + { + if (adapterManager != null) + { + return adapterManager.getAdapter(object, type); + } + + return null; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java index bb37bb3984..8ff05e4a61 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/CheckUtil.java @@ -1,64 +1,64 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-/**
- * Provides static methods that check object states and invocation arguments.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public final class CheckUtil
-{
- private CheckUtil()
- {
- }
-
- public static void checkNull(Object handle, String msg) throws NullPointerException
- {
- if (handle == null)
- {
- throw new NullPointerException(msg);
- }
- }
-
- public static void checkArg(boolean expr, String msg) throws IllegalArgumentException
- {
- if (!expr)
- {
- throw new IllegalArgumentException(msg);
- }
- }
-
- public static void checkArg(Object handle, String handleName) throws IllegalArgumentException
- {
- if (handle == null)
- {
- throw new IllegalArgumentException(handleName + " is null"); //$NON-NLS-1$
- }
- }
-
- public static void checkState(boolean expr, String msg) throws IllegalStateException
- {
- if (!expr)
- {
- throw new IllegalStateException(msg);
- }
- }
-
- public static void checkState(Object handle, String handleName) throws IllegalStateException
- {
- if (handle == null)
- {
- throw new IllegalStateException(handleName + " is null"); //$NON-NLS-1$
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +/** + * Provides static methods that check object states and invocation arguments. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public final class CheckUtil +{ + private CheckUtil() + { + } + + public static void checkNull(Object handle, String msg) throws NullPointerException + { + if (handle == null) + { + throw new NullPointerException(msg); + } + } + + public static void checkArg(boolean expr, String msg) throws IllegalArgumentException + { + if (!expr) + { + throw new IllegalArgumentException(msg); + } + } + + public static void checkArg(Object handle, String handleName) throws IllegalArgumentException + { + if (handle == null) + { + throw new IllegalArgumentException(handleName + " is null"); //$NON-NLS-1$ + } + } + + public static void checkState(boolean expr, String msg) throws IllegalStateException + { + if (!expr) + { + throw new IllegalStateException(msg); + } + } + + public static void checkState(Object handle, String handleName) throws IllegalStateException + { + if (handle == null) + { + throw new IllegalStateException(handleName + " is null"); //$NON-NLS-1$ + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java index e051534586..52efbddfd9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/HexUtil.java @@ -1,192 +1,192 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-import org.eclipse.net4j.util.io.IORuntimeException;
-
-import java.io.IOException;
-
-/**
- * Provides static methods that convert to and from hexadecimal string formats.
- *
- * @author Eike Stepper
- */
-public final class HexUtil
-{
- public static final char DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', };
-
- private HexUtil()
- {
- }
-
- /**
- * Converts a byte array into a string of lower case hex chars.
- *
- * @param bs
- * A byte array
- * @param off
- * The index of the first byte to read
- * @param length
- * The number of bytes to read.
- * @return the string of hex chars.
- */
- public static String bytesToHex(byte[] bs, int off, int length)
- {
- if (bs == null)
- {
- return null;
- }
-
- if (bs.length <= off || bs.length < off + length)
- {
- throw new IllegalArgumentException();
- }
-
- StringBuilder sb = new StringBuilder(length * 2);
- bytesToHexAppend(bs, off, length, sb);
- return sb.toString();
- }
-
- public static void bytesToHexAppend(byte[] bs, int off, int length, Appendable appendable)
- {
- if (bs.length <= off || bs.length < off + length)
- {
- throw new IllegalArgumentException();
- }
-
- if (appendable instanceof StringBuffer)
- {
- StringBuffer buffer = (StringBuffer)appendable;
- buffer.ensureCapacity(buffer.length() + length * 2);
- }
-
- try
- {
- for (int i = off; i < off + length; i++)
- {
- appendable.append(Character.forDigit(bs[i] >>> 4 & 0xf, 16));
- appendable.append(Character.forDigit(bs[i] & 0xf, 16));
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static String bytesToHex(byte[] bs)
- {
- if (bs == null)
- {
- return null;
- }
-
- return bytesToHex(bs, 0, bs.length);
- }
-
- public static byte[] hexToBytes(String s)
- {
- return hexToBytes(s, 0);
- }
-
- public static byte[] hexToBytes(String s, int off)
- {
- byte[] bs = new byte[off + (1 + s.length()) / 2];
- hexToBytes(s, bs, off);
- return bs;
- }
-
- /**
- * Converts a String of hex characters into an array of bytes.
- *
- * @param s
- * A string of hex characters (upper case or lower) of even length.
- * @param out
- * A byte array of length at least s.length()/2 + off
- * @param off
- * The first byte to write of the array
- */
- public static void hexToBytes(String s, byte[] out, int off) throws NumberFormatException, IndexOutOfBoundsException
- {
- int slen = s.length();
- if ((slen & 1) == 1)
- {
- s = '0' + s;
- }
-
- if (out.length < off + (slen >> 1))
- {
- throw new IndexOutOfBoundsException("Output buffer too small for input (" + out.length + '<' + off + (slen >> 1) //$NON-NLS-1$
- + ')');
- }
-
- // Safe to assume the string is even length
- byte b1, b2;
- for (int i = 0; i < slen; i += 2)
- {
- b1 = (byte)Character.digit(s.charAt(i), 16);
- b2 = (byte)Character.digit(s.charAt(i + 1), 16);
- if (b1 < 0 || b2 < 0)
- {
- throw new NumberFormatException(s);
- }
-
- out[off + i / 2] = (byte)(b1 << 4 | b2);
- }
- }
-
- public static String longToHex(long v)
- {
- final String hex = Long.toHexString(v);
- if (hex.length() < 8)
- {
- return "00000000".substring(hex.length()) + hex; //$NON-NLS-1$
- }
-
- return hex;
- }
-
- @Deprecated
- public static String formatByte(int b)
- {
- assertByte(b);
- return "" + DIGITS[b >> 4] + DIGITS[b & 0xf]; //$NON-NLS-1$
- }
-
- @Deprecated
- public static String formatBytes(byte[] bytes)
- {
- StringBuilder builder = new StringBuilder();
- for (byte b : bytes)
- {
- appendHex(builder, b - Byte.MIN_VALUE);
- }
-
- return builder.toString();
- }
-
- @Deprecated
- public static void appendHex(StringBuilder builder, int b)
- {
- assertByte(b);
- builder.append(DIGITS[b >> 4]);
- builder.append(DIGITS[b & 0xf]);
- }
-
- @Deprecated
- private static void assertByte(int b)
- {
- if (b < 0 || b > 255)
- {
- throw new IllegalArgumentException("b=" + b); //$NON-NLS-1$
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +import org.eclipse.net4j.util.io.IORuntimeException; + +import java.io.IOException; + +/** + * Provides static methods that convert to and from hexadecimal string formats. + * + * @author Eike Stepper + */ +public final class HexUtil +{ + public static final char DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', }; + + private HexUtil() + { + } + + /** + * Converts a byte array into a string of lower case hex chars. + * + * @param bs + * A byte array + * @param off + * The index of the first byte to read + * @param length + * The number of bytes to read. + * @return the string of hex chars. + */ + public static String bytesToHex(byte[] bs, int off, int length) + { + if (bs == null) + { + return null; + } + + if (bs.length <= off || bs.length < off + length) + { + throw new IllegalArgumentException(); + } + + StringBuilder sb = new StringBuilder(length * 2); + bytesToHexAppend(bs, off, length, sb); + return sb.toString(); + } + + public static void bytesToHexAppend(byte[] bs, int off, int length, Appendable appendable) + { + if (bs.length <= off || bs.length < off + length) + { + throw new IllegalArgumentException(); + } + + if (appendable instanceof StringBuffer) + { + StringBuffer buffer = (StringBuffer)appendable; + buffer.ensureCapacity(buffer.length() + length * 2); + } + + try + { + for (int i = off; i < off + length; i++) + { + appendable.append(Character.forDigit(bs[i] >>> 4 & 0xf, 16)); + appendable.append(Character.forDigit(bs[i] & 0xf, 16)); + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static String bytesToHex(byte[] bs) + { + if (bs == null) + { + return null; + } + + return bytesToHex(bs, 0, bs.length); + } + + public static byte[] hexToBytes(String s) + { + return hexToBytes(s, 0); + } + + public static byte[] hexToBytes(String s, int off) + { + byte[] bs = new byte[off + (1 + s.length()) / 2]; + hexToBytes(s, bs, off); + return bs; + } + + /** + * Converts a String of hex characters into an array of bytes. + * + * @param s + * A string of hex characters (upper case or lower) of even length. + * @param out + * A byte array of length at least s.length()/2 + off + * @param off + * The first byte to write of the array + */ + public static void hexToBytes(String s, byte[] out, int off) throws NumberFormatException, IndexOutOfBoundsException + { + int slen = s.length(); + if ((slen & 1) == 1) + { + s = '0' + s; + } + + if (out.length < off + (slen >> 1)) + { + throw new IndexOutOfBoundsException("Output buffer too small for input (" + out.length + '<' + off + (slen >> 1) //$NON-NLS-1$ + + ')'); + } + + // Safe to assume the string is even length + byte b1, b2; + for (int i = 0; i < slen; i += 2) + { + b1 = (byte)Character.digit(s.charAt(i), 16); + b2 = (byte)Character.digit(s.charAt(i + 1), 16); + if (b1 < 0 || b2 < 0) + { + throw new NumberFormatException(s); + } + + out[off + i / 2] = (byte)(b1 << 4 | b2); + } + } + + public static String longToHex(long v) + { + final String hex = Long.toHexString(v); + if (hex.length() < 8) + { + return "00000000".substring(hex.length()) + hex; //$NON-NLS-1$ + } + + return hex; + } + + @Deprecated + public static String formatByte(int b) + { + assertByte(b); + return "" + DIGITS[b >> 4] + DIGITS[b & 0xf]; //$NON-NLS-1$ + } + + @Deprecated + public static String formatBytes(byte[] bytes) + { + StringBuilder builder = new StringBuilder(); + for (byte b : bytes) + { + appendHex(builder, b - Byte.MIN_VALUE); + } + + return builder.toString(); + } + + @Deprecated + public static void appendHex(StringBuilder builder, int b) + { + assertByte(b); + builder.append(DIGITS[b >> 4]); + builder.append(DIGITS[b & 0xf]); + } + + @Deprecated + private static void assertByte(int b) + { + if (b < 0 || b > 255) + { + throw new IllegalArgumentException("b=" + b); //$NON-NLS-1$ + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java index 2ae7afa3a2..18f12284a9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/IErrorHandler.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-/**
- * A callback interface with a {@link #handleError(Throwable) handleError()} method.
- *
- * @author Eike Stepper
- * @since 2.0
- */
-public interface IErrorHandler
-{
- public void handleError(Throwable t);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +/** + * A callback interface with a {@link #handleError(Throwable) handleError()} method. + * + * @author Eike Stepper + * @since 2.0 + */ +public interface IErrorHandler +{ + public void handleError(Throwable t); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java index b92523b645..3b6a5d3251 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ImplementationError.java @@ -1,42 +1,42 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-/**
- * Should not be used anymore in favour of {@link AssertionError}. Likely to be deprecated soon.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class ImplementationError extends Error
-{
- private static final long serialVersionUID = 1L;
-
- public ImplementationError()
- {
- }
-
- public ImplementationError(String message)
- {
- super(message);
- }
-
- public ImplementationError(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- public ImplementationError(Throwable cause)
- {
- super(cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +/** + * Should not be used anymore in favour of {@link AssertionError}. Likely to be deprecated soon. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class ImplementationError extends Error +{ + private static final long serialVersionUID = 1L; + + public ImplementationError() + { + } + + public ImplementationError(String message) + { + super(message); + } + + public ImplementationError(String message, Throwable cause) + { + super(message, cause); + } + + public ImplementationError(Throwable cause) + { + super(cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java index 43a51b8dae..b2572ea3ce 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ObjectUtil.java @@ -1,110 +1,110 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-import java.lang.reflect.Array;
-import java.util.Collection;
-import java.util.Map;
-
-/**
- * Various static helper methods.
- *
- * @author Eike Stepper
- */
-public final class ObjectUtil
-{
- private ObjectUtil()
- {
- }
-
- public static boolean equals(Object o1, Object o2)
- {
- if (o1 == null)
- {
- return o2 == null;
- }
-
- return o1.equals(o2);
- }
-
- public static int hashCode(Object o)
- {
- if (o == null)
- {
- return 0;
- }
-
- return o.hashCode();
- }
-
- /**
- * A collision-free hash code for small sets (<=4) of small, positive integers (<=128)
- *
- * @since 3.2
- */
- public static int hashCode(int... values)
- {
- int hash = 0;
- for (int i = 0; i < values.length; i++)
- {
- hash += values[i];
- hash = (hash << 7) - hash;
- }
-
- return hash;
- }
-
- public static int hashCode(long num)
- {
- return (int)(num >> 32) ^ (int)(num & 0xffffffff);
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T[] appendtoArray(T[] array, T... elements)
- {
- T[] result = (T[])Array.newInstance(array.getClass().getComponentType(), array.length + elements.length);
- System.arraycopy(array, 0, result, 0, array.length);
- System.arraycopy(elements, 0, result, array.length, elements.length);
- return result;
- }
-
- /**
- * @since 3.1
- */
- public static <T> boolean isEmpty(T[] array)
- {
- return array == null || array.length == 0;
- }
-
- /**
- * @since 3.1
- */
- public static <T extends Map<?, ?>> boolean isEmpty(Map<?, ?> map)
- {
- return map == null || map.isEmpty();
- }
-
- /**
- * @since 3.1
- */
- public static <T extends Collection<?>> boolean isEmpty(Collection<?> collection)
- {
- return collection == null || collection.isEmpty();
- }
-
- /**
- * @since 3.1
- */
- public static boolean isEmpty(String string)
- {
- return string == null || string.length() == 0;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +import java.lang.reflect.Array; +import java.util.Collection; +import java.util.Map; + +/** + * Various static helper methods. + * + * @author Eike Stepper + */ +public final class ObjectUtil +{ + private ObjectUtil() + { + } + + public static boolean equals(Object o1, Object o2) + { + if (o1 == null) + { + return o2 == null; + } + + return o1.equals(o2); + } + + public static int hashCode(Object o) + { + if (o == null) + { + return 0; + } + + return o.hashCode(); + } + + /** + * A collision-free hash code for small sets (<=4) of small, positive integers (<=128) + * + * @since 3.2 + */ + public static int hashCode(int... values) + { + int hash = 0; + for (int i = 0; i < values.length; i++) + { + hash += values[i]; + hash = (hash << 7) - hash; + } + + return hash; + } + + public static int hashCode(long num) + { + return (int)(num >> 32) ^ (int)(num & 0xffffffff); + } + + @SuppressWarnings("unchecked") + public static <T> T[] appendtoArray(T[] array, T... elements) + { + T[] result = (T[])Array.newInstance(array.getClass().getComponentType(), array.length + elements.length); + System.arraycopy(array, 0, result, 0, array.length); + System.arraycopy(elements, 0, result, array.length, elements.length); + return result; + } + + /** + * @since 3.1 + */ + public static <T> boolean isEmpty(T[] array) + { + return array == null || array.length == 0; + } + + /** + * @since 3.1 + */ + public static <T extends Map<?, ?>> boolean isEmpty(Map<?, ?> map) + { + return map == null || map.isEmpty(); + } + + /** + * @since 3.1 + */ + public static <T extends Collection<?>> boolean isEmpty(Collection<?> collection) + { + return collection == null || collection.isEmpty(); + } + + /** + * @since 3.1 + */ + public static boolean isEmpty(String string) + { + return string == null || string.length() == 0; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java index 3fb7bdd0a1..6a5cf3330c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/StringUtil.java @@ -1,393 +1,393 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-import org.eclipse.net4j.util.om.OMPlatform;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-
-/**
- * Various static helper methods for dealing with strings.
- *
- * @author Eike Stepper
- */
-public final class StringUtil
-{
- public static final String EMPTY = ""; //$NON-NLS-1$
-
- public static final String NL = OMPlatform.INSTANCE.getProperty("line.separator"); //$NON-NLS-1$
-
- private StringUtil()
- {
- }
-
- /**
- * @since 2.0
- */
- public static String formatException(Throwable t)
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- PrintStream s = new PrintStream(baos);
- t.printStackTrace(s);
- return baos.toString();
- }
-
- public static String replace(String text, String[] find, String[] replace)
- {
- for (int i = 0; i < find.length; i++)
- {
- int end = 0;
- for (;;)
- {
- int start = text.indexOf(find[i], end);
- if (start == -1)
- {
- break;
- }
-
- end = start + find[i].length();
- text = text.substring(0, start) + replace[i] + text.substring(end);
- }
- }
-
- return text;
- }
-
- public static String safe(String str)
- {
- if (str == null)
- {
- return EMPTY;
- }
-
- return str;
- }
-
- public static int compare(String s1, String s2)
- {
- if (s1 == null)
- {
- return s2 == null ? 0 : -1;
- }
-
- if (s2 == null)
- {
- return 1;
- }
-
- return s1.compareTo(s2);
- }
-
- /**
- * @since 3.1
- */
- public static boolean equalsUpperOrLowerCase(String s, String upperOrLowerCase)
- {
- if (s == null)
- {
- return upperOrLowerCase == null;
- }
-
- return s.equals(upperOrLowerCase.toLowerCase()) || s.equals(upperOrLowerCase.toUpperCase());
- }
-
- /**
- * @since 2.0
- */
- public static String capAll(String str)
- {
- if (str == null || str.length() == 0)
- {
- return str;
- }
-
- boolean inWhiteSpace = true;
- StringBuilder builder = new StringBuilder(str);
- for (int i = 0; i < builder.length(); i++)
- {
- char c = builder.charAt(i);
- boolean isWhiteSpace = Character.isWhitespace(c);
- if (!isWhiteSpace && inWhiteSpace)
- {
- builder.setCharAt(i, Character.toUpperCase(c));
- }
-
- inWhiteSpace = isWhiteSpace;
- }
-
- return builder.toString();
- }
-
- /**
- * @since 2.0
- */
- public static String uncapAll(String str)
- {
- if (str == null || str.length() == 0)
- {
- return str;
- }
-
- boolean inWhiteSpace = true;
- StringBuilder builder = new StringBuilder(str);
- for (int i = 0; i < builder.length(); i++)
- {
- char c = builder.charAt(i);
- boolean isWhiteSpace = Character.isWhitespace(c);
- if (!isWhiteSpace && inWhiteSpace)
- {
- builder.setCharAt(i, Character.toLowerCase(c));
- }
-
- inWhiteSpace = isWhiteSpace;
- }
-
- return builder.toString();
- }
-
- public static String cap(String str)
- {
- if (str == null || str.length() == 0)
- {
- return str;
- }
-
- char first = str.charAt(0);
- if (Character.isUpperCase(first))
- {
- return str;
- }
-
- if (str.length() == 1)
- {
- return str.toUpperCase();
- }
-
- StringBuilder builder = new StringBuilder(str);
- builder.setCharAt(0, Character.toUpperCase(first));
- return builder.toString();
- }
-
- public static String uncap(String str)
- {
- if (str == null || str.length() == 0)
- {
- return str;
- }
-
- char first = str.charAt(0);
- if (Character.isLowerCase(first))
- {
- return str;
- }
-
- if (str.length() == 1)
- {
- return str.toLowerCase();
- }
-
- StringBuilder builder = new StringBuilder(str);
- builder.setCharAt(0, Character.toLowerCase(first));
- return builder.toString();
- }
-
- public static int occurrences(String str, char c)
- {
- int count = 0;
- for (int i = 0; (i = str.indexOf(c, i)) != -1; ++i)
- {
- ++count;
- }
-
- return count;
- }
-
- public static int occurrences(String str, String c)
- {
- int count = 0;
- for (int i = 0; (i = str.indexOf(c, i)) != -1; i += c.length())
- {
- ++count;
- }
-
- return count;
- }
-
- public static boolean isEmpty(String str)
- {
- return ObjectUtil.isEmpty(str);
- }
-
- /**
- * Matches a string against a pattern.
- * <p>
- * Pattern description:
- * <ul>
- * <li><code>*</code> matches 0 or more characters
- * <li><code>?</code> matches a single character
- * <li><code>[...]</code> matches a set and/or range of characters
- * <li><code>\</code> escapes the following character
- * </ul>
- *
- * @since 2.0
- */
- public static boolean glob(String pattern, String string)
- {
- return glob(pattern, string, null);
- }
-
- /**
- * Matches a string against a pattern and fills an array with the sub-matches.
- * <p>
- * Pattern description:
- * <ul>
- * <li><code>*</code> matches 0 or more characters
- * <li><code>?</code> matches a single character
- * <li><code>[...]</code> matches a set and/or range of characters
- * <li><code>\</code> escapes the following character
- * </ul>
- *
- * @since 2.0
- */
- public static boolean glob(String pattern, String string, String[] subStrings)
- {
- return globRecurse(pattern, 0, string, 0, subStrings, 0);
- }
-
- private static boolean globRecurse(String pattern, int patternIndex, String string, int stringIndex,
- String[] subStrings, int subStringsIndex)
- {
- int patternLength = pattern.length();
- int stringLength = string.length();
-
- for (;;)
- {
- char patternChar = pattern.charAt(patternIndex);
- boolean endReached = stringIndex == stringLength;
- if (patternIndex == patternLength)
- {
- return endReached;
- }
- else if (endReached && patternChar != '*')
- {
- return false;
- }
-
- switch (patternChar)
- {
- case '*':
- {
- int startIndex = stringIndex;
- if (++patternIndex >= patternLength)
- {
- globRemember(string, startIndex, stringLength, subStrings, subStringsIndex);
- return true;
- }
-
- for (;;)
- {
- if (globRecurse(pattern, patternIndex, string, stringIndex, subStrings, subStringsIndex + 1))
- {
- globRemember(string, startIndex, stringIndex, subStrings, subStringsIndex);
- return true;
- }
-
- if (endReached)
- {
- return false;
- }
-
- ++stringIndex;
- }
- }
-
- case '?':
- ++patternIndex;
- globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++);
- break;
-
- case '[':
- try
- {
- ++patternIndex;
- char stringChar = string.charAt(stringIndex);
- char rangeStartChar = patternChar;
-
- while (true)
- {
- if (rangeStartChar == ']')
- {
- return false;
- }
-
- if (rangeStartChar == stringChar)
- {
- break;
- }
-
- ++patternIndex;
- char nextPatternChar = patternChar;
- if (nextPatternChar == '-')
- {
- ++patternIndex;
- char rangeEndChar = patternChar;
- if (rangeStartChar <= stringChar && stringChar <= rangeEndChar)
- {
- break;
- }
-
- ++patternIndex;
- nextPatternChar = patternChar;
- }
-
- rangeStartChar = nextPatternChar;
- }
-
- patternIndex = pattern.indexOf(']', patternIndex) + 1;
- if (patternIndex <= 0)
- {
- return false;
- }
-
- globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++);
- }
- catch (StringIndexOutOfBoundsException ex)
- {
- return false;
- }
-
- break;
-
- case '\\':
- if (++patternIndex >= patternLength)
- {
- return false;
- }
-
- //$FALL-THROUGH$
- default:
- if (patternChar++ != string.charAt(stringIndex++))
- {
- return false;
- }
- }
- }
- }
-
- private static void globRemember(String string, int start, int end, String[] subStrings, int subStringsIndex)
- {
- if (subStrings != null && subStringsIndex < subStrings.length)
- {
- subStrings[subStringsIndex] = string.substring(start, end);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +import org.eclipse.net4j.util.om.OMPlatform; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +/** + * Various static helper methods for dealing with strings. + * + * @author Eike Stepper + */ +public final class StringUtil +{ + public static final String EMPTY = ""; //$NON-NLS-1$ + + public static final String NL = OMPlatform.INSTANCE.getProperty("line.separator"); //$NON-NLS-1$ + + private StringUtil() + { + } + + /** + * @since 2.0 + */ + public static String formatException(Throwable t) + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream s = new PrintStream(baos); + t.printStackTrace(s); + return baos.toString(); + } + + public static String replace(String text, String[] find, String[] replace) + { + for (int i = 0; i < find.length; i++) + { + int end = 0; + for (;;) + { + int start = text.indexOf(find[i], end); + if (start == -1) + { + break; + } + + end = start + find[i].length(); + text = text.substring(0, start) + replace[i] + text.substring(end); + } + } + + return text; + } + + public static String safe(String str) + { + if (str == null) + { + return EMPTY; + } + + return str; + } + + public static int compare(String s1, String s2) + { + if (s1 == null) + { + return s2 == null ? 0 : -1; + } + + if (s2 == null) + { + return 1; + } + + return s1.compareTo(s2); + } + + /** + * @since 3.1 + */ + public static boolean equalsUpperOrLowerCase(String s, String upperOrLowerCase) + { + if (s == null) + { + return upperOrLowerCase == null; + } + + return s.equals(upperOrLowerCase.toLowerCase()) || s.equals(upperOrLowerCase.toUpperCase()); + } + + /** + * @since 2.0 + */ + public static String capAll(String str) + { + if (str == null || str.length() == 0) + { + return str; + } + + boolean inWhiteSpace = true; + StringBuilder builder = new StringBuilder(str); + for (int i = 0; i < builder.length(); i++) + { + char c = builder.charAt(i); + boolean isWhiteSpace = Character.isWhitespace(c); + if (!isWhiteSpace && inWhiteSpace) + { + builder.setCharAt(i, Character.toUpperCase(c)); + } + + inWhiteSpace = isWhiteSpace; + } + + return builder.toString(); + } + + /** + * @since 2.0 + */ + public static String uncapAll(String str) + { + if (str == null || str.length() == 0) + { + return str; + } + + boolean inWhiteSpace = true; + StringBuilder builder = new StringBuilder(str); + for (int i = 0; i < builder.length(); i++) + { + char c = builder.charAt(i); + boolean isWhiteSpace = Character.isWhitespace(c); + if (!isWhiteSpace && inWhiteSpace) + { + builder.setCharAt(i, Character.toLowerCase(c)); + } + + inWhiteSpace = isWhiteSpace; + } + + return builder.toString(); + } + + public static String cap(String str) + { + if (str == null || str.length() == 0) + { + return str; + } + + char first = str.charAt(0); + if (Character.isUpperCase(first)) + { + return str; + } + + if (str.length() == 1) + { + return str.toUpperCase(); + } + + StringBuilder builder = new StringBuilder(str); + builder.setCharAt(0, Character.toUpperCase(first)); + return builder.toString(); + } + + public static String uncap(String str) + { + if (str == null || str.length() == 0) + { + return str; + } + + char first = str.charAt(0); + if (Character.isLowerCase(first)) + { + return str; + } + + if (str.length() == 1) + { + return str.toLowerCase(); + } + + StringBuilder builder = new StringBuilder(str); + builder.setCharAt(0, Character.toLowerCase(first)); + return builder.toString(); + } + + public static int occurrences(String str, char c) + { + int count = 0; + for (int i = 0; (i = str.indexOf(c, i)) != -1; ++i) + { + ++count; + } + + return count; + } + + public static int occurrences(String str, String c) + { + int count = 0; + for (int i = 0; (i = str.indexOf(c, i)) != -1; i += c.length()) + { + ++count; + } + + return count; + } + + public static boolean isEmpty(String str) + { + return ObjectUtil.isEmpty(str); + } + + /** + * Matches a string against a pattern. + * <p> + * Pattern description: + * <ul> + * <li><code>*</code> matches 0 or more characters + * <li><code>?</code> matches a single character + * <li><code>[...]</code> matches a set and/or range of characters + * <li><code>\</code> escapes the following character + * </ul> + * + * @since 2.0 + */ + public static boolean glob(String pattern, String string) + { + return glob(pattern, string, null); + } + + /** + * Matches a string against a pattern and fills an array with the sub-matches. + * <p> + * Pattern description: + * <ul> + * <li><code>*</code> matches 0 or more characters + * <li><code>?</code> matches a single character + * <li><code>[...]</code> matches a set and/or range of characters + * <li><code>\</code> escapes the following character + * </ul> + * + * @since 2.0 + */ + public static boolean glob(String pattern, String string, String[] subStrings) + { + return globRecurse(pattern, 0, string, 0, subStrings, 0); + } + + private static boolean globRecurse(String pattern, int patternIndex, String string, int stringIndex, + String[] subStrings, int subStringsIndex) + { + int patternLength = pattern.length(); + int stringLength = string.length(); + + for (;;) + { + char patternChar = pattern.charAt(patternIndex); + boolean endReached = stringIndex == stringLength; + if (patternIndex == patternLength) + { + return endReached; + } + else if (endReached && patternChar != '*') + { + return false; + } + + switch (patternChar) + { + case '*': + { + int startIndex = stringIndex; + if (++patternIndex >= patternLength) + { + globRemember(string, startIndex, stringLength, subStrings, subStringsIndex); + return true; + } + + for (;;) + { + if (globRecurse(pattern, patternIndex, string, stringIndex, subStrings, subStringsIndex + 1)) + { + globRemember(string, startIndex, stringIndex, subStrings, subStringsIndex); + return true; + } + + if (endReached) + { + return false; + } + + ++stringIndex; + } + } + + case '?': + ++patternIndex; + globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++); + break; + + case '[': + try + { + ++patternIndex; + char stringChar = string.charAt(stringIndex); + char rangeStartChar = patternChar; + + while (true) + { + if (rangeStartChar == ']') + { + return false; + } + + if (rangeStartChar == stringChar) + { + break; + } + + ++patternIndex; + char nextPatternChar = patternChar; + if (nextPatternChar == '-') + { + ++patternIndex; + char rangeEndChar = patternChar; + if (rangeStartChar <= stringChar && stringChar <= rangeEndChar) + { + break; + } + + ++patternIndex; + nextPatternChar = patternChar; + } + + rangeStartChar = nextPatternChar; + } + + patternIndex = pattern.indexOf(']', patternIndex) + 1; + if (patternIndex <= 0) + { + return false; + } + + globRemember(string, stringIndex, ++stringIndex, subStrings, subStringsIndex++); + } + catch (StringIndexOutOfBoundsException ex) + { + return false; + } + + break; + + case '\\': + if (++patternIndex >= patternLength) + { + return false; + } + + //$FALL-THROUGH$ + default: + if (patternChar++ != string.charAt(stringIndex++)) + { + return false; + } + } + } + } + + private static void globRemember(String string, int start, int end, String[] subStrings, int subStringsIndex) + { + if (subStrings != null && subStringsIndex < subStrings.length) + { + subStrings[subStringsIndex] = string.substring(start, end); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java index 82a1f8e45a..c6bae605ff 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/UUIDGenerator.java @@ -1,379 +1,379 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-import java.lang.reflect.Method;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.security.SecureRandom;
-import java.util.Enumeration;
-import java.util.GregorianCalendar;
-import java.util.Random;
-
-/**
- * Generates 16 byte UUID values and can encode them to Strings, decode from Strings respectively.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public final class UUIDGenerator
-{
- public static final int NODE_ADDRESS_BYTES = 6;
-
- public static final UUIDGenerator DEFAULT = new UUIDGenerator();
-
- public UUIDGenerator(byte[] nodeAddress)
- {
- Random random = new SecureRandom();
-
- clockSequence = (short)random.nextInt(16384);
- updateClockSequence();
-
- if (nodeAddress == null)
- {
- try
- {
- nodeAddress = getHardwareAddress();
- }
- catch (Throwable ex)
- {
- //$FALL-THROUGH$
- }
-
- if (nodeAddress == null || nodeAddress.length != NODE_ADDRESS_BYTES)
- {
- // Generate a 48 bit node identifier;
- // This is an alternative to the IEEE 802 host address, which is not available in Java.
- nodeAddress = new byte[NODE_ADDRESS_BYTES];
- random.nextBytes(nodeAddress);
- }
- }
-
- setNodeAddress(nodeAddress);
- }
-
- public UUIDGenerator()
- {
- this(null);
- }
-
- public synchronized String generate()
- {
- updateCurrentTime();
- encode(uuid, buffer);
- return new String(buffer);
- }
-
- public synchronized void generate(byte[] uuid)
- {
- updateCurrentTime();
-
- for (int i = 0; i < 16; i++)
- {
- uuid[i] = this.uuid[i];
- }
- }
-
- public String encode(byte[] uuid)
- {
- char[] buffer = createBuffer();
- encode(uuid, buffer);
- return new String(buffer);
- }
-
- public byte[] decode(String string)
- {
- byte[] uuid = createUUID();
-
- char c1;
- char c2;
- char c3;
- char c4;
-
- int i1;
- int i2;
- int i3;
- int i4;
-
- for (int i = 0; i < 5; ++i)
- {
- c1 = string.charAt(4 * i + 1);
- c2 = string.charAt(4 * i + 2);
- c3 = string.charAt(4 * i + 3);
- c4 = string.charAt(4 * i + 4);
-
- i1 = BASE64_INDEX[c1 - BASE64_INDEX_OFFSET];
- i2 = BASE64_INDEX[c2 - BASE64_INDEX_OFFSET];
- i3 = BASE64_INDEX[c3 - BASE64_INDEX_OFFSET];
- i4 = BASE64_INDEX[c4 - BASE64_INDEX_OFFSET];
-
- uuid[3 * i] = (byte)(i1 << 2 | i2 >>> 4);
- uuid[3 * i + 1] = (byte)((i2 & 0xF) << 4 | i3 >>> 2);
- uuid[3 * i + 2] = (byte)((i3 & 0x3) << 6 | i4);
- }
-
- // Handle the last chars at the end.
- //
- c1 = string.charAt(21);
- c2 = string.charAt(22);
-
- i1 = BASE64_INDEX[c1 - BASE64_INDEX_OFFSET];
- i2 = BASE64_INDEX[c2 - BASE64_INDEX_OFFSET];
-
- uuid[15] = (byte)(i1 << 2 | i2 >>> 4);
-
- return uuid;
- }
-
- private static final char[] BASE64_DIGITS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
- 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
- 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', '-', '_' };
-
- private static final byte[] BASE64_INDEX;
-
- private static final int BASE64_INDEX_OFFSET;
-
- /**
- * An adjustment to convert the Java epoch of Jan 1, 1970 00:00:00 to the epoch required by the IETF specification,
- * Oct 15, 1582 00:00:00.
- */
- private static final long EPOCH_ADJUSTMENT = new GregorianCalendar(1970, 0, 1, 0, 0, 0).getTime().getTime()
- - new GregorianCalendar(1582, 9, 15, 0, 0, 0).getTime().getTime();
-
- private long lastTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT;
-
- private short clockSequence;
-
- private short timeAdjustment;
-
- private int sleepTime = 1;
-
- private final char[] buffer = createBuffer();
-
- /**
- * A cached array of bytes representing the UUID. The second 8 bytes will be kept the same unless the clock sequence
- * has changed.
- */
- private final byte[] uuid = createUUID();
-
- static
- {
- byte[] index = new byte[256];
- int min = Integer.MAX_VALUE;
- int max = Integer.MIN_VALUE;
-
- for (byte i = 0; i < BASE64_DIGITS.length; i++)
- {
- char digit = BASE64_DIGITS[i];
- if (digit < min)
- {
- min = digit;
- }
-
- if (digit > max)
- {
- max = digit;
- }
-
- index[digit] = i;
- }
-
- int length = max - min + 1;
- BASE64_INDEX = new byte[length];
- BASE64_INDEX_OFFSET = min;
- System.arraycopy(index, BASE64_INDEX_OFFSET, BASE64_INDEX, 0, length);
- }
-
- private byte[] getHardwareAddress() throws Throwable
- {
- // getHardwareAddress is a JRE 1.6 method and must be called reflectiviely
- Method method = ReflectUtil.getMethod(NetworkInterface.class, "getHardwareAddress");
-
- Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
- while (networkInterfaces.hasMoreElements())
- {
- NetworkInterface networkInterface = networkInterfaces.nextElement();
-
- try
- {
- byte[] nodeAddress = (byte[])ReflectUtil.invokeMethod(method, networkInterface);
- if (nodeAddress != null && nodeAddress.length == NODE_ADDRESS_BYTES)
- {
- return nodeAddress;
- }
- }
- catch (Throwable ex)
- {
- //$FALL-THROUGH$
- }
- }
-
- throw new SocketException("Hardware address could not be determined");
- }
-
- private void setNodeAddress(byte[] nodeAddress)
- {
- // Set the most significant bit of the first octet to 1 so as to distinguish it from IEEE node addresses
- //
- nodeAddress[0] |= (byte)0x80;
-
- // The node identifier is already in network byte order,
- // so there is no need to do any byte order reversing.
- //
- for (int i = 0; i < NODE_ADDRESS_BYTES; ++i)
- {
- uuid[i + 10] = nodeAddress[i];
- }
- }
-
- /**
- * Updates the clock sequence portion of the UUID. The clock sequence portion may seem odd, but in the specification,
- * the high order byte comes before the low order byte. The variant is multiplexed into the high order octet of
- * clockseq_hi.
- */
- private void updateClockSequence()
- {
- // clockseq_hi
- uuid[8] = (byte)(clockSequence >> 8 & 0x3F | 0x80);
- // clockseq_low
- uuid[9] = (byte)(clockSequence & 0xFF);
- }
-
- /**
- * Updates the UUID with the current time, compensating for the fact that the clock resolution may be less than 100
- * ns. The byte array will have its first eight bytes populated with the time in the correct sequence of bytes, as per
- * the specification.
- */
- private void updateCurrentTime()
- {
- // Get the current time in milliseconds since the epoch
- // and adjust it to match the epoch required by the specification.
- //
- long currentTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT;
-
- if (lastTime > currentTime)
- {
- // The system clock has been rewound so the clock sequence must be incremented
- // to ensure that a duplicate UUID is not generated.
- //
- ++clockSequence;
-
- if (16384 == clockSequence)
- {
- clockSequence = 0;
- }
-
- updateClockSequence();
- }
- else if (lastTime == currentTime)
- {
- // The system time hasn't changed so add some increment of 100s of nanoseconds to guarantee uniqueness.
- //
- ++timeAdjustment;
-
- if (timeAdjustment > 9999)
- {
- // Wait so that the clock can catch up and the time adjustment won't overflow.
- try
- {
- Thread.sleep(sleepTime);
- }
- catch (InterruptedException exception)
- {
- // We just woke up.
- }
-
- timeAdjustment = 0;
- currentTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT;
-
- while (lastTime == currentTime)
- {
- try
- {
- ++sleepTime;
- Thread.sleep(1);
- }
- catch (InterruptedException exception)
- {
- // We just woke up.
- }
- currentTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT;
- }
- }
- }
- else
- {
- timeAdjustment = 0;
- }
-
- lastTime = currentTime;
-
- // Since the granularity of time in Java is only milliseconds,
- // add an adjustment so that the time is represented in 100s of nanoseconds.
- // The version number (1) is multiplexed into the most significant hex digit.
- //
- currentTime *= 10000;
- currentTime += timeAdjustment;
- currentTime |= 0x1000000000000000L;
-
- // Place the time into the byte array in network byte order.
- //
- for (int i = 0; i < 4; ++i)
- {
- // time_low
- //
- uuid[i] = (byte)(currentTime >> 8 * (3 - i) & 0xFFL);
- }
-
- for (int i = 0; i < 2; ++i)
- {
- // time_mid
- //
- uuid[i + 4] = (byte)(currentTime >> 8 * (1 - i) + 32 & 0xFFL);
- }
-
- for (int i = 0; i < 2; ++i)
- {
- // time_hi
- //
- uuid[i + 6] = (byte)(currentTime >> 8 * (1 - i) + 48 & 0xFFL);
- }
- }
-
- private void encode(byte[] uuid, char[] buffer)
- {
- for (int i = 0; i < 5; ++i)
- {
- buffer[4 * i + 1] = BASE64_DIGITS[uuid[i * 3] >> 2 & 0x3F];
- buffer[4 * i + 2] = BASE64_DIGITS[uuid[i * 3] << 4 & 0x30 | uuid[i * 3 + 1] >> 4 & 0xF];
- buffer[4 * i + 3] = BASE64_DIGITS[uuid[i * 3 + 1] << 2 & 0x3C | uuid[i * 3 + 2] >> 6 & 0x3];
- buffer[4 * i + 4] = BASE64_DIGITS[uuid[i * 3 + 2] & 0x3F];
- }
-
- // Handle the last byte at the end.
- //
- buffer[21] = BASE64_DIGITS[uuid[15] >> 2 & 0x3F];
- buffer[22] = BASE64_DIGITS[uuid[15] << 4 & 0x30];
- }
-
- private byte[] createUUID()
- {
- return new byte[16];
- }
-
- private char[] createBuffer()
- {
- char[] buffer = new char[23];
- buffer[0] = '_';
- return buffer;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +import java.lang.reflect.Method; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.security.SecureRandom; +import java.util.Enumeration; +import java.util.GregorianCalendar; +import java.util.Random; + +/** + * Generates 16 byte UUID values and can encode them to Strings, decode from Strings respectively. + * + * @author Eike Stepper + * @since 3.2 + */ +public final class UUIDGenerator +{ + public static final int NODE_ADDRESS_BYTES = 6; + + public static final UUIDGenerator DEFAULT = new UUIDGenerator(); + + public UUIDGenerator(byte[] nodeAddress) + { + Random random = new SecureRandom(); + + clockSequence = (short)random.nextInt(16384); + updateClockSequence(); + + if (nodeAddress == null) + { + try + { + nodeAddress = getHardwareAddress(); + } + catch (Throwable ex) + { + //$FALL-THROUGH$ + } + + if (nodeAddress == null || nodeAddress.length != NODE_ADDRESS_BYTES) + { + // Generate a 48 bit node identifier; + // This is an alternative to the IEEE 802 host address, which is not available in Java. + nodeAddress = new byte[NODE_ADDRESS_BYTES]; + random.nextBytes(nodeAddress); + } + } + + setNodeAddress(nodeAddress); + } + + public UUIDGenerator() + { + this(null); + } + + public synchronized String generate() + { + updateCurrentTime(); + encode(uuid, buffer); + return new String(buffer); + } + + public synchronized void generate(byte[] uuid) + { + updateCurrentTime(); + + for (int i = 0; i < 16; i++) + { + uuid[i] = this.uuid[i]; + } + } + + public String encode(byte[] uuid) + { + char[] buffer = createBuffer(); + encode(uuid, buffer); + return new String(buffer); + } + + public byte[] decode(String string) + { + byte[] uuid = createUUID(); + + char c1; + char c2; + char c3; + char c4; + + int i1; + int i2; + int i3; + int i4; + + for (int i = 0; i < 5; ++i) + { + c1 = string.charAt(4 * i + 1); + c2 = string.charAt(4 * i + 2); + c3 = string.charAt(4 * i + 3); + c4 = string.charAt(4 * i + 4); + + i1 = BASE64_INDEX[c1 - BASE64_INDEX_OFFSET]; + i2 = BASE64_INDEX[c2 - BASE64_INDEX_OFFSET]; + i3 = BASE64_INDEX[c3 - BASE64_INDEX_OFFSET]; + i4 = BASE64_INDEX[c4 - BASE64_INDEX_OFFSET]; + + uuid[3 * i] = (byte)(i1 << 2 | i2 >>> 4); + uuid[3 * i + 1] = (byte)((i2 & 0xF) << 4 | i3 >>> 2); + uuid[3 * i + 2] = (byte)((i3 & 0x3) << 6 | i4); + } + + // Handle the last chars at the end. + // + c1 = string.charAt(21); + c2 = string.charAt(22); + + i1 = BASE64_INDEX[c1 - BASE64_INDEX_OFFSET]; + i2 = BASE64_INDEX[c2 - BASE64_INDEX_OFFSET]; + + uuid[15] = (byte)(i1 << 2 | i2 >>> 4); + + return uuid; + } + + private static final char[] BASE64_DIGITS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', + 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', + '6', '7', '8', '9', '-', '_' }; + + private static final byte[] BASE64_INDEX; + + private static final int BASE64_INDEX_OFFSET; + + /** + * An adjustment to convert the Java epoch of Jan 1, 1970 00:00:00 to the epoch required by the IETF specification, + * Oct 15, 1582 00:00:00. + */ + private static final long EPOCH_ADJUSTMENT = new GregorianCalendar(1970, 0, 1, 0, 0, 0).getTime().getTime() + - new GregorianCalendar(1582, 9, 15, 0, 0, 0).getTime().getTime(); + + private long lastTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT; + + private short clockSequence; + + private short timeAdjustment; + + private int sleepTime = 1; + + private final char[] buffer = createBuffer(); + + /** + * A cached array of bytes representing the UUID. The second 8 bytes will be kept the same unless the clock sequence + * has changed. + */ + private final byte[] uuid = createUUID(); + + static + { + byte[] index = new byte[256]; + int min = Integer.MAX_VALUE; + int max = Integer.MIN_VALUE; + + for (byte i = 0; i < BASE64_DIGITS.length; i++) + { + char digit = BASE64_DIGITS[i]; + if (digit < min) + { + min = digit; + } + + if (digit > max) + { + max = digit; + } + + index[digit] = i; + } + + int length = max - min + 1; + BASE64_INDEX = new byte[length]; + BASE64_INDEX_OFFSET = min; + System.arraycopy(index, BASE64_INDEX_OFFSET, BASE64_INDEX, 0, length); + } + + private byte[] getHardwareAddress() throws Throwable + { + // getHardwareAddress is a JRE 1.6 method and must be called reflectiviely + Method method = ReflectUtil.getMethod(NetworkInterface.class, "getHardwareAddress"); + + Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); + while (networkInterfaces.hasMoreElements()) + { + NetworkInterface networkInterface = networkInterfaces.nextElement(); + + try + { + byte[] nodeAddress = (byte[])ReflectUtil.invokeMethod(method, networkInterface); + if (nodeAddress != null && nodeAddress.length == NODE_ADDRESS_BYTES) + { + return nodeAddress; + } + } + catch (Throwable ex) + { + //$FALL-THROUGH$ + } + } + + throw new SocketException("Hardware address could not be determined"); + } + + private void setNodeAddress(byte[] nodeAddress) + { + // Set the most significant bit of the first octet to 1 so as to distinguish it from IEEE node addresses + // + nodeAddress[0] |= (byte)0x80; + + // The node identifier is already in network byte order, + // so there is no need to do any byte order reversing. + // + for (int i = 0; i < NODE_ADDRESS_BYTES; ++i) + { + uuid[i + 10] = nodeAddress[i]; + } + } + + /** + * Updates the clock sequence portion of the UUID. The clock sequence portion may seem odd, but in the specification, + * the high order byte comes before the low order byte. The variant is multiplexed into the high order octet of + * clockseq_hi. + */ + private void updateClockSequence() + { + // clockseq_hi + uuid[8] = (byte)(clockSequence >> 8 & 0x3F | 0x80); + // clockseq_low + uuid[9] = (byte)(clockSequence & 0xFF); + } + + /** + * Updates the UUID with the current time, compensating for the fact that the clock resolution may be less than 100 + * ns. The byte array will have its first eight bytes populated with the time in the correct sequence of bytes, as per + * the specification. + */ + private void updateCurrentTime() + { + // Get the current time in milliseconds since the epoch + // and adjust it to match the epoch required by the specification. + // + long currentTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT; + + if (lastTime > currentTime) + { + // The system clock has been rewound so the clock sequence must be incremented + // to ensure that a duplicate UUID is not generated. + // + ++clockSequence; + + if (16384 == clockSequence) + { + clockSequence = 0; + } + + updateClockSequence(); + } + else if (lastTime == currentTime) + { + // The system time hasn't changed so add some increment of 100s of nanoseconds to guarantee uniqueness. + // + ++timeAdjustment; + + if (timeAdjustment > 9999) + { + // Wait so that the clock can catch up and the time adjustment won't overflow. + try + { + Thread.sleep(sleepTime); + } + catch (InterruptedException exception) + { + // We just woke up. + } + + timeAdjustment = 0; + currentTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT; + + while (lastTime == currentTime) + { + try + { + ++sleepTime; + Thread.sleep(1); + } + catch (InterruptedException exception) + { + // We just woke up. + } + currentTime = System.currentTimeMillis() + EPOCH_ADJUSTMENT; + } + } + } + else + { + timeAdjustment = 0; + } + + lastTime = currentTime; + + // Since the granularity of time in Java is only milliseconds, + // add an adjustment so that the time is represented in 100s of nanoseconds. + // The version number (1) is multiplexed into the most significant hex digit. + // + currentTime *= 10000; + currentTime += timeAdjustment; + currentTime |= 0x1000000000000000L; + + // Place the time into the byte array in network byte order. + // + for (int i = 0; i < 4; ++i) + { + // time_low + // + uuid[i] = (byte)(currentTime >> 8 * (3 - i) & 0xFFL); + } + + for (int i = 0; i < 2; ++i) + { + // time_mid + // + uuid[i + 4] = (byte)(currentTime >> 8 * (1 - i) + 32 & 0xFFL); + } + + for (int i = 0; i < 2; ++i) + { + // time_hi + // + uuid[i + 6] = (byte)(currentTime >> 8 * (1 - i) + 48 & 0xFFL); + } + } + + private void encode(byte[] uuid, char[] buffer) + { + for (int i = 0; i < 5; ++i) + { + buffer[4 * i + 1] = BASE64_DIGITS[uuid[i * 3] >> 2 & 0x3F]; + buffer[4 * i + 2] = BASE64_DIGITS[uuid[i * 3] << 4 & 0x30 | uuid[i * 3 + 1] >> 4 & 0xF]; + buffer[4 * i + 3] = BASE64_DIGITS[uuid[i * 3 + 1] << 2 & 0x3C | uuid[i * 3 + 2] >> 6 & 0x3]; + buffer[4 * i + 4] = BASE64_DIGITS[uuid[i * 3 + 2] & 0x3F]; + } + + // Handle the last byte at the end. + // + buffer[21] = BASE64_DIGITS[uuid[15] >> 2 & 0x3F]; + buffer[22] = BASE64_DIGITS[uuid[15] << 4 & 0x30]; + } + + private byte[] createUUID() + { + return new byte[16]; + } + + private char[] createBuffer() + { + char[] buffer = new char[23]; + buffer[0] = '_'; + return buffer; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java index 7ee8967faf..38649ba74e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/WrappedException.java @@ -1,66 +1,66 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util;
-
-/**
- * An unchecked exception that wraps a checked exception. Wrapping occurs conditionally in the static
- * {@link #wrap(Exception, String) wrap()} methods.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- */
-public class WrappedException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- private WrappedException(Exception exception)
- {
- super(exception);
- }
-
- private WrappedException(String message, Exception exception)
- {
- super(message, exception);
- }
-
- public Exception exception()
- {
- return (Exception)getCause();
- }
-
- /**
- * @since 3.1
- */
- public static RuntimeException wrap(Exception exception, String message)
- {
- return new WrappedException(message, exception);
- }
-
- public static RuntimeException wrap(Exception exception)
- {
- if (exception instanceof RuntimeException)
- {
- return (RuntimeException)exception;
- }
-
- return new WrappedException(exception);
- }
-
- public static Exception unwrap(Exception exception)
- {
- if (exception instanceof WrappedException)
- {
- return ((WrappedException)exception).exception();
- }
-
- return exception;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util; + +/** + * An unchecked exception that wraps a checked exception. Wrapping occurs conditionally in the static + * {@link #wrap(Exception, String) wrap()} methods. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + */ +public class WrappedException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + private WrappedException(Exception exception) + { + super(exception); + } + + private WrappedException(String message, Exception exception) + { + super(message, exception); + } + + public Exception exception() + { + return (Exception)getCause(); + } + + /** + * @since 3.1 + */ + public static RuntimeException wrap(Exception exception, String message) + { + return new WrappedException(message, exception); + } + + public static RuntimeException wrap(Exception exception) + { + if (exception instanceof RuntimeException) + { + return (RuntimeException)exception; + } + + return new WrappedException(exception); + } + + public static Exception unwrap(Exception exception) + { + if (exception instanceof WrappedException) + { + return ((WrappedException)exception).exception(); + } + + return exception; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java index c4de6167a0..14a8448fa5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/Cache.java @@ -1,108 +1,108 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.concurrent.Worker;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-
-/**
- * @author Eike Stepper
- */
-public abstract class Cache<E> extends Worker implements ICache
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class);
-
- private ICacheMonitor cacheMonitor;
-
- private ICacheProbe cacheProbe;
-
- private ReferenceQueue<E> referenceQueue = new ReferenceQueue<E>();
-
- public Cache()
- {
- }
-
- public ICacheMonitor getCacheMonitor()
- {
- return cacheMonitor;
- }
-
- public void setCacheMonitor(ICacheMonitor cacheMonitor)
- {
- this.cacheMonitor = cacheMonitor;
- }
-
- protected ICacheProbe getCacheProbe()
- {
- return cacheProbe;
- }
-
- protected ReferenceQueue<E> getReferenceQueue()
- {
- return referenceQueue;
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- if (cacheMonitor == null)
- {
- throw new IllegalStateException("cacheMonitor == null"); //$NON-NLS-1$
- }
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- cacheProbe = cacheMonitor.registerCache(this);
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- cacheMonitor.deregisterCache(this);
- cacheProbe = null;
- super.doDeactivate();
- }
-
- @Override
- protected void work(WorkContext context) throws Exception
- {
- Reference<? extends E> reference = referenceQueue.remove(200);
- if (reference != null)
- {
- unreachableElement(reference);
- }
- }
-
- protected void unreachableElement(Reference<? extends E> reference)
- {
- E element = reference.get();
- if (element != null)
- {
- unreachableElement(element);
- }
- }
-
- protected void unreachableElement(E element)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Unreachable: " + element); //$NON-NLS-1$
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.concurrent.Worker; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; + +/** + * @author Eike Stepper + */ +public abstract class Cache<E> extends Worker implements ICache +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class); + + private ICacheMonitor cacheMonitor; + + private ICacheProbe cacheProbe; + + private ReferenceQueue<E> referenceQueue = new ReferenceQueue<E>(); + + public Cache() + { + } + + public ICacheMonitor getCacheMonitor() + { + return cacheMonitor; + } + + public void setCacheMonitor(ICacheMonitor cacheMonitor) + { + this.cacheMonitor = cacheMonitor; + } + + protected ICacheProbe getCacheProbe() + { + return cacheProbe; + } + + protected ReferenceQueue<E> getReferenceQueue() + { + return referenceQueue; + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + if (cacheMonitor == null) + { + throw new IllegalStateException("cacheMonitor == null"); //$NON-NLS-1$ + } + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + cacheProbe = cacheMonitor.registerCache(this); + } + + @Override + protected void doDeactivate() throws Exception + { + cacheMonitor.deregisterCache(this); + cacheProbe = null; + super.doDeactivate(); + } + + @Override + protected void work(WorkContext context) throws Exception + { + Reference<? extends E> reference = referenceQueue.remove(200); + if (reference != null) + { + unreachableElement(reference); + } + } + + protected void unreachableElement(Reference<? extends E> reference) + { + E element = reference.get(); + if (element != null) + { + unreachableElement(element); + } + } + + protected void unreachableElement(E element) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Unreachable: " + element); //$NON-NLS-1$ + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java index f4dc24ce36..b5ff052923 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheMonitor.java @@ -1,251 +1,251 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.ImplementationError;
-import org.eclipse.net4j.util.concurrent.Worker;
-import org.eclipse.net4j.util.event.Event;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public class CacheMonitor extends Worker implements ICacheMonitor
-{
- // percentFreeAllocated = Round((freeMemory / totalMemory) * 100);
- // percentAllocated = Round((totalMemory / maxMemory ) * 100);
-
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CacheMonitor.class);
-
- private static final long DEFAULT_PAUSE_GREEN = 60L * 1000L; // 1 minute
-
- private static final long DEFAULT_PAUSE_YELLOW = 5L * 1000L; // 5 seconds
-
- private static final long DEFAULT_PAUSE_RED = 100L; // 100 milliseconds
-
- private long pauseGREEN = DEFAULT_PAUSE_GREEN;
-
- private long pauseYELLOW = DEFAULT_PAUSE_YELLOW;
-
- private long pauseRED = DEFAULT_PAUSE_RED;
-
- private ConditionPolicy conditionPolicy;
-
- private Condition condition;
-
- private Map<ICache, ICacheRegistration> registrations = new HashMap<ICache, ICacheRegistration>();
-
- public CacheMonitor()
- {
- }
-
- public long getPauseGREEN()
- {
- return pauseGREEN;
- }
-
- public void setPauseGREEN(long pauseGREEN)
- {
- this.pauseGREEN = pauseGREEN;
- }
-
- public long getPauseYELLOW()
- {
- return pauseYELLOW;
- }
-
- public void setPauseYELLOW(long pauseYELLOW)
- {
- this.pauseYELLOW = pauseYELLOW;
- }
-
- public long getPauseRED()
- {
- return pauseRED;
- }
-
- public void setPauseRED(long pauseRED)
- {
- this.pauseRED = pauseRED;
- }
-
- public ConditionPolicy getConditionPolicy()
- {
- return conditionPolicy;
- }
-
- public void setConditionPolicy(ConditionPolicy conditionPolicy)
- {
- this.conditionPolicy = conditionPolicy;
- }
-
- public Condition getCondition()
- {
- return condition;
- }
-
- public ICacheRegistration[] getRegistrations()
- {
- synchronized (registrations)
- {
- return registrations.values().toArray(new ICacheRegistration[registrations.size()]);
- }
- }
-
- public ICacheRegistration registerCache(ICache cache)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace("Registering cache " + cache); //$NON-NLS-1$
- }
-
- ICacheRegistration registration = new CacheRegistration(this, cache);
- ICacheRegistration oldRegistration;
- synchronized (registrations)
- {
- oldRegistration = registrations.put(cache, registration);
- }
-
- if (oldRegistration != null)
- {
- oldRegistration.dispose();
- }
-
- return registration;
- }
-
- public void deregisterCache(ICache cache)
- {
- ICacheRegistration registration;
- synchronized (registrations)
- {
- registration = registrations.remove(cache);
- }
-
- if (registration != null)
- {
- registration.dispose();
- if (TRACER.isEnabled())
- {
- TRACER.trace("Deregistered cache " + cache); //$NON-NLS-1$
- }
- }
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- if (conditionPolicy == null)
- {
- throw new IllegalStateException("conditionPolicy == null"); //$NON-NLS-1$
- }
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- for (ICacheRegistration registration : getRegistrations())
- {
- registration.dispose();
- }
-
- registrations.clear();
- super.doDeactivate();
- }
-
- @Override
- protected void work(WorkContext context) throws Exception
- {
- Condition newCondition = conditionPolicy.getNewCondition(condition);
- setCondition(newCondition);
-
- switch (newCondition)
- {
- case GREEN:
- context.nextWork(pauseGREEN);
- break;
-
- case YELLOW:
- context.nextWork(pauseYELLOW);
- break;
-
- case RED:
- handleConditionRED();
- context.nextWork(pauseRED);
- break;
- }
- }
-
- protected void setCondition(Condition newCondition)
- {
- if (newCondition == null)
- {
- throw new ImplementationError("newCondition == null"); //$NON-NLS-1$
- }
-
- Condition oldCondition = condition;
- if (newCondition != oldCondition)
- {
- condition = newCondition;
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(new CacheMonitorEvent(oldCondition, newCondition), listeners);
- }
- }
- }
-
- protected void handleConditionRED()
- {
- OM.LOG.warn("CONDITION RED"); //$NON-NLS-1$
- }
-
- /**
- * @author Eike Stepper
- */
- private final class CacheMonitorEvent extends Event implements ICacheMonitorEvent
- {
- private static final long serialVersionUID = 1L;
-
- private Condition oldCondition;
-
- private Condition newCondition;
-
- public CacheMonitorEvent(Condition oldCondition, Condition newCondition)
- {
- super(CacheMonitor.this);
- this.oldCondition = oldCondition;
- this.newCondition = newCondition;
- }
-
- @Override
- public ICacheMonitor getSource()
- {
- return (ICacheMonitor)super.getSource();
- }
-
- public Condition getOldCondition()
- {
- return oldCondition;
- }
-
- public Condition getNewCondition()
- {
- return newCondition;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.ImplementationError; +import org.eclipse.net4j.util.concurrent.Worker; +import org.eclipse.net4j.util.event.Event; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public class CacheMonitor extends Worker implements ICacheMonitor +{ + // percentFreeAllocated = Round((freeMemory / totalMemory) * 100); + // percentAllocated = Round((totalMemory / maxMemory ) * 100); + + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, CacheMonitor.class); + + private static final long DEFAULT_PAUSE_GREEN = 60L * 1000L; // 1 minute + + private static final long DEFAULT_PAUSE_YELLOW = 5L * 1000L; // 5 seconds + + private static final long DEFAULT_PAUSE_RED = 100L; // 100 milliseconds + + private long pauseGREEN = DEFAULT_PAUSE_GREEN; + + private long pauseYELLOW = DEFAULT_PAUSE_YELLOW; + + private long pauseRED = DEFAULT_PAUSE_RED; + + private ConditionPolicy conditionPolicy; + + private Condition condition; + + private Map<ICache, ICacheRegistration> registrations = new HashMap<ICache, ICacheRegistration>(); + + public CacheMonitor() + { + } + + public long getPauseGREEN() + { + return pauseGREEN; + } + + public void setPauseGREEN(long pauseGREEN) + { + this.pauseGREEN = pauseGREEN; + } + + public long getPauseYELLOW() + { + return pauseYELLOW; + } + + public void setPauseYELLOW(long pauseYELLOW) + { + this.pauseYELLOW = pauseYELLOW; + } + + public long getPauseRED() + { + return pauseRED; + } + + public void setPauseRED(long pauseRED) + { + this.pauseRED = pauseRED; + } + + public ConditionPolicy getConditionPolicy() + { + return conditionPolicy; + } + + public void setConditionPolicy(ConditionPolicy conditionPolicy) + { + this.conditionPolicy = conditionPolicy; + } + + public Condition getCondition() + { + return condition; + } + + public ICacheRegistration[] getRegistrations() + { + synchronized (registrations) + { + return registrations.values().toArray(new ICacheRegistration[registrations.size()]); + } + } + + public ICacheRegistration registerCache(ICache cache) + { + if (TRACER.isEnabled()) + { + TRACER.trace("Registering cache " + cache); //$NON-NLS-1$ + } + + ICacheRegistration registration = new CacheRegistration(this, cache); + ICacheRegistration oldRegistration; + synchronized (registrations) + { + oldRegistration = registrations.put(cache, registration); + } + + if (oldRegistration != null) + { + oldRegistration.dispose(); + } + + return registration; + } + + public void deregisterCache(ICache cache) + { + ICacheRegistration registration; + synchronized (registrations) + { + registration = registrations.remove(cache); + } + + if (registration != null) + { + registration.dispose(); + if (TRACER.isEnabled()) + { + TRACER.trace("Deregistered cache " + cache); //$NON-NLS-1$ + } + } + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + if (conditionPolicy == null) + { + throw new IllegalStateException("conditionPolicy == null"); //$NON-NLS-1$ + } + } + + @Override + protected void doDeactivate() throws Exception + { + for (ICacheRegistration registration : getRegistrations()) + { + registration.dispose(); + } + + registrations.clear(); + super.doDeactivate(); + } + + @Override + protected void work(WorkContext context) throws Exception + { + Condition newCondition = conditionPolicy.getNewCondition(condition); + setCondition(newCondition); + + switch (newCondition) + { + case GREEN: + context.nextWork(pauseGREEN); + break; + + case YELLOW: + context.nextWork(pauseYELLOW); + break; + + case RED: + handleConditionRED(); + context.nextWork(pauseRED); + break; + } + } + + protected void setCondition(Condition newCondition) + { + if (newCondition == null) + { + throw new ImplementationError("newCondition == null"); //$NON-NLS-1$ + } + + Condition oldCondition = condition; + if (newCondition != oldCondition) + { + condition = newCondition; + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new CacheMonitorEvent(oldCondition, newCondition), listeners); + } + } + } + + protected void handleConditionRED() + { + OM.LOG.warn("CONDITION RED"); //$NON-NLS-1$ + } + + /** + * @author Eike Stepper + */ + private final class CacheMonitorEvent extends Event implements ICacheMonitorEvent + { + private static final long serialVersionUID = 1L; + + private Condition oldCondition; + + private Condition newCondition; + + public CacheMonitorEvent(Condition oldCondition, Condition newCondition) + { + super(CacheMonitor.this); + this.oldCondition = oldCondition; + this.newCondition = newCondition; + } + + @Override + public ICacheMonitor getSource() + { + return (ICacheMonitor)super.getSource(); + } + + public Condition getOldCondition() + { + return oldCondition; + } + + public Condition getNewCondition() + { + return newCondition; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java index 43e5f0edf2..da357186eb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/CacheRegistration.java @@ -1,110 +1,110 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-/**
- * @author Eike Stepper
- */
-public class CacheRegistration implements ICacheRegistration
-{
- public static final float DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR = 0.1f;
-
- private ICacheMonitor cacheMonitor;
-
- private ICache cache;
-
- private int elementCount;
-
- private long cacheSize;
-
- private long reconstructionCost;
-
- public CacheRegistration(ICacheMonitor cacheMonitor, ICache cache)
- {
- this.cacheMonitor = cacheMonitor;
- this.cache = cache;
- }
-
- public void dispose()
- {
- cacheMonitor = null;
- cache = null;
- }
-
- public boolean isDisposed()
- {
- return cacheMonitor == null || cache == null;
- }
-
- public ICacheMonitor getCacheMonitor()
- {
- return cacheMonitor;
- }
-
- public ICache getCache()
- {
- return cache;
- }
-
- public int getElementCount()
- {
- return elementCount;
- }
-
- public long getCacheSize()
- {
- return cacheSize;
- }
-
- public long getAverageElementSize()
- {
- return cacheSize / elementCount;
- }
-
- public long getReconstructionCost()
- {
- return reconstructionCost;
- }
-
- public void elementCached(int elementSize)
- {
- checkDisposal();
- ++elementCount;
- cacheSize += elementSize;
- }
-
- public void elementEvicted(int elementSize)
- {
- checkDisposal();
- --elementCount;
- cacheSize -= elementSize;
- }
-
- public void elementReconstructed(long reconstructionTime)
- {
- checkDisposal();
- float decayFactor = getReconstructionCostDecayFactor();
- reconstructionCost = (long)(decayFactor * reconstructionCost + (1 - decayFactor) * reconstructionTime);
- }
-
- protected float getReconstructionCostDecayFactor()
- {
- return DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR;
- }
-
- private void checkDisposal()
- {
- if (isDisposed())
- {
- throw new IllegalStateException("disposed"); //$NON-NLS-1$
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +/** + * @author Eike Stepper + */ +public class CacheRegistration implements ICacheRegistration +{ + public static final float DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR = 0.1f; + + private ICacheMonitor cacheMonitor; + + private ICache cache; + + private int elementCount; + + private long cacheSize; + + private long reconstructionCost; + + public CacheRegistration(ICacheMonitor cacheMonitor, ICache cache) + { + this.cacheMonitor = cacheMonitor; + this.cache = cache; + } + + public void dispose() + { + cacheMonitor = null; + cache = null; + } + + public boolean isDisposed() + { + return cacheMonitor == null || cache == null; + } + + public ICacheMonitor getCacheMonitor() + { + return cacheMonitor; + } + + public ICache getCache() + { + return cache; + } + + public int getElementCount() + { + return elementCount; + } + + public long getCacheSize() + { + return cacheSize; + } + + public long getAverageElementSize() + { + return cacheSize / elementCount; + } + + public long getReconstructionCost() + { + return reconstructionCost; + } + + public void elementCached(int elementSize) + { + checkDisposal(); + ++elementCount; + cacheSize += elementSize; + } + + public void elementEvicted(int elementSize) + { + checkDisposal(); + --elementCount; + cacheSize -= elementSize; + } + + public void elementReconstructed(long reconstructionTime) + { + checkDisposal(); + float decayFactor = getReconstructionCostDecayFactor(); + reconstructionCost = (long)(decayFactor * reconstructionCost + (1 - decayFactor) * reconstructionTime); + } + + protected float getReconstructionCostDecayFactor() + { + return DEFAULT_RECONSTRUCTION_COST_DECAY_FACTOR; + } + + private void checkDisposal() + { + if (isDisposed()) + { + throw new IllegalStateException("disposed"); //$NON-NLS-1$ + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java index a341c9fe97..2f0769c6d2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/HysteresisConditionPolicy.java @@ -1,105 +1,105 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-import org.eclipse.net4j.util.cache.ICacheMonitor.Condition;
-
-/**
- * @author Eike Stepper
- */
-public class HysteresisConditionPolicy extends ThresholdConditionPolicy
-{
- private long thresholdYellowRed;
-
- private long thresholdGreenYellow;
-
- public HysteresisConditionPolicy(long thresholdYellowRed, long thresholdRedYellow, long thresholdGreenYellow,
- long thresholdYellowGreen)
- {
- super(thresholdRedYellow, thresholdYellowGreen);
- if (thresholdYellowRed > thresholdRedYellow)
- {
- throw new IllegalArgumentException("thresholdYellowRed > thresholdRedYellow"); //$NON-NLS-1$
- }
-
- if (thresholdRedYellow > thresholdGreenYellow)
- {
- throw new IllegalArgumentException("thresholdRedYellow > thresholdGreenYellow"); //$NON-NLS-1$
- }
-
- if (thresholdGreenYellow > thresholdYellowGreen)
- {
- throw new IllegalArgumentException("thresholdGreenYellow > thresholdYellowGreen"); //$NON-NLS-1$
- }
-
- this.thresholdGreenYellow = thresholdGreenYellow;
- this.thresholdYellowRed = thresholdYellowRed;
- }
-
- public long getThresholdYellowRed()
- {
- return thresholdYellowRed;
- }
-
- public long getThresholdGreenYellow()
- {
- return thresholdGreenYellow;
- }
-
- @Override
- protected Condition getNewCondition(Condition oldCondition, long freeMemory)
- {
- switch (oldCondition)
- {
- case GREEN:
- if (freeMemory < thresholdYellowRed)
- {
- return Condition.RED;
- }
-
- if (freeMemory < thresholdGreenYellow)
- {
- return Condition.YELLOW;
- }
-
- return Condition.GREEN;
-
- case YELLOW:
- if (freeMemory < thresholdYellowRed)
- {
- return Condition.RED;
- }
-
- if (freeMemory > getThresholdYellowGreen())
- {
- return Condition.GREEN;
- }
-
- return Condition.YELLOW;
-
- case RED:
- if (freeMemory > getThresholdYellowGreen())
- {
- return Condition.GREEN;
- }
-
- if (freeMemory > getThresholdRedYellow())
- {
- return Condition.YELLOW;
- }
-
- return Condition.RED;
-
- default:
- throw new IllegalArgumentException("oldCondition == " + oldCondition); //$NON-NLS-1$
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +import org.eclipse.net4j.util.cache.ICacheMonitor.Condition; + +/** + * @author Eike Stepper + */ +public class HysteresisConditionPolicy extends ThresholdConditionPolicy +{ + private long thresholdYellowRed; + + private long thresholdGreenYellow; + + public HysteresisConditionPolicy(long thresholdYellowRed, long thresholdRedYellow, long thresholdGreenYellow, + long thresholdYellowGreen) + { + super(thresholdRedYellow, thresholdYellowGreen); + if (thresholdYellowRed > thresholdRedYellow) + { + throw new IllegalArgumentException("thresholdYellowRed > thresholdRedYellow"); //$NON-NLS-1$ + } + + if (thresholdRedYellow > thresholdGreenYellow) + { + throw new IllegalArgumentException("thresholdRedYellow > thresholdGreenYellow"); //$NON-NLS-1$ + } + + if (thresholdGreenYellow > thresholdYellowGreen) + { + throw new IllegalArgumentException("thresholdGreenYellow > thresholdYellowGreen"); //$NON-NLS-1$ + } + + this.thresholdGreenYellow = thresholdGreenYellow; + this.thresholdYellowRed = thresholdYellowRed; + } + + public long getThresholdYellowRed() + { + return thresholdYellowRed; + } + + public long getThresholdGreenYellow() + { + return thresholdGreenYellow; + } + + @Override + protected Condition getNewCondition(Condition oldCondition, long freeMemory) + { + switch (oldCondition) + { + case GREEN: + if (freeMemory < thresholdYellowRed) + { + return Condition.RED; + } + + if (freeMemory < thresholdGreenYellow) + { + return Condition.YELLOW; + } + + return Condition.GREEN; + + case YELLOW: + if (freeMemory < thresholdYellowRed) + { + return Condition.RED; + } + + if (freeMemory > getThresholdYellowGreen()) + { + return Condition.GREEN; + } + + return Condition.YELLOW; + + case RED: + if (freeMemory > getThresholdYellowGreen()) + { + return Condition.GREEN; + } + + if (freeMemory > getThresholdRedYellow()) + { + return Condition.YELLOW; + } + + return Condition.RED; + + default: + throw new IllegalArgumentException("oldCondition == " + oldCondition); //$NON-NLS-1$ + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java index 43c55009fa..4aba187929 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICache.java @@ -1,24 +1,24 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-/**
- * @author Eike Stepper
- */
-public interface ICache
-{
- public ICacheMonitor getCacheMonitor();
-
- /**
- * Instructs this cache to evict <b>elementCount</b> elements.
- */
- public void evictElements(int elementCount);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +/** + * @author Eike Stepper + */ +public interface ICache +{ + public ICacheMonitor getCacheMonitor(); + + /** + * Instructs this cache to evict <b>elementCount</b> elements. + */ + public void evictElements(int elementCount); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java index f8c9aefb6d..16b9bc057b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitor.java @@ -1,60 +1,60 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-import org.eclipse.net4j.util.event.INotifier;
-
-/**
- * @author Eike Stepper
- */
-public interface ICacheMonitor extends INotifier
-{
- public ConditionPolicy getConditionPolicy();
-
- public Condition getCondition();
-
- public ICacheProbe registerCache(ICache cache);
-
- public void deregisterCache(ICache cache);
-
- /**
- * @author Eike Stepper
- */
- public enum Condition
- {
- /**
- * Condition <b>GREEN</b> indicates that the system is operating normally and enough free memory is available so
- * that caches are free to cache additional elements.
- */
- GREEN,
-
- /**
- * Condition <b>YELLOW</b> indicates that the system is operating normally but free memory is about to go low so
- * that caches should stop to cache additional elements.
- */
- YELLOW,
-
- /**
- * Condition <b>RED</b> indicates that the system state is critical and free memory is almost exhausted so that
- * caches must immediately stop to cache additional elements. Depending of the eviction strategy element eviction is
- * ordered.
- */
- RED;
- }
-
- /**
- * @author Eike Stepper
- */
- public interface ConditionPolicy
- {
- public Condition getNewCondition(Condition oldCondition);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +import org.eclipse.net4j.util.event.INotifier; + +/** + * @author Eike Stepper + */ +public interface ICacheMonitor extends INotifier +{ + public ConditionPolicy getConditionPolicy(); + + public Condition getCondition(); + + public ICacheProbe registerCache(ICache cache); + + public void deregisterCache(ICache cache); + + /** + * @author Eike Stepper + */ + public enum Condition + { + /** + * Condition <b>GREEN</b> indicates that the system is operating normally and enough free memory is available so + * that caches are free to cache additional elements. + */ + GREEN, + + /** + * Condition <b>YELLOW</b> indicates that the system is operating normally but free memory is about to go low so + * that caches should stop to cache additional elements. + */ + YELLOW, + + /** + * Condition <b>RED</b> indicates that the system state is critical and free memory is almost exhausted so that + * caches must immediately stop to cache additional elements. Depending of the eviction strategy element eviction is + * ordered. + */ + RED; + } + + /** + * @author Eike Stepper + */ + public interface ConditionPolicy + { + public Condition getNewCondition(Condition oldCondition); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java index 9ebebc683e..c5866fc940 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheMonitorEvent.java @@ -1,30 +1,30 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-import org.eclipse.net4j.util.event.IEvent;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface ICacheMonitorEvent extends IEvent
-{
- /**
- * @since 3.0
- */
- public ICacheMonitor getSource();
-
- public ICacheMonitor.Condition getOldCondition();
-
- public ICacheMonitor.Condition getNewCondition();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +import org.eclipse.net4j.util.event.IEvent; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface ICacheMonitorEvent extends IEvent +{ + /** + * @since 3.0 + */ + public ICacheMonitor getSource(); + + public ICacheMonitor.Condition getOldCondition(); + + public ICacheMonitor.Condition getNewCondition(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java index e4c9c93074..64f8468c3b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheProbe.java @@ -1,33 +1,33 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-/**
- * @author Eike Stepper
- */
-public interface ICacheProbe
-{
- public boolean isDisposed();
-
- public void elementCached(int elementSize);
-
- public void elementEvicted(int elementSize);
-
- public void elementReconstructed(long reconstructionTime);
-
- public int getElementCount();
-
- public long getCacheSize();
-
- public long getAverageElementSize();
-
- public long getReconstructionCost();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +/** + * @author Eike Stepper + */ +public interface ICacheProbe +{ + public boolean isDisposed(); + + public void elementCached(int elementSize); + + public void elementEvicted(int elementSize); + + public void elementReconstructed(long reconstructionTime); + + public int getElementCount(); + + public long getCacheSize(); + + public long getAverageElementSize(); + + public long getReconstructionCost(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java index 7cc730a3f2..2bdf721ac2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ICacheRegistration.java @@ -1,23 +1,23 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-/**
- * @author Eike Stepper
- */
-public interface ICacheRegistration extends ICacheProbe
-{
- public ICacheMonitor getCacheMonitor();
-
- public ICache getCache();
-
- public void dispose();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +/** + * @author Eike Stepper + */ +public interface ICacheRegistration extends ICacheProbe +{ + public ICacheMonitor getCacheMonitor(); + + public ICache getCache(); + + public void dispose(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java index 01a228948d..3d3aebd19d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/ThresholdConditionPolicy.java @@ -1,64 +1,64 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.cache;
-
-import org.eclipse.net4j.util.cache.ICacheMonitor.Condition;
-
-/**
- * @author Eike Stepper
- */
-public class ThresholdConditionPolicy implements ICacheMonitor.ConditionPolicy
-{
- private long thresholdRedYellow;
-
- private long thresholdYellowGreen;
-
- public ThresholdConditionPolicy(long thresholdRedYellow, long thresholdYellowGreen)
- {
- if (thresholdRedYellow > thresholdYellowGreen)
- {
- throw new IllegalArgumentException("thresholdRedYellow > thresholdYellowGreen"); //$NON-NLS-1$
- }
-
- this.thresholdRedYellow = thresholdRedYellow;
- this.thresholdYellowGreen = thresholdYellowGreen;
- }
-
- public long getThresholdRedYellow()
- {
- return thresholdRedYellow;
- }
-
- public long getThresholdYellowGreen()
- {
- return thresholdYellowGreen;
- }
-
- public Condition getNewCondition(Condition oldCondition)
- {
- return getNewCondition(oldCondition, Runtime.getRuntime().freeMemory());
- }
-
- protected Condition getNewCondition(Condition oldCondition, long freeMemory)
- {
- if (freeMemory > thresholdYellowGreen)
- {
- return Condition.GREEN;
- }
-
- if (freeMemory > thresholdRedYellow)
- {
- return Condition.YELLOW;
- }
-
- return Condition.RED;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.cache; + +import org.eclipse.net4j.util.cache.ICacheMonitor.Condition; + +/** + * @author Eike Stepper + */ +public class ThresholdConditionPolicy implements ICacheMonitor.ConditionPolicy +{ + private long thresholdRedYellow; + + private long thresholdYellowGreen; + + public ThresholdConditionPolicy(long thresholdRedYellow, long thresholdYellowGreen) + { + if (thresholdRedYellow > thresholdYellowGreen) + { + throw new IllegalArgumentException("thresholdRedYellow > thresholdYellowGreen"); //$NON-NLS-1$ + } + + this.thresholdRedYellow = thresholdRedYellow; + this.thresholdYellowGreen = thresholdYellowGreen; + } + + public long getThresholdRedYellow() + { + return thresholdRedYellow; + } + + public long getThresholdYellowGreen() + { + return thresholdYellowGreen; + } + + public Condition getNewCondition(Condition oldCondition) + { + return getNewCondition(oldCondition, Runtime.getRuntime().freeMemory()); + } + + protected Condition getNewCondition(Condition oldCondition, long freeMemory) + { + if (freeMemory > thresholdYellowGreen) + { + return Condition.GREEN; + } + + if (freeMemory > thresholdRedYellow) + { + return Condition.YELLOW; + } + + return Condition.RED; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java index dc74f11f66..1710b0ba86 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/cache/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A generic caching and memory monitoring framework.
- */
-package org.eclipse.net4j.util.cache;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A generic caching and memory monitoring framework. + */ +package org.eclipse.net4j.util.cache; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java index 37a4ffd0ed..a503071784 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/AbstractIterator.java @@ -1,79 +1,79 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-/**
- * An abstract base class for custom iterators that only requires to implement a single {@link #computeNextElement()}
- * method.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public abstract class AbstractIterator<T> implements Iterator<T>
-{
- /**
- * The token to be used in {@link #computeNextElement()} to indicate the end of the iteration.
- */
- protected static final Object END_OF_DATA = new Object();
-
- private boolean computed;
-
- private T next;
-
- public AbstractIterator()
- {
- }
-
- public final boolean hasNext()
- {
- if (computed)
- {
- return true;
- }
-
- Object object = computeNextElement();
- computed = true;
-
- if (object == END_OF_DATA)
- {
- return false;
- }
-
- @SuppressWarnings("unchecked")
- T cast = (T)object;
- next = cast;
- return true;
- }
-
- public final T next()
- {
- if (!hasNext())
- {
- throw new NoSuchElementException();
- }
-
- computed = false;
- return next;
- }
-
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Returns the next iteration element, or {@link #END_OF_DATA} if the end of the iteration has been reached.
- */
- protected abstract Object computeNextElement();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * An abstract base class for custom iterators that only requires to implement a single {@link #computeNextElement()} + * method. + * + * @author Eike Stepper + * @since 3.2 + */ +public abstract class AbstractIterator<T> implements Iterator<T> +{ + /** + * The token to be used in {@link #computeNextElement()} to indicate the end of the iteration. + */ + protected static final Object END_OF_DATA = new Object(); + + private boolean computed; + + private T next; + + public AbstractIterator() + { + } + + public final boolean hasNext() + { + if (computed) + { + return true; + } + + Object object = computeNextElement(); + computed = true; + + if (object == END_OF_DATA) + { + return false; + } + + @SuppressWarnings("unchecked") + T cast = (T)object; + next = cast; + return true; + } + + public final T next() + { + if (!hasNext()) + { + throw new NoSuchElementException(); + } + + computed = false; + return next; + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + + /** + * Returns the next iteration element, or {@link #END_OF_DATA} if the end of the iteration has been reached. + */ + protected abstract Object computeNextElement(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java index c7ecb0b8b9..b7026be859 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ArrayIterator.java @@ -1,72 +1,72 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-/**
- * An object that iterates over the elements of an array
- *
- * @author Eike Stepper
- * @since 3.0
- */
-public class ArrayIterator<T> implements Iterator<T>
-{
- private T[] elements;
-
- private int index;
-
- private int lastElement;
-
- public ArrayIterator(T[] elements)
- {
- this(elements, 0, elements.length - 1);
- }
-
- public ArrayIterator(T[] elements, int firstElement)
- {
- this(elements, firstElement, elements.length - 1);
- }
-
- public ArrayIterator(T[] elements, int firstElement, int lastElement)
- {
- this.elements = elements;
- index = firstElement;
- this.lastElement = lastElement;
- }
-
- public boolean hasNext()
- {
- return elements != null && index <= lastElement;
- }
-
- public T next() throws NoSuchElementException
- {
- if (!hasNext())
- {
- throw new NoSuchElementException();
- }
-
- return elements[index++];
- }
-
- /**
- * Unsupported.
- *
- * @throws UnsupportedOperationException
- * always
- */
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * An object that iterates over the elements of an array + * + * @author Eike Stepper + * @since 3.0 + */ +public class ArrayIterator<T> implements Iterator<T> +{ + private T[] elements; + + private int index; + + private int lastElement; + + public ArrayIterator(T[] elements) + { + this(elements, 0, elements.length - 1); + } + + public ArrayIterator(T[] elements, int firstElement) + { + this(elements, firstElement, elements.length - 1); + } + + public ArrayIterator(T[] elements, int firstElement, int lastElement) + { + this.elements = elements; + index = firstElement; + this.lastElement = lastElement; + } + + public boolean hasNext() + { + return elements != null && index <= lastElement; + } + + public T next() throws NoSuchElementException + { + if (!hasNext()) + { + throw new NoSuchElementException(); + } + + return elements[index++]; + } + + /** + * Unsupported. + * + * @throws UnsupportedOperationException + * always + */ + public void remove() + { + throw new UnsupportedOperationException(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java index 8d04d15bff..5bd5e44690 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/BidiMapper.java @@ -1,80 +1,80 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @since 2.0
- * @author Eike Stepper
- */
-public class BidiMapper<T1, T2>
-{
- private Map<T1, T2> map1 = new HashMap<T1, T2>();
-
- private Map<T2, T1> map2 = new HashMap<T2, T1>();
-
- public BidiMapper()
- {
- }
-
- public synchronized void map(T1 v1, T2 v2)
- {
- map1.put(v1, v2);
- map2.put(v2, v1);
- }
-
- public synchronized int size()
- {
- return map1.size();
- }
-
- public synchronized void clear()
- {
- map1.clear();
- map2.clear();
- }
-
- public synchronized T2 lookup1(T1 v1)
- {
- return map1.get(v1);
- }
-
- public synchronized T1 lookup2(T2 v2)
- {
- return map2.get(v2);
- }
-
- public synchronized boolean remove1(T1 v1)
- {
- T2 v2 = map1.remove(v1);
- if (v2 != null)
- {
- map2.remove(v2);
- return true;
- }
-
- return false;
- }
-
- public synchronized boolean remove2(T2 v2)
- {
- T1 v1 = map2.remove(v2);
- if (v1 != null)
- {
- map1.remove(v1);
- return true;
- }
-
- return false;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.HashMap; +import java.util.Map; + +/** + * @since 2.0 + * @author Eike Stepper + */ +public class BidiMapper<T1, T2> +{ + private Map<T1, T2> map1 = new HashMap<T1, T2>(); + + private Map<T2, T1> map2 = new HashMap<T2, T1>(); + + public BidiMapper() + { + } + + public synchronized void map(T1 v1, T2 v2) + { + map1.put(v1, v2); + map2.put(v2, v1); + } + + public synchronized int size() + { + return map1.size(); + } + + public synchronized void clear() + { + map1.clear(); + map2.clear(); + } + + public synchronized T2 lookup1(T1 v1) + { + return map1.get(v1); + } + + public synchronized T1 lookup2(T2 v2) + { + return map2.get(v2); + } + + public synchronized boolean remove1(T1 v1) + { + T2 v2 = map1.remove(v1); + if (v2 != null) + { + map2.remove(v2); + return true; + } + + return false; + } + + public synchronized boolean remove2(T2 v2) + { + T1 v1 = map2.remove(v2); + if (v1 != null) + { + map1.remove(v1); + return true; + } + + return false; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java index cfb6629f7f..e7bdc4c5e9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ByteArrayWrapper.java @@ -1,76 +1,76 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.CheckUtil;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * @author Eike Stepper
- * @since 3.2
- */
-public final class ByteArrayWrapper
-{
- private final byte[] data;
-
- public ByteArrayWrapper(byte[] data)
- {
- CheckUtil.checkArg(data, "data");
- this.data = data;
- }
-
- public byte[] getData()
- {
- return data;
- }
-
- @Override
- public boolean equals(Object other)
- {
- if (other instanceof ByteArrayWrapper)
- {
- return Arrays.equals(data, ((ByteArrayWrapper)other).data);
- }
-
- return false;
- }
-
- @Override
- public int hashCode()
- {
- return Arrays.hashCode(data);
- }
-
- @Override
- public String toString()
- {
- return data.toString();
- }
-
- public static Set<byte[]> toByteArray(Set<ByteArrayWrapper> wrappers)
- {
- if (wrappers == null)
- {
- return null;
- }
-
- Set<byte[]> result = new HashSet<byte[]>();
- for (ByteArrayWrapper wrapper : wrappers)
- {
- result.add(wrapper.getData());
- }
-
- return result;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.CheckUtil; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +/** + * @author Eike Stepper + * @since 3.2 + */ +public final class ByteArrayWrapper +{ + private final byte[] data; + + public ByteArrayWrapper(byte[] data) + { + CheckUtil.checkArg(data, "data"); + this.data = data; + } + + public byte[] getData() + { + return data; + } + + @Override + public boolean equals(Object other) + { + if (other instanceof ByteArrayWrapper) + { + return Arrays.equals(data, ((ByteArrayWrapper)other).data); + } + + return false; + } + + @Override + public int hashCode() + { + return Arrays.hashCode(data); + } + + @Override + public String toString() + { + return data.toString(); + } + + public static Set<byte[]> toByteArray(Set<ByteArrayWrapper> wrappers) + { + if (wrappers == null) + { + return null; + } + + Set<byte[]> result = new HashSet<byte[]>(); + for (ByteArrayWrapper wrapper : wrappers) + { + result.add(wrapper.getData()); + } + + return result; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java index 2aafff27bd..1ccee98090 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CaseInsensitiveStringSet.java @@ -1,128 +1,128 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-
-/**
- * @author Eike Stepper
- * @since 3.2
- */
-public class CaseInsensitiveStringSet extends HashSet<String>
-{
- private static final long serialVersionUID = 1L;
-
- public CaseInsensitiveStringSet()
- {
- }
-
- public CaseInsensitiveStringSet(Collection<? extends String> c)
- {
- super(c);
- }
-
- public CaseInsensitiveStringSet(int initialCapacity, float loadFactor)
- {
- super(initialCapacity, loadFactor);
- }
-
- public CaseInsensitiveStringSet(int initialCapacity)
- {
- super(initialCapacity);
- }
-
- public boolean isLowerCase()
- {
- return true;
- }
-
- @Override
- public boolean contains(Object o)
- {
- return super.contains(convert(o));
- }
-
- @Override
- public boolean add(String e)
- {
- return super.add(convert(e));
- }
-
- @Override
- public boolean remove(Object o)
- {
- return super.remove(convert(o));
- }
-
- @Override
- public boolean removeAll(Collection<?> c)
- {
- return super.removeAll(convert(c));
- }
-
- @Override
- public boolean containsAll(Collection<?> c)
- {
- return super.containsAll(convert(c));
- }
-
- @Override
- public boolean addAll(Collection<? extends String> c)
- {
- boolean modified = false;
- Iterator<? extends String> e = c.iterator();
- while (e.hasNext())
- {
- if (add(convert(e.next())))
- {
- modified = true;
- }
- }
-
- return modified;
- }
-
- @Override
- public boolean retainAll(Collection<?> c)
- {
- return super.retainAll(convert(c));
- }
-
- protected String convert(Object o)
- {
- if (o instanceof String)
- {
- if (isLowerCase())
- {
- return ((String)o).toLowerCase();
- }
-
- return ((String)o).toUpperCase();
- }
-
- return null;
- }
-
- protected Collection<?> convert(Collection<?> c)
- {
- Collection<Object> list = new ArrayList<Object>();
- for (Iterator<?> it = c.iterator(); it.hasNext();)
- {
- Object o = it.next();
- list.add(convert(o));
- }
-
- return list;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; + +/** + * @author Eike Stepper + * @since 3.2 + */ +public class CaseInsensitiveStringSet extends HashSet<String> +{ + private static final long serialVersionUID = 1L; + + public CaseInsensitiveStringSet() + { + } + + public CaseInsensitiveStringSet(Collection<? extends String> c) + { + super(c); + } + + public CaseInsensitiveStringSet(int initialCapacity, float loadFactor) + { + super(initialCapacity, loadFactor); + } + + public CaseInsensitiveStringSet(int initialCapacity) + { + super(initialCapacity); + } + + public boolean isLowerCase() + { + return true; + } + + @Override + public boolean contains(Object o) + { + return super.contains(convert(o)); + } + + @Override + public boolean add(String e) + { + return super.add(convert(e)); + } + + @Override + public boolean remove(Object o) + { + return super.remove(convert(o)); + } + + @Override + public boolean removeAll(Collection<?> c) + { + return super.removeAll(convert(c)); + } + + @Override + public boolean containsAll(Collection<?> c) + { + return super.containsAll(convert(c)); + } + + @Override + public boolean addAll(Collection<? extends String> c) + { + boolean modified = false; + Iterator<? extends String> e = c.iterator(); + while (e.hasNext()) + { + if (add(convert(e.next()))) + { + modified = true; + } + } + + return modified; + } + + @Override + public boolean retainAll(Collection<?> c) + { + return super.retainAll(convert(c)); + } + + protected String convert(Object o) + { + if (o instanceof String) + { + if (isLowerCase()) + { + return ((String)o).toLowerCase(); + } + + return ((String)o).toUpperCase(); + } + + return null; + } + + protected Collection<?> convert(Collection<?> c) + { + Collection<Object> list = new ArrayList<Object>(); + for (Iterator<?> it = c.iterator(); it.hasNext();) + { + Object o = it.next(); + list.add(convert(o)); + } + + return list; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java index 1933ca6609..f5710b3d4c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Closeable.java @@ -1,24 +1,24 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-/**
- * @author Eike Stepper
- */
-public interface Closeable
-{
- public void close();
-
- /**
- * @since 2.0
- */
- public boolean isClosed();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +/** + * @author Eike Stepper + */ +public interface Closeable +{ + public void close(); + + /** + * @since 2.0 + */ + public boolean isClosed(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java index 6af4c708cc..b636841536 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/CloseableIterator.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.Iterator;
-
-/**
- * A closeable iterator.
- *
- * @author Eike Stepper
- */
-public interface CloseableIterator<E> extends Iterator<E>, Closeable
-{
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.Iterator; + +/** + * A closeable iterator. + * + * @author Eike Stepper + */ +public interface CloseableIterator<E> extends Iterator<E>, Closeable +{ +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java index 4dc217c537..136e01171c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/ConcurrentArray.java @@ -1,203 +1,203 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-/**
- * @author Eike Stepper
- * @since 3.2
- */
-public abstract class ConcurrentArray<E>
-{
- protected E[] elements;
-
- private final E[] EMPTY = newArray(0);
-
- public ConcurrentArray()
- {
- }
-
- public boolean isEmpty()
- {
- return elements == null;
- }
-
- /**
- * Returns the elements, never <code>null</code>.
- */
- public E[] get()
- {
- return elements == null ? EMPTY : elements;
- }
-
- public synchronized void add(E element)
- {
- if (!validate(element))
- {
- return;
- }
-
- if (elements == null)
- {
- E[] array = newArray(1);
- array[0] = element;
- elements = array;
- firstElementAdded();
- }
- else
- {
- int length = elements.length;
- E[] array = newArray(length + 1);
- System.arraycopy(elements, 0, array, 0, length);
- array[length] = element;
- elements = array;
- }
- }
-
- public synchronized boolean remove(E element)
- {
- if (elements != null)
- {
- int length = elements.length;
- if (length == 1)
- {
- if (elements[0] == element)
- {
- elements = null;
- lastElementRemoved();
- return true;
- }
- }
- else
- {
- for (int i = 0; i < length; i++)
- {
- E e = elements[i];
- if (e == element)
- {
- E[] array = newArray(length - 1);
-
- if (i > 0)
- {
- System.arraycopy(elements, 0, array, 0, i);
- }
-
- if (i + 1 <= length - 1)
- {
- System.arraycopy(elements, i + 1, array, i, length - 1 - i);
- }
-
- elements = array;
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- protected boolean validate(E element)
- {
- return true;
- }
-
- protected void firstElementAdded()
- {
- }
-
- protected void lastElementRemoved()
- {
- }
-
- protected abstract E[] newArray(int length);
-
- /**
- * @author Eike Stepper
- */
- public abstract static class Unique<E> extends ConcurrentArray<E>
- {
- public Unique()
- {
- }
-
- @Override
- protected boolean validate(E element)
- {
- if (elements != null)
- {
- for (int i = 0; i < elements.length; i++)
- {
- if (equals(element, elements[i]))
- {
- violatingUniqueness(element);
- return false;
- }
- }
- }
-
- return true;
- }
-
- protected boolean equals(E e1, E e2)
- {
- return e1 == e2;
- }
-
- protected void violatingUniqueness(E element)
- {
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public abstract static class DuplicateCounter<E> extends ConcurrentArray<E>
- {
- private int maxDuplicates;
-
- public DuplicateCounter()
- {
- }
-
- public final int getMaxDuplicates()
- {
- return maxDuplicates;
- }
-
- @Override
- protected boolean validate(E element)
- {
- if (elements != null)
- {
- int duplicates = 0;
- for (int i = 0; i < elements.length; i++)
- {
- if (equals(element, elements[i]))
- {
- ++duplicates;
- }
- }
-
- if (duplicates > maxDuplicates)
- {
- maxDuplicates = duplicates;
- }
- }
-
- return true;
- }
-
- protected boolean equals(E e1, E e2)
- {
- return e1 == e2;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +/** + * @author Eike Stepper + * @since 3.2 + */ +public abstract class ConcurrentArray<E> +{ + protected E[] elements; + + private final E[] EMPTY = newArray(0); + + public ConcurrentArray() + { + } + + public boolean isEmpty() + { + return elements == null; + } + + /** + * Returns the elements, never <code>null</code>. + */ + public E[] get() + { + return elements == null ? EMPTY : elements; + } + + public synchronized void add(E element) + { + if (!validate(element)) + { + return; + } + + if (elements == null) + { + E[] array = newArray(1); + array[0] = element; + elements = array; + firstElementAdded(); + } + else + { + int length = elements.length; + E[] array = newArray(length + 1); + System.arraycopy(elements, 0, array, 0, length); + array[length] = element; + elements = array; + } + } + + public synchronized boolean remove(E element) + { + if (elements != null) + { + int length = elements.length; + if (length == 1) + { + if (elements[0] == element) + { + elements = null; + lastElementRemoved(); + return true; + } + } + else + { + for (int i = 0; i < length; i++) + { + E e = elements[i]; + if (e == element) + { + E[] array = newArray(length - 1); + + if (i > 0) + { + System.arraycopy(elements, 0, array, 0, i); + } + + if (i + 1 <= length - 1) + { + System.arraycopy(elements, i + 1, array, i, length - 1 - i); + } + + elements = array; + return true; + } + } + } + } + + return false; + } + + protected boolean validate(E element) + { + return true; + } + + protected void firstElementAdded() + { + } + + protected void lastElementRemoved() + { + } + + protected abstract E[] newArray(int length); + + /** + * @author Eike Stepper + */ + public abstract static class Unique<E> extends ConcurrentArray<E> + { + public Unique() + { + } + + @Override + protected boolean validate(E element) + { + if (elements != null) + { + for (int i = 0; i < elements.length; i++) + { + if (equals(element, elements[i])) + { + violatingUniqueness(element); + return false; + } + } + } + + return true; + } + + protected boolean equals(E e1, E e2) + { + return e1 == e2; + } + + protected void violatingUniqueness(E element) + { + } + } + + /** + * @author Eike Stepper + */ + public abstract static class DuplicateCounter<E> extends ConcurrentArray<E> + { + private int maxDuplicates; + + public DuplicateCounter() + { + } + + public final int getMaxDuplicates() + { + return maxDuplicates; + } + + @Override + protected boolean validate(E element) + { + if (elements != null) + { + int duplicates = 0; + for (int i = 0; i < elements.length; i++) + { + if (equals(element, elements[i])) + { + ++duplicates; + } + } + + if (duplicates > maxDuplicates) + { + maxDuplicates = duplicates; + } + } + + return true; + } + + protected boolean equals(E e1, E e2) + { + return e1 == e2; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java index c6b345d73d..aa07386d5b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/DynamicArray.java @@ -1,97 +1,97 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class DynamicArray<E>
-{
- private Object[] elements = {};
-
- public DynamicArray()
- {
- }
-
- public int add(E element)
- {
- int length = elements.length;
- for (int i = 0; i < length; i++)
- {
- if (elements[i] == null)
- {
- elements[i] = element;
- return i;
- }
- }
-
- grow(length);
- elements[length] = element;
- return length;
- }
-
- @SuppressWarnings("unchecked")
- public E add(int index, E element)
- {
- grow(index);
- Object old = elements[index];
- elements[index] = element;
- return (E)old;
- }
-
- @SuppressWarnings("unchecked")
- public E remove(int index)
- {
- Object old = elements[index];
- if (old != null)
- {
- elements[index] = null;
- shrink();
- }
-
- return (E)old;
- }
-
- @SuppressWarnings("unchecked")
- public E get(int index)
- {
- return (E)elements[index];
- }
-
- private void grow(int index)
- {
- if (index >= elements.length)
- {
- Object[] newChannels = new Object[index + 1];
- System.arraycopy(elements, 0, newChannels, 0, elements.length);
- elements = newChannels;
- }
- }
-
- private void shrink()
- {
- boolean shrink = false;
- int lastIndex = elements.length - 1;
- while (lastIndex > 0 && (shrink = elements[lastIndex] == null))
- {
- --lastIndex;
- }
-
- if (shrink)
- {
- int newLength = lastIndex + 1;
- Object[] newChannels = new Object[newLength];
- System.arraycopy(elements, 0, newChannels, 0, newLength);
- elements = newChannels;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class DynamicArray<E> +{ + private Object[] elements = {}; + + public DynamicArray() + { + } + + public int add(E element) + { + int length = elements.length; + for (int i = 0; i < length; i++) + { + if (elements[i] == null) + { + elements[i] = element; + return i; + } + } + + grow(length); + elements[length] = element; + return length; + } + + @SuppressWarnings("unchecked") + public E add(int index, E element) + { + grow(index); + Object old = elements[index]; + elements[index] = element; + return (E)old; + } + + @SuppressWarnings("unchecked") + public E remove(int index) + { + Object old = elements[index]; + if (old != null) + { + elements[index] = null; + shrink(); + } + + return (E)old; + } + + @SuppressWarnings("unchecked") + public E get(int index) + { + return (E)elements[index]; + } + + private void grow(int index) + { + if (index >= elements.length) + { + Object[] newChannels = new Object[index + 1]; + System.arraycopy(elements, 0, newChannels, 0, elements.length); + elements = newChannels; + } + } + + private void shrink() + { + boolean shrink = false; + int lastIndex = elements.length - 1; + while (lastIndex > 0 && (shrink = elements[lastIndex] == null)) + { + --lastIndex; + } + + if (shrink) + { + int newLength = lastIndex + 1; + Object[] newChannels = new Object[newLength]; + System.arraycopy(elements, 0, newChannels, 0, newLength); + elements = newChannels; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java index 44faf57b38..4474c72da8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/FastList.java @@ -1,21 +1,21 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-/**
- * @author Eike Stepper
- * @since 3.0
- * @deprecated As of 3.2 use {@link ConcurrentArray}.
- */
-@Deprecated
-public abstract class FastList<E> extends ConcurrentArray<E>
-{
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +/** + * @author Eike Stepper + * @since 3.0 + * @deprecated As of 3.2 use {@link ConcurrentArray}. + */ +@Deprecated +public abstract class FastList<E> extends ConcurrentArray<E> +{ +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java index 8afd492dd4..8ea46ff126 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HashBag.java @@ -1,186 +1,186 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author Eike Stepper
- */
-public final class HashBag<T> implements Set<T>
-{
- private Map<T, HashBag.Counter> map;
-
- public HashBag()
- {
- map = new HashMap<T, Counter>();
- }
-
- public HashBag(int initialCapacity, float loadFactor)
- {
- map = new HashMap<T, Counter>(initialCapacity, loadFactor);
- }
-
- public HashBag(int initialCapacity)
- {
- map = new HashMap<T, Counter>(initialCapacity);
- }
-
- public HashBag(Map<? extends T, ? extends HashBag.Counter> m)
- {
- map = new HashMap<T, Counter>(m);
- }
-
- /**
- * @since 3.0
- */
- public int getCounterFor(T o)
- {
- Counter counter = map.get(o);
- if (counter == null)
- {
- return 0;
- }
-
- return counter.getValue();
- }
-
- public boolean add(T o)
- {
- HashBag.Counter counter = map.get(o);
- if (counter == null)
- {
- counter = new Counter();
- map.put(o, counter);
- return true;
- }
-
- counter.incValue();
- return false;
- }
-
- public boolean addAll(Collection<? extends T> c)
- {
- for (T t : c)
- {
- add(t);
- }
-
- return true;
- }
-
- public void clear()
- {
- map.clear();
- }
-
- public boolean contains(Object o)
- {
- return map.containsKey(o);
- }
-
- public boolean containsAll(Collection<?> c)
- {
- return map.keySet().containsAll(c);
- }
-
- public boolean isEmpty()
- {
- return map.isEmpty();
- }
-
- public Iterator<T> iterator()
- {
- return map.keySet().iterator();
- }
-
- public boolean remove(Object o)
- {
- HashBag.Counter counter = map.get(o);
- if (counter == null)
- {
- return false;
- }
-
- if (counter.decValue() == 0)
- {
- map.remove(o);
- }
-
- return true;
- }
-
- public boolean removeAll(Collection<?> c)
- {
- boolean changed = false;
- for (Object object : c)
- {
- if (remove(object))
- {
- changed = true;
- }
- }
-
- return changed;
- }
-
- public boolean retainAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- public int size()
- {
- return map.size();
- }
-
- public Object[] toArray()
- {
- return map.keySet().toArray();
- }
-
- @SuppressWarnings("hiding")
- public <T> T[] toArray(T[] a)
- {
- return map.keySet().toArray(a);
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class Counter
- {
- private int value = 1;
-
- public Counter()
- {
- }
-
- public int getValue()
- {
- return value;
- }
-
- public int incValue()
- {
- return ++value;
- }
-
- public int decValue()
- {
- return --value;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * @author Eike Stepper + */ +public final class HashBag<T> implements Set<T> +{ + private Map<T, HashBag.Counter> map; + + public HashBag() + { + map = new HashMap<T, Counter>(); + } + + public HashBag(int initialCapacity, float loadFactor) + { + map = new HashMap<T, Counter>(initialCapacity, loadFactor); + } + + public HashBag(int initialCapacity) + { + map = new HashMap<T, Counter>(initialCapacity); + } + + public HashBag(Map<? extends T, ? extends HashBag.Counter> m) + { + map = new HashMap<T, Counter>(m); + } + + /** + * @since 3.0 + */ + public int getCounterFor(T o) + { + Counter counter = map.get(o); + if (counter == null) + { + return 0; + } + + return counter.getValue(); + } + + public boolean add(T o) + { + HashBag.Counter counter = map.get(o); + if (counter == null) + { + counter = new Counter(); + map.put(o, counter); + return true; + } + + counter.incValue(); + return false; + } + + public boolean addAll(Collection<? extends T> c) + { + for (T t : c) + { + add(t); + } + + return true; + } + + public void clear() + { + map.clear(); + } + + public boolean contains(Object o) + { + return map.containsKey(o); + } + + public boolean containsAll(Collection<?> c) + { + return map.keySet().containsAll(c); + } + + public boolean isEmpty() + { + return map.isEmpty(); + } + + public Iterator<T> iterator() + { + return map.keySet().iterator(); + } + + public boolean remove(Object o) + { + HashBag.Counter counter = map.get(o); + if (counter == null) + { + return false; + } + + if (counter.decValue() == 0) + { + map.remove(o); + } + + return true; + } + + public boolean removeAll(Collection<?> c) + { + boolean changed = false; + for (Object object : c) + { + if (remove(object)) + { + changed = true; + } + } + + return changed; + } + + public boolean retainAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + public int size() + { + return map.size(); + } + + public Object[] toArray() + { + return map.keySet().toArray(); + } + + @SuppressWarnings("hiding") + public <T> T[] toArray(T[] a) + { + return map.keySet().toArray(a); + } + + /** + * @author Eike Stepper + */ + private static final class Counter + { + private int value = 1; + + public Counter() + { + } + + public int getValue() + { + return value; + } + + public int incValue() + { + return ++value; + } + + public int decValue() + { + return --value; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java index 67fc3f5ce0..b442a9bfa1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/History.java @@ -1,217 +1,217 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.event.Notifier;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * @author Eike Stepper
- */
-public class History<T> extends Notifier implements IHistory<T>
-{
- protected List<IHistoryElement<T>> elements = new ArrayList<IHistoryElement<T>>(0);
-
- private boolean loaded;
-
- public History()
- {
- }
-
- public List<IHistoryElement<T>> getElements()
- {
- lazyLoad();
- return elements;
- }
-
- public void setElements(List<IHistoryElement<T>> newElements)
- {
- if (newElements == null)
- {
- newElements = new ArrayList<IHistoryElement<T>>(0);
- }
-
- if (!elements.equals(newElements))
- {
- elements = newElements;
- changed();
- }
- }
-
- public boolean isEmpty()
- {
- lazyLoad();
- return elements.isEmpty();
- }
-
- public int size()
- {
- lazyLoad();
- return elements.size();
- }
-
- public int indexOf(T data)
- {
- lazyLoad();
- for (int i = 0; i < elements.size(); i++)
- {
- if (elements.get(i).getData().equals(data))
- {
- return i;
- }
- }
-
- return -1;
- }
-
- public IHistoryElement<T> get(int index)
- {
- lazyLoad();
- return elements.get(index);
- }
-
- public boolean add(T data)
- {
- lazyLoad();
- int index = indexOf(data);
- IHistoryElement<T> element = index != -1 ? elements.remove(index) : createElement(data);
- elements.add(0, element);
-
- boolean changed = index != 0;
- if (changed)
- {
- changed();
- }
-
- return changed;
- }
-
- public IHistoryElement<T> remove(int index)
- {
- lazyLoad();
- IHistoryElement<T> element = elements.remove(index);
- if (element != null)
- {
- changed();
- }
-
- return element;
- }
-
- public boolean clear()
- {
- if (elements.isEmpty())
- {
- return false;
- }
-
- elements.clear();
- changed();
- return true;
- }
-
- public T getMostRecent()
- {
- lazyLoad();
- if (isEmpty())
- {
- return null;
- }
-
- return elements.get(0).getData();
- }
-
- @SuppressWarnings("unchecked")
- public <D> D[] getData(D[] a)
- {
- lazyLoad();
- int size = elements.size();
- if (a.length < size)
- {
- a = (D[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
- }
-
- for (int i = 0; i < size; i++)
- {
- a[i] = (D)elements.get(i).getData();
- }
-
- if (a.length > size)
- {
- a[size] = null;
- }
-
- return a;
- }
-
- @SuppressWarnings("unchecked")
- public IHistoryElement<T>[] toArray()
- {
- lazyLoad();
- return elements.toArray(new IHistoryElement[elements.size()]);
- }
-
- public Iterator<IHistoryElement<T>> iterator()
- {
- lazyLoad();
- return elements.iterator();
- }
-
- @SuppressWarnings("unchecked")
- protected IHistoryElement<T> createElement(T data)
- {
- @SuppressWarnings("rawtypes")
- HistoryElement result = new HistoryElement(this, data);
- return result;
- }
-
- protected void load()
- {
- }
-
- protected void save()
- {
- }
-
- protected final void changed()
- {
- save();
- fireChangedEvent();
- }
-
- private void lazyLoad()
- {
- if (!loaded)
- {
- loaded = true;
- load();
- }
- }
-
- private void fireChangedEvent()
- {
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(new IHistoryChangeEvent()
- {
- public IHistory<?> getSource()
- {
- return History.this;
- }
- }, listeners);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.event.Notifier; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * @author Eike Stepper + */ +public class History<T> extends Notifier implements IHistory<T> +{ + protected List<IHistoryElement<T>> elements = new ArrayList<IHistoryElement<T>>(0); + + private boolean loaded; + + public History() + { + } + + public List<IHistoryElement<T>> getElements() + { + lazyLoad(); + return elements; + } + + public void setElements(List<IHistoryElement<T>> newElements) + { + if (newElements == null) + { + newElements = new ArrayList<IHistoryElement<T>>(0); + } + + if (!elements.equals(newElements)) + { + elements = newElements; + changed(); + } + } + + public boolean isEmpty() + { + lazyLoad(); + return elements.isEmpty(); + } + + public int size() + { + lazyLoad(); + return elements.size(); + } + + public int indexOf(T data) + { + lazyLoad(); + for (int i = 0; i < elements.size(); i++) + { + if (elements.get(i).getData().equals(data)) + { + return i; + } + } + + return -1; + } + + public IHistoryElement<T> get(int index) + { + lazyLoad(); + return elements.get(index); + } + + public boolean add(T data) + { + lazyLoad(); + int index = indexOf(data); + IHistoryElement<T> element = index != -1 ? elements.remove(index) : createElement(data); + elements.add(0, element); + + boolean changed = index != 0; + if (changed) + { + changed(); + } + + return changed; + } + + public IHistoryElement<T> remove(int index) + { + lazyLoad(); + IHistoryElement<T> element = elements.remove(index); + if (element != null) + { + changed(); + } + + return element; + } + + public boolean clear() + { + if (elements.isEmpty()) + { + return false; + } + + elements.clear(); + changed(); + return true; + } + + public T getMostRecent() + { + lazyLoad(); + if (isEmpty()) + { + return null; + } + + return elements.get(0).getData(); + } + + @SuppressWarnings("unchecked") + public <D> D[] getData(D[] a) + { + lazyLoad(); + int size = elements.size(); + if (a.length < size) + { + a = (D[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); + } + + for (int i = 0; i < size; i++) + { + a[i] = (D)elements.get(i).getData(); + } + + if (a.length > size) + { + a[size] = null; + } + + return a; + } + + @SuppressWarnings("unchecked") + public IHistoryElement<T>[] toArray() + { + lazyLoad(); + return elements.toArray(new IHistoryElement[elements.size()]); + } + + public Iterator<IHistoryElement<T>> iterator() + { + lazyLoad(); + return elements.iterator(); + } + + @SuppressWarnings("unchecked") + protected IHistoryElement<T> createElement(T data) + { + @SuppressWarnings("rawtypes") + HistoryElement result = new HistoryElement(this, data); + return result; + } + + protected void load() + { + } + + protected void save() + { + } + + protected final void changed() + { + save(); + fireChangedEvent(); + } + + private void lazyLoad() + { + if (!loaded) + { + loaded = true; + load(); + } + } + + private void fireChangedEvent() + { + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new IHistoryChangeEvent() + { + public IHistory<?> getSource() + { + return History.this; + } + }, listeners); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java index 56b6713425..b2adac636d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryElement.java @@ -1,74 +1,74 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-/**
- * @author Eike Stepper
- */
-public class HistoryElement<T> implements IHistoryElement<T>
-{
- private IHistory<IHistoryElement<T>> history;
-
- private T data;
-
- public HistoryElement(IHistory<IHistoryElement<T>> history, T data)
- {
- this.history = history;
- this.data = data;
- }
-
- public IHistory<IHistoryElement<T>> getHistory()
- {
- return history;
- }
-
- public T getData()
- {
- return data;
- }
-
- public String getText()
- {
- return data.toString();
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (obj == this)
- {
- return true;
- }
-
- if (obj instanceof IHistoryElement<?>)
- {
- @SuppressWarnings("unchecked")
- IHistoryElement<T> that = (IHistoryElement<T>)obj;
- return ObjectUtil.equals(history, that.getHistory()) && ObjectUtil.equals(data, that.getData());
- }
-
- return false;
- }
-
- @Override
- public int hashCode()
- {
- return history.hashCode() ^ data.hashCode();
- }
-
- @Override
- public String toString()
- {
- return getText();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.ObjectUtil; + +/** + * @author Eike Stepper + */ +public class HistoryElement<T> implements IHistoryElement<T> +{ + private IHistory<IHistoryElement<T>> history; + + private T data; + + public HistoryElement(IHistory<IHistoryElement<T>> history, T data) + { + this.history = history; + this.data = data; + } + + public IHistory<IHistoryElement<T>> getHistory() + { + return history; + } + + public T getData() + { + return data; + } + + public String getText() + { + return data.toString(); + } + + @Override + public boolean equals(Object obj) + { + if (obj == this) + { + return true; + } + + if (obj instanceof IHistoryElement<?>) + { + @SuppressWarnings("unchecked") + IHistoryElement<T> that = (IHistoryElement<T>)obj; + return ObjectUtil.equals(history, that.getHistory()) && ObjectUtil.equals(data, that.getData()); + } + + return false; + } + + @Override + public int hashCode() + { + return history.hashCode() ^ data.hashCode(); + } + + @Override + public String toString() + { + return getText(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java index cd17e499a7..4b7bf11de7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/HistoryUtil.java @@ -1,33 +1,33 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.om.pref.OMPreference;
-
-/**
- * @author Eike Stepper
- */
-public final class HistoryUtil
-{
- private HistoryUtil()
- {
- }
-
- public static IHistory<String> createHistory()
- {
- return new History<String>();
- }
-
- public static IHistory<String> createPreferenceHistory(OMPreference<String[]> preference)
- {
- return new PreferenceHistory(preference);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.om.pref.OMPreference; + +/** + * @author Eike Stepper + */ +public final class HistoryUtil +{ + private HistoryUtil() + { + } + + public static IHistory<String> createHistory() + { + return new History<String>(); + } + + public static IHistory<String> createPreferenceHistory(OMPreference<String[]> preference) + { + return new PreferenceHistory(preference); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java index b240ab4b7e..bc51d29d1c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistory.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.event.INotifier;
-
-/**
- * @author Eike Stepper
- */
-public interface IHistory<T> extends INotifier, Iterable<IHistoryElement<T>>
-{
- public boolean isEmpty();
-
- public int size();
-
- public boolean clear();
-
- public int indexOf(T data);
-
- public boolean add(T data);
-
- public IHistoryElement<T> remove(int index);
-
- public IHistoryElement<T> get(int index);
-
- public T getMostRecent();
-
- public <D> D[] getData(D[] a);
-
- public IHistoryElement<T>[] toArray();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.event.INotifier; + +/** + * @author Eike Stepper + */ +public interface IHistory<T> extends INotifier, Iterable<IHistoryElement<T>> +{ + public boolean isEmpty(); + + public int size(); + + public boolean clear(); + + public int indexOf(T data); + + public boolean add(T data); + + public IHistoryElement<T> remove(int index); + + public IHistoryElement<T> get(int index); + + public T getMostRecent(); + + public <D> D[] getData(D[] a); + + public IHistoryElement<T>[] toArray(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java index d644429c88..5ce8206b73 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryChangeEvent.java @@ -1,26 +1,26 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.event.IEvent;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface IHistoryChangeEvent extends IEvent
-{
- /**
- * @since 3.0
- */
- public IHistory<?> getSource();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.event.IEvent; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface IHistoryChangeEvent extends IEvent +{ + /** + * @since 3.0 + */ + public IHistory<?> getSource(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java index 3481f573bb..76d16bb984 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IHistoryElement.java @@ -1,23 +1,23 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-/**
- * @author Eike Stepper
- */
-public interface IHistoryElement<T>
-{
- public IHistory<IHistoryElement<T>> getHistory();
-
- public T getData();
-
- public String getText();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +/** + * @author Eike Stepper + */ +public interface IHistoryElement<T> +{ + public IHistory<IHistoryElement<T>> getHistory(); + + public T getData(); + + public String getText(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java index 791a66ffae..4ea76a6482 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/IndexedList.java @@ -1,280 +1,280 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.NoSuchElementException;
-
-/**
- * @author Eike Stepper
- * @since 3.0
- */
-public abstract class IndexedList<E> implements List<E>
-{
- public IndexedList()
- {
- }
-
- public abstract E get(int index);
-
- public abstract int size();
-
- public boolean isEmpty()
- {
- return size() == 0;
- }
-
- public boolean contains(Object o)
- {
- int size = size();
- for (int i = 0; i < size; i++)
- {
- if (get(i).equals(o))
- {
- return true;
- }
- }
-
- return false;
- }
-
- public boolean containsAll(Collection<?> c)
- {
- for (Object object : c)
- {
- if (!contains(object))
- {
- return false;
- }
- }
-
- return true;
- }
-
- public int indexOf(Object o)
- {
- return 0;
- }
-
- public int lastIndexOf(Object o)
- {
- return 0;
- }
-
- public Iterator<E> iterator()
- {
- return new IndexedIterator();
- }
-
- public ListIterator<E> listIterator()
- {
- return new IndexedListIterator(0);
- }
-
- public ListIterator<E> listIterator(int index)
- {
- if (index < 0 || index > size())
- {
- throw new IndexOutOfBoundsException("Index: " + index);
- }
-
- return new IndexedListIterator(index);
- }
-
- public List<E> subList(int fromIndex, int toIndex)
- {
- return null;
- }
-
- public Object[] toArray()
- {
- throw new UnsupportedOperationException();
- }
-
- public <T> T[] toArray(T[] a)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean add(E o)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean remove(Object o)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean addAll(Collection<? extends E> c)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean addAll(int index, Collection<? extends E> c)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean removeAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean retainAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- public void clear()
- {
- throw new UnsupportedOperationException();
- }
-
- public E set(int index, E element)
- {
- throw new UnsupportedOperationException();
- }
-
- public void add(int index, E element)
- {
- throw new UnsupportedOperationException();
- }
-
- public E remove(int index)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String toString()
- {
- StringBuilder builder = new StringBuilder();
- builder.append("{"); //$NON-NLS-1$
- for (int i = 0; i < size(); i++)
- {
- if (i != 0)
- {
- builder.append(", "); //$NON-NLS-1$
- }
-
- builder.append(get(i).toString());
- }
-
- builder.append("}"); //$NON-NLS-1$
- return builder.toString();
- }
-
- /**
- * @author Eike Stepper
- */
- private class IndexedIterator implements Iterator<E>
- {
- int pos = 0;
-
- public boolean hasNext()
- {
- return pos != size();
- }
-
- public E next()
- {
- try
- {
- return get(pos++);
- }
- catch (IndexOutOfBoundsException ex)
- {
- throw new NoSuchElementException();
- }
- }
-
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private class IndexedListIterator extends IndexedIterator implements ListIterator<E>
- {
- IndexedListIterator(int index)
- {
- pos = index;
- }
-
- public boolean hasPrevious()
- {
- return pos != 0;
- }
-
- public E previous()
- {
- try
- {
- return get(--pos);
- }
- catch (IndexOutOfBoundsException ex)
- {
- throw new NoSuchElementException();
- }
- }
-
- public int nextIndex()
- {
- return pos;
- }
-
- public int previousIndex()
- {
- return pos - 1;
- }
-
- public void set(E o)
- {
- throw new UnsupportedOperationException();
- }
-
- public void add(E o)
- {
- throw new UnsupportedOperationException();
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static abstract class ArrayBacked<E> extends IndexedList<E>
- {
- public ArrayBacked()
- {
- }
-
- protected abstract E[] getArray();
-
- @Override
- public E get(int i)
- {
- return getArray()[i];
- }
-
- @Override
- public int size()
- {
- return getArray().length;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; + +/** + * @author Eike Stepper + * @since 3.0 + */ +public abstract class IndexedList<E> implements List<E> +{ + public IndexedList() + { + } + + public abstract E get(int index); + + public abstract int size(); + + public boolean isEmpty() + { + return size() == 0; + } + + public boolean contains(Object o) + { + int size = size(); + for (int i = 0; i < size; i++) + { + if (get(i).equals(o)) + { + return true; + } + } + + return false; + } + + public boolean containsAll(Collection<?> c) + { + for (Object object : c) + { + if (!contains(object)) + { + return false; + } + } + + return true; + } + + public int indexOf(Object o) + { + return 0; + } + + public int lastIndexOf(Object o) + { + return 0; + } + + public Iterator<E> iterator() + { + return new IndexedIterator(); + } + + public ListIterator<E> listIterator() + { + return new IndexedListIterator(0); + } + + public ListIterator<E> listIterator(int index) + { + if (index < 0 || index > size()) + { + throw new IndexOutOfBoundsException("Index: " + index); + } + + return new IndexedListIterator(index); + } + + public List<E> subList(int fromIndex, int toIndex) + { + return null; + } + + public Object[] toArray() + { + throw new UnsupportedOperationException(); + } + + public <T> T[] toArray(T[] a) + { + throw new UnsupportedOperationException(); + } + + public boolean add(E o) + { + throw new UnsupportedOperationException(); + } + + public boolean remove(Object o) + { + throw new UnsupportedOperationException(); + } + + public boolean addAll(Collection<? extends E> c) + { + throw new UnsupportedOperationException(); + } + + public boolean addAll(int index, Collection<? extends E> c) + { + throw new UnsupportedOperationException(); + } + + public boolean removeAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + public boolean retainAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + public void clear() + { + throw new UnsupportedOperationException(); + } + + public E set(int index, E element) + { + throw new UnsupportedOperationException(); + } + + public void add(int index, E element) + { + throw new UnsupportedOperationException(); + } + + public E remove(int index) + { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() + { + StringBuilder builder = new StringBuilder(); + builder.append("{"); //$NON-NLS-1$ + for (int i = 0; i < size(); i++) + { + if (i != 0) + { + builder.append(", "); //$NON-NLS-1$ + } + + builder.append(get(i).toString()); + } + + builder.append("}"); //$NON-NLS-1$ + return builder.toString(); + } + + /** + * @author Eike Stepper + */ + private class IndexedIterator implements Iterator<E> + { + int pos = 0; + + public boolean hasNext() + { + return pos != size(); + } + + public E next() + { + try + { + return get(pos++); + } + catch (IndexOutOfBoundsException ex) + { + throw new NoSuchElementException(); + } + } + + public void remove() + { + throw new UnsupportedOperationException(); + } + } + + /** + * @author Eike Stepper + */ + private class IndexedListIterator extends IndexedIterator implements ListIterator<E> + { + IndexedListIterator(int index) + { + pos = index; + } + + public boolean hasPrevious() + { + return pos != 0; + } + + public E previous() + { + try + { + return get(--pos); + } + catch (IndexOutOfBoundsException ex) + { + throw new NoSuchElementException(); + } + } + + public int nextIndex() + { + return pos; + } + + public int previousIndex() + { + return pos - 1; + } + + public void set(E o) + { + throw new UnsupportedOperationException(); + } + + public void add(E o) + { + throw new UnsupportedOperationException(); + } + } + + /** + * @author Eike Stepper + */ + public static abstract class ArrayBacked<E> extends IndexedList<E> + { + public ArrayBacked() + { + } + + protected abstract E[] getArray(); + + @Override + public E get(int i) + { + return getArray()[i]; + } + + @Override + public int size() + { + return getArray().length; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java index 95326270ba..39985c5bd3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MapEntry.java @@ -1,84 +1,84 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-import java.text.MessageFormat;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public class MapEntry<K, V> implements Map.Entry<K, V>
-{
- private K key;
-
- private V value;
-
- public MapEntry(K key, V value)
- {
- this.key = key;
- this.value = value;
- }
-
- public MapEntry(Map.Entry<K, V> entry)
- {
- key = entry.getKey();
- value = entry.getValue();
- }
-
- public K getKey()
- {
- return key;
- }
-
- public V getValue()
- {
- return value;
- }
-
- public V setValue(V value)
- {
- V oldValue = this.value;
- this.value = value;
- return oldValue;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (obj == this)
- {
- return true;
- }
-
- if (obj instanceof Map.Entry<?, ?>)
- {
- Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj;
- return ObjectUtil.equals(key, entry.getKey()) && ObjectUtil.equals(value, entry.getValue());
- }
-
- return false;
- }
-
- @Override
- public int hashCode()
- {
- return ObjectUtil.hashCode(key) ^ ObjectUtil.hashCode(value);
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("{0}={1}", key, value); //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.ObjectUtil; + +import java.text.MessageFormat; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public class MapEntry<K, V> implements Map.Entry<K, V> +{ + private K key; + + private V value; + + public MapEntry(K key, V value) + { + this.key = key; + this.value = value; + } + + public MapEntry(Map.Entry<K, V> entry) + { + key = entry.getKey(); + value = entry.getValue(); + } + + public K getKey() + { + return key; + } + + public V getValue() + { + return value; + } + + public V setValue(V value) + { + V oldValue = this.value; + this.value = value; + return oldValue; + } + + @Override + public boolean equals(Object obj) + { + if (obj == this) + { + return true; + } + + if (obj instanceof Map.Entry<?, ?>) + { + Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj; + return ObjectUtil.equals(key, entry.getKey()) && ObjectUtil.equals(value, entry.getValue()); + } + + return false; + } + + @Override + public int hashCode() + { + return ObjectUtil.hashCode(key) ^ ObjectUtil.hashCode(value); + } + + @Override + public String toString() + { + return MessageFormat.format("{0}={1}", key, value); //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java index 94bb0f0648..825f796aa2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableArrayList.java @@ -1,84 +1,84 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.ArrayList;
-
-/**
- * A list with O(1) effort for random access.
- *
- * @author Eike Stepper
- */
-public class MoveableArrayList<E> extends ArrayList<E> implements MoveableList<E>
-{
- private static final long serialVersionUID = 1L;
-
- public MoveableArrayList(int initialCapacity)
- {
- super(initialCapacity);
- }
-
- /**
- * @since 3.0
- */
- public void move(int newPosition, Object object)
- {
- move(newPosition, indexOf(object));
- }
-
- public E move(int targetIndex, int sourceIndex)
- {
- int size = size();
- if (sourceIndex >= size)
- {
- throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (targetIndex >= size)
- {
- throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- E object = get(sourceIndex);
- if (targetIndex == sourceIndex)
- {
- return object;
- }
-
- if (targetIndex < sourceIndex)
- {
- moveUp1(targetIndex, sourceIndex - targetIndex);
- }
- else
- {
- moveDown1(targetIndex, targetIndex - sourceIndex);
- }
-
- set(targetIndex, object);
- return object;
- }
-
- private void moveUp1(int index, int count)
- {
- for (int i = count; i > 0; i--)
- {
- set(index + i, get(index + i - 1));
- }
- }
-
- private void moveDown1(int index, int count)
- {
- for (int i = count; i > 0; i--)
- {
- set(index - i, get(index - i + 1));
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.ArrayList; + +/** + * A list with O(1) effort for random access. + * + * @author Eike Stepper + */ +public class MoveableArrayList<E> extends ArrayList<E> implements MoveableList<E> +{ + private static final long serialVersionUID = 1L; + + public MoveableArrayList(int initialCapacity) + { + super(initialCapacity); + } + + /** + * @since 3.0 + */ + public void move(int newPosition, Object object) + { + move(newPosition, indexOf(object)); + } + + public E move(int targetIndex, int sourceIndex) + { + int size = size(); + if (sourceIndex >= size) + { + throw new IndexOutOfBoundsException("sourceIndex=" + sourceIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (targetIndex >= size) + { + throw new IndexOutOfBoundsException("targetIndex=" + targetIndex + ", size=" + size); //$NON-NLS-1$ //$NON-NLS-2$ + } + + E object = get(sourceIndex); + if (targetIndex == sourceIndex) + { + return object; + } + + if (targetIndex < sourceIndex) + { + moveUp1(targetIndex, sourceIndex - targetIndex); + } + else + { + moveDown1(targetIndex, targetIndex - sourceIndex); + } + + set(targetIndex, object); + return object; + } + + private void moveUp1(int index, int count) + { + for (int i = count; i > 0; i--) + { + set(index + i, get(index + i - 1)); + } + } + + private void moveDown1(int index, int count) + { + for (int i = count; i > 0; i--) + { + set(index - i, get(index - i + 1)); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java index 4b1751ee3e..821e1a20dc 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MoveableList.java @@ -1,21 +1,21 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import java.util.List;
-
-/**
- * @author Eike Stepper
- */
-public interface MoveableList<E> extends List<E>
-{
- public E move(int targetIndex, int sourceIndex);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import java.util.List; + +/** + * @author Eike Stepper + */ +public interface MoveableList<E> extends List<E> +{ + public E move(int targetIndex, int sourceIndex); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java index f025e66147..96db56ad3e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/MultiMap.java @@ -1,775 +1,775 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-import java.util.AbstractCollection;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-
-/**
- * @author Eike Stepper
- */
-public abstract class MultiMap<K, V> implements Map<K, V>
-{
- private transient Entries entries;
-
- private transient Set<K> keys;
-
- private transient Collection<V> values;
-
- public MultiMap()
- {
- }
-
- public abstract int getDelegateCount();
-
- public Map<K, V> getDelegate(int index)
- {
- if (0 <= index && index < getDelegateCount())
- {
- return doGetDelegate(index);
- }
-
- return null;
- }
-
- /**
- * @category WRITE
- */
- public void clear()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- public V put(K key, V value)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- public void putAll(Map<? extends K, ? extends V> t)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- public V remove(Object key)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- public boolean containsKey(Object key)
- {
- return containsKey(key, getDelegateCount());
- }
-
- /**
- * @category READ
- */
- public boolean containsValue(Object value)
- {
- for (int i = 0; i < getDelegateCount(); i++)
- {
- Map<K, V> delegate = getDelegate(i);
- if (delegate != null)
- {
- if (delegate.containsValue(value))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * @category READ
- */
- public V get(Object key)
- {
- for (int i = 0; i < getDelegateCount(); i++)
- {
- Map<K, V> delegate = getDelegate(i);
- if (delegate != null)
- {
- if (delegate.containsKey(key))
- {
- return delegate.get(key);
- }
- }
- }
-
- return null;
- }
-
- /**
- * @category READ
- */
- public int size()
- {
- int size = 0;
- Map<K, V> delegate = getDelegate(0);
- if (delegate != null)
- {
- size += delegate.size();
- for (int i = 1; i < getDelegateCount(); i++)
- {
- delegate = getDelegate(i);
- if (delegate != null)
- {
- Set<K> keySet = delegate.keySet();
- for (K key : keySet)
- {
- if (!containsKey(key, i))
- {
- ++size;
- }
- }
- }
- }
- }
-
- return size;
- }
-
- /**
- * @category READ
- */
- public boolean isEmpty()
- {
- for (int i = 0; i < getDelegateCount(); i++)
- {
- Map<K, V> delegate = getDelegate(i);
- if (delegate != null)
- {
- if (!delegate.isEmpty())
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- public synchronized Set<Map.Entry<K, V>> entrySet()
- {
- if (entries == null)
- {
- entries = new Entries();
- }
-
- return entries;
- }
-
- public synchronized Set<K> keySet()
- {
- if (keys == null)
- {
- keys = new Keys();
- }
-
- return keys;
- }
-
- public synchronized Collection<V> values()
- {
- if (values == null)
- {
- values = new Values();
- }
-
- return values;
- }
-
- protected boolean containsKey(Object key, int delegateCount)
- {
- for (int i = 0; i < delegateCount; i++)
- {
- Map<K, V> delegate = getDelegate(i);
- if (delegate != null)
- {
- if (delegate.containsKey(key))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- protected abstract Map<K, V> doGetDelegate(int index);
-
- /**
- * @author Eike Stepper
- */
- public static class ListBased<K, V> extends MultiMap<K, V>
- {
- private List<Map<K, V>> delegates;
-
- public ListBased()
- {
- }
-
- public ListBased(List<Map<K, V>> delegates)
- {
- this.delegates = delegates;
- }
-
- public synchronized List<Map<K, V>> getDelegates()
- {
- if (delegates == null)
- {
- delegates = createDelegates();
- }
-
- return delegates;
- }
-
- public void setDelegates(List<Map<K, V>> delegates)
- {
- this.delegates = delegates;
- }
-
- @Override
- public int getDelegateCount()
- {
- return getDelegates().size();
- }
-
- @Override
- protected Map<K, V> doGetDelegate(int index)
- {
- return getDelegates().get(index);
- }
-
- protected List<Map<K, V>> createDelegates()
- {
- return new ArrayList<Map<K, V>>();
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private final class Entries extends AbstractSet<Entry<K, V>>
- {
- public Entries()
- {
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean add(Entry<K, V> o)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean addAll(Collection<? extends Entry<K, V>> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public void clear()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean remove(Object o)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean removeAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean retainAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean contains(Object o)
- {
- if (o instanceof Map.Entry<?, ?>)
- {
- for (int i = 0; i < getDelegateCount(); i++)
- {
- Map<K, V> delegate = getDelegate(i);
- if (delegate != null)
- {
- @SuppressWarnings("unchecked")
- K key = ((Map.Entry<K, V>)o).getKey();
- if (delegate.containsKey(key))
- {
- @SuppressWarnings("unchecked")
- V value = ((Map.Entry<K, V>)o).getValue();
- if (ObjectUtil.equals(delegate.get(key), value))
- {
- return true;
- }
- }
- }
- }
- }
-
- return false;
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean isEmpty()
- {
- return MultiMap.this.isEmpty();
- }
-
- /**
- * @category READ
- */
- @Override
- public int size()
- {
- return MultiMap.this.size();
- }
-
- @Override
- public Iterator<Entry<K, V>> iterator()
- {
- return new Iterator<Entry<K, V>>()
- {
- private Entry<K, V> next;
-
- private int delegateIndex = -1;
-
- private Iterator<Entry<K, V>> delegateIt;
-
- /**
- * @category WRITE
- */
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- public boolean hasNext()
- {
- next = null;
- while (next == null)
- {
- if (delegateIt == null)
- {
- Map<K, V> delegate = getDelegate(++delegateIndex);
- if (delegate == null)
- {
- // All delegates have been iterated
- break;
- }
-
- delegateIt = delegate.entrySet().iterator();
- }
-
- if (delegateIt.hasNext())
- {
- next = delegateIt.next();
-
- // Check if this key has been returned previously
- if (containsKey(next.getKey(), delegateIndex))
- {
- next = null;
- }
- }
- else
- {
- // Determine next delegate iterator in next loop
- delegateIt = null;
- }
- }
-
- return next != null;
- }
-
- /**
- * @category READ
- */
- public Map.Entry<K, V> next()
- {
- if (next == null)
- {
- throw new NoSuchElementException();
- }
-
- try
- {
- return next;
- }
- finally
- {
- next = null;
- }
- }
- };
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private final class Keys extends AbstractSet<K>
- {
- public Keys()
- {
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean add(K o)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean addAll(Collection<? extends K> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public void clear()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean remove(Object o)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean removeAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean retainAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean contains(Object o)
- {
- return MultiMap.this.containsKey(o);
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean isEmpty()
- {
- return MultiMap.this.isEmpty();
- }
-
- /**
- * @category READ
- */
- @Override
- public int size()
- {
- return MultiMap.this.size();
- }
-
- /**
- * @category READ
- */
- @Override
- public Iterator<K> iterator()
- {
- return new Iterator<K>()
- {
- private K next;
-
- private int delegateIndex = -1;
-
- private Iterator<K> delegateIt;
-
- /**
- * @category WRITE
- */
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- public boolean hasNext()
- {
- next = null;
- while (next == null)
- {
- if (delegateIt == null)
- {
- Map<K, V> delegate = getDelegate(++delegateIndex);
- if (delegate == null)
- {
- // All delegates have been iterated
- break;
- }
-
- delegateIt = delegate.keySet().iterator();
- }
-
- if (delegateIt.hasNext())
- {
- next = delegateIt.next();
-
- // Check if this key has been returned previously
- if (containsKey(next, delegateIndex))
- {
- next = null;
- }
- }
- else
- {
- // Determine next delegate iterator in next loop
- delegateIt = null;
- }
- }
-
- return next != null;
- }
-
- /**
- * @category READ
- */
- public K next()
- {
- if (next == null)
- {
- throw new NoSuchElementException();
- }
-
- try
- {
- return next;
- }
- finally
- {
- next = null;
- }
- }
- };
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private final class Values extends AbstractCollection<V>
- {
- public Values()
- {
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean add(V o)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean addAll(Collection<? extends V> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public void clear()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean remove(Object o)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean removeAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category WRITE
- */
- @Override
- public boolean retainAll(Collection<?> c)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean contains(Object o)
- {
- return MultiMap.this.containsValue(o);
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean isEmpty()
- {
- return MultiMap.this.isEmpty();
- }
-
- /**
- * @category READ
- */
- @Override
- public int size()
- {
- return MultiMap.this.size();
- }
-
- /**
- * @category READ
- */
- @Override
- public Iterator<V> iterator()
- {
- return new Iterator<V>()
- {
- private Iterator<Entry<K, V>> delegateIt = entrySet().iterator();
-
- /**
- * @category WRITE
- */
- public void remove()
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @category READ
- */
- public boolean hasNext()
- {
- return delegateIt.hasNext();
- }
-
- /**
- * @category READ
- */
- public V next()
- {
- return delegateIt.next().getValue();
- }
- };
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.ObjectUtil; + +import java.util.AbstractCollection; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * @author Eike Stepper + */ +public abstract class MultiMap<K, V> implements Map<K, V> +{ + private transient Entries entries; + + private transient Set<K> keys; + + private transient Collection<V> values; + + public MultiMap() + { + } + + public abstract int getDelegateCount(); + + public Map<K, V> getDelegate(int index) + { + if (0 <= index && index < getDelegateCount()) + { + return doGetDelegate(index); + } + + return null; + } + + /** + * @category WRITE + */ + public void clear() + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + public V put(K key, V value) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + public void putAll(Map<? extends K, ? extends V> t) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + public V remove(Object key) + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + public boolean containsKey(Object key) + { + return containsKey(key, getDelegateCount()); + } + + /** + * @category READ + */ + public boolean containsValue(Object value) + { + for (int i = 0; i < getDelegateCount(); i++) + { + Map<K, V> delegate = getDelegate(i); + if (delegate != null) + { + if (delegate.containsValue(value)) + { + return true; + } + } + } + + return false; + } + + /** + * @category READ + */ + public V get(Object key) + { + for (int i = 0; i < getDelegateCount(); i++) + { + Map<K, V> delegate = getDelegate(i); + if (delegate != null) + { + if (delegate.containsKey(key)) + { + return delegate.get(key); + } + } + } + + return null; + } + + /** + * @category READ + */ + public int size() + { + int size = 0; + Map<K, V> delegate = getDelegate(0); + if (delegate != null) + { + size += delegate.size(); + for (int i = 1; i < getDelegateCount(); i++) + { + delegate = getDelegate(i); + if (delegate != null) + { + Set<K> keySet = delegate.keySet(); + for (K key : keySet) + { + if (!containsKey(key, i)) + { + ++size; + } + } + } + } + } + + return size; + } + + /** + * @category READ + */ + public boolean isEmpty() + { + for (int i = 0; i < getDelegateCount(); i++) + { + Map<K, V> delegate = getDelegate(i); + if (delegate != null) + { + if (!delegate.isEmpty()) + { + return false; + } + } + } + + return true; + } + + public synchronized Set<Map.Entry<K, V>> entrySet() + { + if (entries == null) + { + entries = new Entries(); + } + + return entries; + } + + public synchronized Set<K> keySet() + { + if (keys == null) + { + keys = new Keys(); + } + + return keys; + } + + public synchronized Collection<V> values() + { + if (values == null) + { + values = new Values(); + } + + return values; + } + + protected boolean containsKey(Object key, int delegateCount) + { + for (int i = 0; i < delegateCount; i++) + { + Map<K, V> delegate = getDelegate(i); + if (delegate != null) + { + if (delegate.containsKey(key)) + { + return true; + } + } + } + + return false; + } + + protected abstract Map<K, V> doGetDelegate(int index); + + /** + * @author Eike Stepper + */ + public static class ListBased<K, V> extends MultiMap<K, V> + { + private List<Map<K, V>> delegates; + + public ListBased() + { + } + + public ListBased(List<Map<K, V>> delegates) + { + this.delegates = delegates; + } + + public synchronized List<Map<K, V>> getDelegates() + { + if (delegates == null) + { + delegates = createDelegates(); + } + + return delegates; + } + + public void setDelegates(List<Map<K, V>> delegates) + { + this.delegates = delegates; + } + + @Override + public int getDelegateCount() + { + return getDelegates().size(); + } + + @Override + protected Map<K, V> doGetDelegate(int index) + { + return getDelegates().get(index); + } + + protected List<Map<K, V>> createDelegates() + { + return new ArrayList<Map<K, V>>(); + } + } + + /** + * @author Eike Stepper + */ + private final class Entries extends AbstractSet<Entry<K, V>> + { + public Entries() + { + } + + /** + * @category WRITE + */ + @Override + public boolean add(Entry<K, V> o) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean addAll(Collection<? extends Entry<K, V>> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public void clear() + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean remove(Object o) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean removeAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean retainAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + @Override + public boolean contains(Object o) + { + if (o instanceof Map.Entry<?, ?>) + { + for (int i = 0; i < getDelegateCount(); i++) + { + Map<K, V> delegate = getDelegate(i); + if (delegate != null) + { + @SuppressWarnings("unchecked") + K key = ((Map.Entry<K, V>)o).getKey(); + if (delegate.containsKey(key)) + { + @SuppressWarnings("unchecked") + V value = ((Map.Entry<K, V>)o).getValue(); + if (ObjectUtil.equals(delegate.get(key), value)) + { + return true; + } + } + } + } + } + + return false; + } + + /** + * @category READ + */ + @Override + public boolean isEmpty() + { + return MultiMap.this.isEmpty(); + } + + /** + * @category READ + */ + @Override + public int size() + { + return MultiMap.this.size(); + } + + @Override + public Iterator<Entry<K, V>> iterator() + { + return new Iterator<Entry<K, V>>() + { + private Entry<K, V> next; + + private int delegateIndex = -1; + + private Iterator<Entry<K, V>> delegateIt; + + /** + * @category WRITE + */ + public void remove() + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + public boolean hasNext() + { + next = null; + while (next == null) + { + if (delegateIt == null) + { + Map<K, V> delegate = getDelegate(++delegateIndex); + if (delegate == null) + { + // All delegates have been iterated + break; + } + + delegateIt = delegate.entrySet().iterator(); + } + + if (delegateIt.hasNext()) + { + next = delegateIt.next(); + + // Check if this key has been returned previously + if (containsKey(next.getKey(), delegateIndex)) + { + next = null; + } + } + else + { + // Determine next delegate iterator in next loop + delegateIt = null; + } + } + + return next != null; + } + + /** + * @category READ + */ + public Map.Entry<K, V> next() + { + if (next == null) + { + throw new NoSuchElementException(); + } + + try + { + return next; + } + finally + { + next = null; + } + } + }; + } + } + + /** + * @author Eike Stepper + */ + private final class Keys extends AbstractSet<K> + { + public Keys() + { + } + + /** + * @category WRITE + */ + @Override + public boolean add(K o) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean addAll(Collection<? extends K> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public void clear() + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean remove(Object o) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean removeAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean retainAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + @Override + public boolean contains(Object o) + { + return MultiMap.this.containsKey(o); + } + + /** + * @category READ + */ + @Override + public boolean isEmpty() + { + return MultiMap.this.isEmpty(); + } + + /** + * @category READ + */ + @Override + public int size() + { + return MultiMap.this.size(); + } + + /** + * @category READ + */ + @Override + public Iterator<K> iterator() + { + return new Iterator<K>() + { + private K next; + + private int delegateIndex = -1; + + private Iterator<K> delegateIt; + + /** + * @category WRITE + */ + public void remove() + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + public boolean hasNext() + { + next = null; + while (next == null) + { + if (delegateIt == null) + { + Map<K, V> delegate = getDelegate(++delegateIndex); + if (delegate == null) + { + // All delegates have been iterated + break; + } + + delegateIt = delegate.keySet().iterator(); + } + + if (delegateIt.hasNext()) + { + next = delegateIt.next(); + + // Check if this key has been returned previously + if (containsKey(next, delegateIndex)) + { + next = null; + } + } + else + { + // Determine next delegate iterator in next loop + delegateIt = null; + } + } + + return next != null; + } + + /** + * @category READ + */ + public K next() + { + if (next == null) + { + throw new NoSuchElementException(); + } + + try + { + return next; + } + finally + { + next = null; + } + } + }; + } + } + + /** + * @author Eike Stepper + */ + private final class Values extends AbstractCollection<V> + { + public Values() + { + } + + /** + * @category WRITE + */ + @Override + public boolean add(V o) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean addAll(Collection<? extends V> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public void clear() + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean remove(Object o) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean removeAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category WRITE + */ + @Override + public boolean retainAll(Collection<?> c) + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + @Override + public boolean contains(Object o) + { + return MultiMap.this.containsValue(o); + } + + /** + * @category READ + */ + @Override + public boolean isEmpty() + { + return MultiMap.this.isEmpty(); + } + + /** + * @category READ + */ + @Override + public int size() + { + return MultiMap.this.size(); + } + + /** + * @category READ + */ + @Override + public Iterator<V> iterator() + { + return new Iterator<V>() + { + private Iterator<Entry<K, V>> delegateIt = entrySet().iterator(); + + /** + * @category WRITE + */ + public void remove() + { + throw new UnsupportedOperationException(); + } + + /** + * @category READ + */ + public boolean hasNext() + { + return delegateIt.hasNext(); + } + + /** + * @category READ + */ + public V next() + { + return delegateIt.next().getValue(); + } + }; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java index f23cbb46cb..f22a62398c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Pair.java @@ -1,100 +1,100 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-/**
- * @author Eike Stepper
- */
-public class Pair<T1, T2>
-{
- private T1 element1;
-
- private T2 element2;
-
- public Pair()
- {
- }
-
- public Pair(T1 element1, T2 element2)
- {
- this.element1 = element1;
- this.element2 = element2;
- }
-
- /**
- * @since 2.0
- */
- public Pair(Pair<T1, T2> source)
- {
- element1 = source.element1;
- element2 = source.element2;
- }
-
- public final T1 getElement1()
- {
- return element1;
- }
-
- public void setElement1(T1 element1)
- {
- this.element1 = element1;
- }
-
- public final T2 getElement2()
- {
- return element2;
- }
-
- public void setElement2(T2 element2)
- {
- this.element2 = element2;
- }
-
- /**
- * @since 2.0
- */
- @Override
- public boolean equals(Object obj)
- {
- if (this == obj)
- {
- return true;
- }
-
- if (obj instanceof Pair<?, ?>)
- {
- Pair<?, ?> that = (Pair<?, ?>)obj;
- return ObjectUtil.equals(element1, that.getElement1()) && ObjectUtil.equals(element2, that.getElement2());
- }
-
- return false;
- }
-
- /**
- * @since 2.0
- */
- @Override
- public int hashCode()
- {
- return ObjectUtil.hashCode(element1) ^ ObjectUtil.hashCode(element2);
- }
-
- /**
- * @since 2.0
- */
- @Override
- public String toString()
- {
- return "Pair[" + element1 + ", " + element2 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.ObjectUtil; + +/** + * @author Eike Stepper + */ +public class Pair<T1, T2> +{ + private T1 element1; + + private T2 element2; + + public Pair() + { + } + + public Pair(T1 element1, T2 element2) + { + this.element1 = element1; + this.element2 = element2; + } + + /** + * @since 2.0 + */ + public Pair(Pair<T1, T2> source) + { + element1 = source.element1; + element2 = source.element2; + } + + public final T1 getElement1() + { + return element1; + } + + public void setElement1(T1 element1) + { + this.element1 = element1; + } + + public final T2 getElement2() + { + return element2; + } + + public void setElement2(T2 element2) + { + this.element2 = element2; + } + + /** + * @since 2.0 + */ + @Override + public boolean equals(Object obj) + { + if (this == obj) + { + return true; + } + + if (obj instanceof Pair<?, ?>) + { + Pair<?, ?> that = (Pair<?, ?>)obj; + return ObjectUtil.equals(element1, that.getElement1()) && ObjectUtil.equals(element2, that.getElement2()); + } + + return false; + } + + /** + * @since 2.0 + */ + @Override + public int hashCode() + { + return ObjectUtil.hashCode(element1) ^ ObjectUtil.hashCode(element2); + } + + /** + * @since 2.0 + */ + @Override + public String toString() + { + return "Pair[" + element1 + ", " + element2 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java index b5cf423284..db43237894 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/PreferenceHistory.java @@ -1,54 +1,54 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.CheckUtil;
-import org.eclipse.net4j.util.om.pref.OMPreference;
-
-/**
- * @author Eike Stepper
- */
-public class PreferenceHistory extends History<String>
-{
- private OMPreference<String[]> preference;
-
- public PreferenceHistory(OMPreference<String[]> preference)
- {
- CheckUtil.checkArg(preference, "preference");
- this.preference = preference;
- }
-
- public OMPreference<String[]> getPreference()
- {
- return preference;
- }
-
- @Override
- protected void load()
- {
- String[] value = preference.getValue();
- if (value != null)
- {
- for (String data : value)
- {
- IHistoryElement<String> element = createElement(data);
- elements.add(element);
- }
- }
- }
-
- @Override
- protected void save()
- {
- String[] array = getData(new String[size()]);
- preference.setValue(array);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.CheckUtil; +import org.eclipse.net4j.util.om.pref.OMPreference; + +/** + * @author Eike Stepper + */ +public class PreferenceHistory extends History<String> +{ + private OMPreference<String[]> preference; + + public PreferenceHistory(OMPreference<String[]> preference) + { + CheckUtil.checkArg(preference, "preference"); + this.preference = preference; + } + + public OMPreference<String[]> getPreference() + { + return preference; + } + + @Override + protected void load() + { + String[] value = preference.getValue(); + if (value != null) + { + for (String data : value) + { + IHistoryElement<String> element = createElement(data); + elements.add(element); + } + } + } + + @Override + protected void save() + { + String[] array = getData(new String[size()]); + preference.setValue(array); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java index 508c8d62a1..a7b9ebf6be 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/RoundRobinBlockingQueue.java @@ -1,368 +1,368 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public class RoundRobinBlockingQueue<E> implements BlockingQueue<E>
-{
- private BlockingQueue<Entry<E>> list = new LinkedBlockingQueue<Entry<E>>();
-
- public RoundRobinBlockingQueue()
- {
- }
-
- public int remainingCapacity()
- {
- return Integer.MAX_VALUE;
- }
-
- public int size()
- {
- int size = 0;
- synchronized (list)
- {
- for (Entry<E> entry : list)
- {
- size += entry.getCount();
- }
- }
-
- return size;
- }
-
- public boolean isEmpty()
- {
- synchronized (list)
- {
- return list.isEmpty();
- }
- }
-
- public boolean offer(E e)
- {
- synchronized (list)
- {
- for (Entry<E> entry : list)
- {
- if (ObjectUtil.equals(entry.getElement(), e))
- {
- entry.increaseCount();
- return true;
- }
- }
-
- return list.add(new Entry<E>(e));
- }
- }
-
- public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException
- {
- return offer(o);
- }
-
- public void put(E o) throws InterruptedException
- {
- offer(o);
- }
-
- public boolean add(E o)
- {
- return offer(o);
- }
-
- public E poll(long timeout, TimeUnit unit) throws InterruptedException
- {
- synchronized (list)
- {
- Entry<E> entry = list.poll(timeout, unit);
- if (entry == null)
- {
- return null;
- }
-
- if (entry.decreaseCount() > 0)
- {
- list.add(entry);
- }
-
- return entry.getElement();
- }
- }
-
- public E poll()
- {
- synchronized (list)
- {
- Entry<E> entry = list.poll();
- if (entry == null)
- {
- return null;
- }
-
- if (entry.decreaseCount() > 0)
- {
- list.add(entry);
- }
-
- return entry.getElement();
- }
- }
-
- public E take() throws InterruptedException
- {
- synchronized (list)
- {
- Entry<E> entry = list.take();
- if (entry.decreaseCount() > 0)
- {
- list.add(entry);
- }
-
- return entry.getElement();
- }
- }
-
- public E peek()
- {
- synchronized (list)
- {
- Entry<E> entry = list.peek();
- if (entry == null)
- {
- return null;
- }
-
- return entry.getElement();
- }
- }
-
- public E element()
- {
- synchronized (list)
- {
- Entry<E> entry = list.element();
- if (entry == null)
- {
- return null;
- }
-
- return entry.getElement();
- }
- }
-
- public E remove()
- {
- synchronized (list)
- {
- Entry<E> entry = list.remove();
- if (entry.decreaseCount() > 0)
- {
- list.add(entry);
- }
-
- return entry.getElement();
- }
- }
-
- public boolean remove(Object o)
- {
- synchronized (list)
- {
- for (Iterator<Entry<E>> it = list.iterator(); it.hasNext();)
- {
- Entry<E> entry = it.next();
- if (ObjectUtil.equals(entry.getElement(), o))
- {
- if (entry.decreaseCount() > 0)
- {
- it.remove();
- }
-
- return true;
- }
- }
- }
-
- return false;
- }
-
- public void clear()
- {
- synchronized (list)
- {
- list.clear();
- }
- }
-
- public Iterator<E> iterator()
- {
- List<E> copy = new ArrayList<E>();
-
- synchronized (list)
- {
- int round = 0;
- boolean again;
-
- do
- {
- again = false;
- for (Entry<E> entry : list)
- {
- int rest = entry.getCount() - round;
- if (rest > 0)
- {
- copy.add(entry.getElement());
- if (rest > 1)
- {
- again = true;
- }
- }
- }
-
- ++round;
- } while (again);
- }
-
- return copy.iterator();
- }
-
- public boolean contains(Object o)
- {
- synchronized (list)
- {
- for (Entry<E> entry : list)
- {
- if (ObjectUtil.equals(entry.getElement(), o))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- public Object[] toArray()
- {
- synchronized (list)
- {
- return list.toArray();
- }
- }
-
- public <T> T[] toArray(T[] array)
- {
- synchronized (list)
- {
- return list.toArray(array);
- }
- }
-
- public boolean containsAll(Collection<?> c)
- {
- // TODO: implement RoundRobinBlockingQueue.containsAll(c)
- throw new UnsupportedOperationException();
- }
-
- public boolean addAll(Collection<? extends E> c)
- {
- // TODO: implement RoundRobinBlockingQueue.addAll(c)
- throw new UnsupportedOperationException();
- }
-
- public boolean removeAll(Collection<?> c)
- {
- // TODO: implement RoundRobinBlockingQueue.removeAll(c)
- throw new UnsupportedOperationException();
- }
-
- public boolean retainAll(Collection<?> c)
- {
- // TODO: implement RoundRobinBlockingQueue.retainAll(c)
- throw new UnsupportedOperationException();
- }
-
- public int drainTo(Collection<? super E> c)
- {
- // TODO: implement RoundRobinBlockingQueue.drainTo(c)
- throw new UnsupportedOperationException();
- }
-
- public int drainTo(Collection<? super E> c, int maxElements)
- {
- // TODO: implement RoundRobinBlockingQueue.drainTo(c, maxElements)
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String toString()
- {
- synchronized (list)
- {
- return list.toString();
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class Entry<E>
- {
- private E element;
-
- private int count;
-
- public Entry(E element)
- {
- this.element = element;
- count = 1;
- }
-
- public E getElement()
- {
- return element;
- }
-
- public int getCount()
- {
- return count;
- }
-
- public int increaseCount()
- {
- return ++count;
- }
-
- public int decreaseCount()
- {
- return --count;
- }
-
- @Override
- public String toString()
- {
- return element.toString() + "(" + count + ")";
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.ObjectUtil; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public class RoundRobinBlockingQueue<E> implements BlockingQueue<E> +{ + private BlockingQueue<Entry<E>> list = new LinkedBlockingQueue<Entry<E>>(); + + public RoundRobinBlockingQueue() + { + } + + public int remainingCapacity() + { + return Integer.MAX_VALUE; + } + + public int size() + { + int size = 0; + synchronized (list) + { + for (Entry<E> entry : list) + { + size += entry.getCount(); + } + } + + return size; + } + + public boolean isEmpty() + { + synchronized (list) + { + return list.isEmpty(); + } + } + + public boolean offer(E e) + { + synchronized (list) + { + for (Entry<E> entry : list) + { + if (ObjectUtil.equals(entry.getElement(), e)) + { + entry.increaseCount(); + return true; + } + } + + return list.add(new Entry<E>(e)); + } + } + + public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException + { + return offer(o); + } + + public void put(E o) throws InterruptedException + { + offer(o); + } + + public boolean add(E o) + { + return offer(o); + } + + public E poll(long timeout, TimeUnit unit) throws InterruptedException + { + synchronized (list) + { + Entry<E> entry = list.poll(timeout, unit); + if (entry == null) + { + return null; + } + + if (entry.decreaseCount() > 0) + { + list.add(entry); + } + + return entry.getElement(); + } + } + + public E poll() + { + synchronized (list) + { + Entry<E> entry = list.poll(); + if (entry == null) + { + return null; + } + + if (entry.decreaseCount() > 0) + { + list.add(entry); + } + + return entry.getElement(); + } + } + + public E take() throws InterruptedException + { + synchronized (list) + { + Entry<E> entry = list.take(); + if (entry.decreaseCount() > 0) + { + list.add(entry); + } + + return entry.getElement(); + } + } + + public E peek() + { + synchronized (list) + { + Entry<E> entry = list.peek(); + if (entry == null) + { + return null; + } + + return entry.getElement(); + } + } + + public E element() + { + synchronized (list) + { + Entry<E> entry = list.element(); + if (entry == null) + { + return null; + } + + return entry.getElement(); + } + } + + public E remove() + { + synchronized (list) + { + Entry<E> entry = list.remove(); + if (entry.decreaseCount() > 0) + { + list.add(entry); + } + + return entry.getElement(); + } + } + + public boolean remove(Object o) + { + synchronized (list) + { + for (Iterator<Entry<E>> it = list.iterator(); it.hasNext();) + { + Entry<E> entry = it.next(); + if (ObjectUtil.equals(entry.getElement(), o)) + { + if (entry.decreaseCount() > 0) + { + it.remove(); + } + + return true; + } + } + } + + return false; + } + + public void clear() + { + synchronized (list) + { + list.clear(); + } + } + + public Iterator<E> iterator() + { + List<E> copy = new ArrayList<E>(); + + synchronized (list) + { + int round = 0; + boolean again; + + do + { + again = false; + for (Entry<E> entry : list) + { + int rest = entry.getCount() - round; + if (rest > 0) + { + copy.add(entry.getElement()); + if (rest > 1) + { + again = true; + } + } + } + + ++round; + } while (again); + } + + return copy.iterator(); + } + + public boolean contains(Object o) + { + synchronized (list) + { + for (Entry<E> entry : list) + { + if (ObjectUtil.equals(entry.getElement(), o)) + { + return true; + } + } + } + + return false; + } + + public Object[] toArray() + { + synchronized (list) + { + return list.toArray(); + } + } + + public <T> T[] toArray(T[] array) + { + synchronized (list) + { + return list.toArray(array); + } + } + + public boolean containsAll(Collection<?> c) + { + // TODO: implement RoundRobinBlockingQueue.containsAll(c) + throw new UnsupportedOperationException(); + } + + public boolean addAll(Collection<? extends E> c) + { + // TODO: implement RoundRobinBlockingQueue.addAll(c) + throw new UnsupportedOperationException(); + } + + public boolean removeAll(Collection<?> c) + { + // TODO: implement RoundRobinBlockingQueue.removeAll(c) + throw new UnsupportedOperationException(); + } + + public boolean retainAll(Collection<?> c) + { + // TODO: implement RoundRobinBlockingQueue.retainAll(c) + throw new UnsupportedOperationException(); + } + + public int drainTo(Collection<? super E> c) + { + // TODO: implement RoundRobinBlockingQueue.drainTo(c) + throw new UnsupportedOperationException(); + } + + public int drainTo(Collection<? super E> c, int maxElements) + { + // TODO: implement RoundRobinBlockingQueue.drainTo(c, maxElements) + throw new UnsupportedOperationException(); + } + + @Override + public String toString() + { + synchronized (list) + { + return list.toString(); + } + } + + /** + * @author Eike Stepper + */ + private static final class Entry<E> + { + private E element; + + private int count; + + public Entry(E element) + { + this.element = element; + count = 1; + } + + public E getElement() + { + return element; + } + + public int getCount() + { + return count; + } + + public int increaseCount() + { + return ++count; + } + + public int decreaseCount() + { + return --count; + } + + @Override + public String toString() + { + return element.toString() + "(" + count + ")"; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java index 5656c815aa..040be33ec5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/Triplet.java @@ -1,79 +1,79 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Caspar De Groot - initial API and implementation
- */
-package org.eclipse.net4j.util.collection;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-/**
- * @author Caspar De Groot
- * @since 3.0
- */
-public class Triplet<T1, T2, T3> extends Pair<T1, T2>
-{
- private T3 element3;
-
- public Triplet()
- {
- }
-
- public Triplet(T1 element1, T2 element2, T3 element3)
- {
- super(element1, element2);
- this.element3 = element3;
- }
-
- public Triplet(Triplet<T1, T2, T3> source)
- {
- super(source.getElement1(), source.getElement2());
- element3 = source.element3;
- }
-
- public final T3 getElement3()
- {
- return element3;
- }
-
- public void setElement3(T3 element3)
- {
- this.element3 = element3;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (this == obj)
- {
- return true;
- }
-
- if (obj instanceof Triplet<?, ?, ?>)
- {
- Triplet<?, ?, ?> that = (Triplet<?, ?, ?>)obj;
- return ObjectUtil.equals(getElement1(), that.getElement1()) //
- && ObjectUtil.equals(getElement2(), that.getElement2()) //
- && ObjectUtil.equals(element3, that.element3);
- }
-
- return false;
- }
-
- @Override
- public int hashCode()
- {
- return ObjectUtil.hashCode(getElement1()) ^ ObjectUtil.hashCode(getElement2()) ^ ObjectUtil.hashCode(element3);
- }
-
- @Override
- public String toString()
- {
- return "Triplet[" + getElement1() + ", " + getElement2() + ", " + element3 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Caspar De Groot - initial API and implementation + */ +package org.eclipse.net4j.util.collection; + +import org.eclipse.net4j.util.ObjectUtil; + +/** + * @author Caspar De Groot + * @since 3.0 + */ +public class Triplet<T1, T2, T3> extends Pair<T1, T2> +{ + private T3 element3; + + public Triplet() + { + } + + public Triplet(T1 element1, T2 element2, T3 element3) + { + super(element1, element2); + this.element3 = element3; + } + + public Triplet(Triplet<T1, T2, T3> source) + { + super(source.getElement1(), source.getElement2()); + element3 = source.element3; + } + + public final T3 getElement3() + { + return element3; + } + + public void setElement3(T3 element3) + { + this.element3 = element3; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + { + return true; + } + + if (obj instanceof Triplet<?, ?, ?>) + { + Triplet<?, ?, ?> that = (Triplet<?, ?, ?>)obj; + return ObjectUtil.equals(getElement1(), that.getElement1()) // + && ObjectUtil.equals(getElement2(), that.getElement2()) // + && ObjectUtil.equals(element3, that.element3); + } + + return false; + } + + @Override + public int hashCode() + { + return ObjectUtil.hashCode(getElement1()) ^ ObjectUtil.hashCode(getElement2()) ^ ObjectUtil.hashCode(element3); + } + + @Override + public String toString() + { + return "Triplet[" + getElement1() + ", " + getElement2() + ", " + element3 + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java index effa3c9d67..8843c5478b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/collection/package-info.java @@ -1,17 +1,17 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Additional collection-like interfaces and classes.
- * @apiviz.exclude .*
- */
-package org.eclipse.net4j.util.collection;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Additional collection-like interfaces and classes. + * @apiviz.exclude .* + */ +package org.eclipse.net4j.util.collection; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java index 602621d9e2..58c0ce7230 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/AsynchronousWorkSerializer.java @@ -1,161 +1,161 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-
-/**
- * @author Eike Stepper
- */
-public class AsynchronousWorkSerializer implements IWorkSerializer, Runnable
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_CONCURRENCY, AsynchronousWorkSerializer.class);
-
- private ExecutorService executorService;
-
- private Queue<Runnable> workQueue;
-
- private Occupation occupation = new Occupation();
-
- // private Object newElementLock = new Object();
-
- public AsynchronousWorkSerializer(ExecutorService executorService, Queue<Runnable> workQueue)
- {
- if (executorService == null)
- {
- throw new IllegalArgumentException("executorService == null"); //$NON-NLS-1$
- }
-
- this.executorService = executorService;
- this.workQueue = workQueue;
- }
-
- public AsynchronousWorkSerializer(ExecutorService executorService)
- {
- this(executorService, new ConcurrentLinkedQueue<Runnable>());
- }
-
- public ExecutorService getExecutorService()
- {
- return executorService;
- }
-
- public boolean addWork(Runnable work)
- {
- // Need to be a block of execution. Cannot add when doing last check
- // XXX synchronized (newElementLock)
- {
- workQueue.add(work);
-
- // isOccupied can (and must) be called unsynchronized here
- if (!occupation.isOccupied())
- {
- synchronized (occupation)
- {
- occupation.setOccupied(true);
- }
-
- if (TRACER.isEnabled())
- {
- TRACER.trace("Notifying executor service"); //$NON-NLS-1$
- }
-
- executorService.execute(this);
- }
- }
-
- return true;
- }
-
- /**
- * Executed in the context of the {@link #getExecutorService() executor service}.
- * <p>
- */
- public void run()
- {
- // XXX synchronized (occupation)
- {
- Runnable work;
- // for (;;)
- {
- while (occupation.isOccupied() && (work = workQueue.poll()) != null)
- {
- try
- {
- work.run();
- }
- catch (RuntimeException ex)
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace(ex);
- }
- }
- }
-
- // ConcurrencyUtil.sleep(500);
-
- // Could put the sync in the while loop... but not efficient.
- // Doing a last check to make sure that no one added something in the
- // queue
- // synchronized (newElementLock)
- // {
- // if (!occupation.isOccupied() || (work = workQueue.peek()) == null)
- // {
- // occupation.setOccupied(false);
- // break;
- // }
- // }
- }
- }
- }
-
- public void dispose()
- {
- if (occupation.isOccupied())
- {
- occupation.setOccupied(false);
- }
-
- workQueue.clear();
- workQueue = null;
- executorService = null;
- }
-
- @Override
- public String toString()
- {
- return AsynchronousWorkSerializer.class.getSimpleName();
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class Occupation
- {
- private boolean occupied;
-
- public boolean isOccupied()
- {
- return occupied;
- }
-
- public void setOccupied(boolean occupied)
- {
- this.occupied = occupied;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; + +/** + * @author Eike Stepper + */ +public class AsynchronousWorkSerializer implements IWorkSerializer, Runnable +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_CONCURRENCY, AsynchronousWorkSerializer.class); + + private ExecutorService executorService; + + private Queue<Runnable> workQueue; + + private Occupation occupation = new Occupation(); + + // private Object newElementLock = new Object(); + + public AsynchronousWorkSerializer(ExecutorService executorService, Queue<Runnable> workQueue) + { + if (executorService == null) + { + throw new IllegalArgumentException("executorService == null"); //$NON-NLS-1$ + } + + this.executorService = executorService; + this.workQueue = workQueue; + } + + public AsynchronousWorkSerializer(ExecutorService executorService) + { + this(executorService, new ConcurrentLinkedQueue<Runnable>()); + } + + public ExecutorService getExecutorService() + { + return executorService; + } + + public boolean addWork(Runnable work) + { + // Need to be a block of execution. Cannot add when doing last check + // XXX synchronized (newElementLock) + { + workQueue.add(work); + + // isOccupied can (and must) be called unsynchronized here + if (!occupation.isOccupied()) + { + synchronized (occupation) + { + occupation.setOccupied(true); + } + + if (TRACER.isEnabled()) + { + TRACER.trace("Notifying executor service"); //$NON-NLS-1$ + } + + executorService.execute(this); + } + } + + return true; + } + + /** + * Executed in the context of the {@link #getExecutorService() executor service}. + * <p> + */ + public void run() + { + // XXX synchronized (occupation) + { + Runnable work; + // for (;;) + { + while (occupation.isOccupied() && (work = workQueue.poll()) != null) + { + try + { + work.run(); + } + catch (RuntimeException ex) + { + if (TRACER.isEnabled()) + { + TRACER.trace(ex); + } + } + } + + // ConcurrencyUtil.sleep(500); + + // Could put the sync in the while loop... but not efficient. + // Doing a last check to make sure that no one added something in the + // queue + // synchronized (newElementLock) + // { + // if (!occupation.isOccupied() || (work = workQueue.peek()) == null) + // { + // occupation.setOccupied(false); + // break; + // } + // } + } + } + } + + public void dispose() + { + if (occupation.isOccupied()) + { + occupation.setOccupied(false); + } + + workQueue.clear(); + workQueue = null; + executorService = null; + } + + @Override + public String toString() + { + return AsynchronousWorkSerializer.class.getSimpleName(); + } + + /** + * @author Eike Stepper + */ + private static final class Occupation + { + private boolean occupied; + + public boolean isOccupied() + { + return occupied; + } + + public void setOccupied(boolean occupied) + { + this.occupied = occupied; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java index da46e06ec3..872556702c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/CompletionWorkSerializer.java @@ -1,66 +1,66 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.CompletionService;
-import java.util.concurrent.Executor;
-import java.util.concurrent.ExecutorCompletionService;
-import java.util.concurrent.Future;
-
-/**
- * @author Eike Stepper
- */
-public class CompletionWorkSerializer implements IWorkSerializer
-{
- private CompletionService<Object> completionService;
-
- public CompletionWorkSerializer(CompletionService<Object> completionService)
- {
- this.completionService = completionService;
- }
-
- public CompletionWorkSerializer(Executor executor, BlockingQueue<Future<Object>> completionQueue)
- {
- this(new ExecutorCompletionService<Object>(executor, completionQueue));
- }
-
- public CompletionWorkSerializer(Executor executor)
- {
- this(new ExecutorCompletionService<Object>(executor));
- }
-
- public CompletionWorkSerializer()
- {
- this(new OnePendingExecutor());
- }
-
- public CompletionService<Object> getCompletionService()
- {
- return completionService;
- }
-
- public void dispose()
- {
- }
-
- public boolean addWork(Runnable work)
- {
- completionService.submit(work, true);
- return true;
- }
-
- @Override
- public String toString()
- {
- return CompletionWorkSerializer.class.getSimpleName();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletionService; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.Future; + +/** + * @author Eike Stepper + */ +public class CompletionWorkSerializer implements IWorkSerializer +{ + private CompletionService<Object> completionService; + + public CompletionWorkSerializer(CompletionService<Object> completionService) + { + this.completionService = completionService; + } + + public CompletionWorkSerializer(Executor executor, BlockingQueue<Future<Object>> completionQueue) + { + this(new ExecutorCompletionService<Object>(executor, completionQueue)); + } + + public CompletionWorkSerializer(Executor executor) + { + this(new ExecutorCompletionService<Object>(executor)); + } + + public CompletionWorkSerializer() + { + this(new OnePendingExecutor()); + } + + public CompletionService<Object> getCompletionService() + { + return completionService; + } + + public void dispose() + { + } + + public boolean addWork(Runnable work) + { + completionService.submit(work, true); + return true; + } + + @Override + public String toString() + { + return CompletionWorkSerializer.class.getSimpleName(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java index 1a50cc854b..494b51f3b1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ICorrelator.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-/**
- * @author Eike Stepper
- */
-public interface ICorrelator<CORRELATION, VALUE>
-{
- public boolean isCorrelated(CORRELATION correlation);
-
- public VALUE correlate(CORRELATION correlation);
-
- public VALUE correlateUnique(CORRELATION correlation);
-
- public VALUE uncorrelate(CORRELATION correlation);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +/** + * @author Eike Stepper + */ +public interface ICorrelator<CORRELATION, VALUE> +{ + public boolean isCorrelated(CORRELATION correlation); + + public VALUE correlate(CORRELATION correlation); + + public VALUE correlateUnique(CORRELATION correlation); + + public VALUE uncorrelate(CORRELATION correlation); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java index 75064d4ffe..d5d96b4a06 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWLockManager.java @@ -1,63 +1,63 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.Collection;
-
-/**
- * Support Multiple reads/no write and upgrade lock from read to write. Many context could request
- * {@link LockType#WRITE write} lock at the same time. It will privileges first context that has already a
- * {@link LockType#READ read} lock. If no one has any read lock, it's "first come first serve".
- *
- * @author Eike Stepper
- * @since 3.0
- */
-public interface IRWLockManager<OBJECT, CONTEXT>
-{
- public static final int WAIT = 0;
-
- public static final int NO_WAIT = 1;
-
- public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout)
- throws InterruptedException;
-
- public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException;
-
- /**
- * Attempts to release for a given locktype, context and objects.
- *
- * @throws IllegalMonitorStateException
- * Unlocking objects without lock.
- */
- public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock);
-
- /**
- * Attempts to release all locks(read and write) for a given context.
- */
- public void unlock(CONTEXT context);
-
- public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock);
-
- public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock);
-
- /**
- * @author Simon McDuff
- */
- public static enum LockType
- {
- WRITE, READ,
-
- /**
- * @since 3.2
- */
- OPTION
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.Collection; + +/** + * Support Multiple reads/no write and upgrade lock from read to write. Many context could request + * {@link LockType#WRITE write} lock at the same time. It will privileges first context that has already a + * {@link LockType#READ read} lock. If no one has any read lock, it's "first come first serve". + * + * @author Eike Stepper + * @since 3.0 + */ +public interface IRWLockManager<OBJECT, CONTEXT> +{ + public static final int WAIT = 0; + + public static final int NO_WAIT = 1; + + public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout) + throws InterruptedException; + + public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException; + + /** + * Attempts to release for a given locktype, context and objects. + * + * @throws IllegalMonitorStateException + * Unlocking objects without lock. + */ + public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock); + + /** + * Attempts to release all locks(read and write) for a given context. + */ + public void unlock(CONTEXT context); + + public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock); + + public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock); + + /** + * @author Simon McDuff + */ + public static enum LockType + { + WRITE, READ, + + /** + * @since 3.2 + */ + OPTION + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java index df1900a214..356bd1de88 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IRWOLockManager.java @@ -1,48 +1,48 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Caspar De Groot - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.util.concurrent.RWOLockManager.LockState;
-
-import java.util.Collection;
-import java.util.List;
-
-/**
- * A {@link IRWLockManager read/write lock manager} that supports {@link IRWLockManager.LockType#OPTION write option}
- * locks.
- *
- * @author Caspar De Groot
- * @since 3.2
- */
-public interface IRWOLockManager<OBJECT, CONTEXT> extends IRWLockManager<OBJECT, CONTEXT>
-{
- /**
- * Adds locks of the given type, owned by the given context on the given objects.
- */
- public List<LockState<OBJECT, CONTEXT>> lock2(LockType type, CONTEXT context,
- Collection<? extends OBJECT> objectsToLock, long timeout) throws InterruptedException;
-
- /**
- * Removes all locks of the given type, owned by the given context on the given objects.
- */
- public List<LockState<OBJECT, CONTEXT>> unlock2(LockType type, CONTEXT context,
- Collection<? extends OBJECT> objectsToUnlock);
-
- /**
- * Removes all locks owned by the given context on any objects.
- */
- public List<LockState<OBJECT, CONTEXT>> unlock2(CONTEXT context);
-
- /**
- * Removes all locks owned by the given context.
- */
- public List<LockState<OBJECT, CONTEXT>> unlock2(CONTEXT context, Collection<? extends OBJECT> objectsToUnlock);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Caspar De Groot - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.util.concurrent.RWOLockManager.LockState; + +import java.util.Collection; +import java.util.List; + +/** + * A {@link IRWLockManager read/write lock manager} that supports {@link IRWLockManager.LockType#OPTION write option} + * locks. + * + * @author Caspar De Groot + * @since 3.2 + */ +public interface IRWOLockManager<OBJECT, CONTEXT> extends IRWLockManager<OBJECT, CONTEXT> +{ + /** + * Adds locks of the given type, owned by the given context on the given objects. + */ + public List<LockState<OBJECT, CONTEXT>> lock2(LockType type, CONTEXT context, + Collection<? extends OBJECT> objectsToLock, long timeout) throws InterruptedException; + + /** + * Removes all locks of the given type, owned by the given context on the given objects. + */ + public List<LockState<OBJECT, CONTEXT>> unlock2(LockType type, CONTEXT context, + Collection<? extends OBJECT> objectsToUnlock); + + /** + * Removes all locks owned by the given context on any objects. + */ + public List<LockState<OBJECT, CONTEXT>> unlock2(CONTEXT context); + + /** + * Removes all locks owned by the given context. + */ + public List<LockState<OBJECT, CONTEXT>> unlock2(CONTEXT context, Collection<? extends OBJECT> objectsToUnlock); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java index 02db259b42..78c35d4f3a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ISynchronizer.java @@ -1,28 +1,28 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-/**
- * Synchronizes a producer and a consumer thread letting the producer pass a value to the consumer. Both producer and
- * consumer must have access to this {@link ISynchronizer} and there must only ever exist one consumer for it. Once the
- * result value is consumed by the consumer this {@link ISynchronizer} must not be reused.
- * <p>
- *
- * @author Eike Stepper
- */
-public interface ISynchronizer<RESULT>
-{
- public RESULT get(long timeout);
-
- public void put(RESULT result);
-
- public boolean put(RESULT result, long timeout);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +/** + * Synchronizes a producer and a consumer thread letting the producer pass a value to the consumer. Both producer and + * consumer must have access to this {@link ISynchronizer} and there must only ever exist one consumer for it. Once the + * result value is consumed by the consumer this {@link ISynchronizer} must not be reused. + * <p> + * + * @author Eike Stepper + */ +public interface ISynchronizer<RESULT> +{ + public RESULT get(long timeout); + + public void put(RESULT result); + + public boolean put(RESULT result, long timeout); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java index 782af3d834..5b07e6943f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/IWorkSerializer.java @@ -1,21 +1,21 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-/**
- * @author Eike Stepper
- */
-public interface IWorkSerializer
-{
- public boolean addWork(Runnable work);
-
- public void dispose();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +/** + * @author Eike Stepper + */ +public interface IWorkSerializer +{ + public boolean addWork(Runnable work); + + public void dispose(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java index 79287f00f5..4fbde6a9e3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/MonitoredThread.java @@ -1,261 +1,261 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.WrappedException;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class MonitoredThread extends Thread
-{
- private MonitoredThread.ThreadMonitor monitor;
-
- private long timeStamp;
-
- private boolean shutdown;
-
- public MonitoredThread(String name, MonitoredThread.ThreadMonitor monitor)
- {
- super(name);
- this.monitor = monitor;
- }
-
- public long getTimeStamp()
- {
- return timeStamp;
- }
-
- public boolean isIdleTimeoutExpired(long idleTimeOut)
- {
- if (timeStamp != 0L) // Skip in first loop
- {
- long idle = System.currentTimeMillis() - timeStamp;
- return idle > idleTimeOut;
- }
-
- return false;
- }
-
- public void heartBeat()
- {
- if (shutdown)
- {
- throw new ShutdownException();
- }
-
- timeStamp = System.currentTimeMillis();
- }
-
- public void shutdown()
- {
- shutdown = true;
- }
-
- @Override
- public void run()
- {
- monitor.handleStarting(this);
-
- try
- {
- doRun();
- }
- catch (MonitoredThread.ShutdownException ex)
- {
- return;
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- throw WrappedException.wrap(ex);
- }
- finally
- {
- monitor.handleFinished(this);
- }
- }
-
- protected abstract void doRun() throws Exception;
-
- /**
- * @author Eike Stepper
- */
- private static final class ShutdownException extends RuntimeException
- {
- private static final long serialVersionUID = 1L;
- }
-
- /**
- * @author Eike Stepper
- */
- public static interface ThreadMonitor
- {
- public void handleStarting(MonitoredThread thread);
-
- public void handleFinished(MonitoredThread thread);
- }
-
- /**
- * @author Eike Stepper
- */
- public static class MultiThreadMonitor implements MonitoredThread.ThreadMonitor, Runnable
- {
- public static final long SYNCED_START = -1;
-
- private long idleTimeOut;
-
- private long startOffset;
-
- private CountDownLatch startLatch;
-
- private List<MonitoredThread> threads = new ArrayList<MonitoredThread>();
-
- /**
- * @param idleTimeOut
- * The number of milli seconds one of the threads may be idle (i.e. not having called
- * {@link MonitoredThread#heartBeat()}) before {@link #handleTimeoutExpiration(MonitoredThread)} is called.
- * @param startOffset
- * The number of milli seconds to sleep between threads are started. Zero means not to sleep and
- * {@link #SYNCED_START} means that all threads start at the same time by waiting on a shared latch.
- */
- public MultiThreadMonitor(long idleTimeOut, long startOffset)
- {
- this.idleTimeOut = idleTimeOut;
- this.startOffset = startOffset;
- if (startOffset == SYNCED_START)
- {
- startLatch = new CountDownLatch(1);
- }
- }
-
- /**
- * Same as calling <tt>MonitoredThread(idleTimeOut, SYNCED_START)</tt>.
- */
- public MultiThreadMonitor(long timeOut)
- {
- this(timeOut, SYNCED_START);
- }
-
- public long getIdleTimeOut()
- {
- return idleTimeOut;
- }
-
- public void addThread(MonitoredThread thread)
- {
- synchronized (threads)
- {
- threads.add(thread);
- }
- }
-
- public void handleStarting(MonitoredThread thread)
- {
- if (startLatch != null)
- {
- try
- {
- startLatch.await();
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
- else if (startOffset > 0L)
- {
- ConcurrencyUtil.sleep(startOffset);
- }
- }
-
- public void handleFinished(MonitoredThread thread)
- {
- synchronized (threads)
- {
- threads.remove(thread);
- }
- }
-
- public void run()
- {
- startupThreads();
-
- for (;;)
- {
- List<MonitoredThread> idleThreads = new ArrayList<MonitoredThread>();
- synchronized (threads)
- {
- if (threads.isEmpty())
- {
- break;
- }
-
- for (MonitoredThread thread : threads)
- {
- if (thread.isIdleTimeoutExpired(idleTimeOut))
- {
- idleThreads.add(thread);
- }
- }
- }
-
- for (MonitoredThread thread : idleThreads)
- {
- handleTimeoutExpiration(thread);
- }
- }
-
- ConcurrencyUtil.sleep(10);
- }
-
- protected void handleTimeoutExpiration(MonitoredThread thread)
- {
- synchronized (threads)
- {
- threads.remove(thread);
- }
-
- shutdownThreads();
- throw new RuntimeException("Idle timeout expired: " + thread.getName()); //$NON-NLS-1$
- }
-
- private void startupThreads()
- {
- for (MonitoredThread thread : threads)
- {
- thread.start();
- }
-
- if (startLatch != null)
- {
- startLatch.countDown();
- }
- }
-
- private void shutdownThreads()
- {
- synchronized (threads)
- {
- for (MonitoredThread t : threads)
- {
- t.shutdown();
- }
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.WrappedException; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class MonitoredThread extends Thread +{ + private MonitoredThread.ThreadMonitor monitor; + + private long timeStamp; + + private boolean shutdown; + + public MonitoredThread(String name, MonitoredThread.ThreadMonitor monitor) + { + super(name); + this.monitor = monitor; + } + + public long getTimeStamp() + { + return timeStamp; + } + + public boolean isIdleTimeoutExpired(long idleTimeOut) + { + if (timeStamp != 0L) // Skip in first loop + { + long idle = System.currentTimeMillis() - timeStamp; + return idle > idleTimeOut; + } + + return false; + } + + public void heartBeat() + { + if (shutdown) + { + throw new ShutdownException(); + } + + timeStamp = System.currentTimeMillis(); + } + + public void shutdown() + { + shutdown = true; + } + + @Override + public void run() + { + monitor.handleStarting(this); + + try + { + doRun(); + } + catch (MonitoredThread.ShutdownException ex) + { + return; + } + catch (Exception ex) + { + OM.LOG.error(ex); + throw WrappedException.wrap(ex); + } + finally + { + monitor.handleFinished(this); + } + } + + protected abstract void doRun() throws Exception; + + /** + * @author Eike Stepper + */ + private static final class ShutdownException extends RuntimeException + { + private static final long serialVersionUID = 1L; + } + + /** + * @author Eike Stepper + */ + public static interface ThreadMonitor + { + public void handleStarting(MonitoredThread thread); + + public void handleFinished(MonitoredThread thread); + } + + /** + * @author Eike Stepper + */ + public static class MultiThreadMonitor implements MonitoredThread.ThreadMonitor, Runnable + { + public static final long SYNCED_START = -1; + + private long idleTimeOut; + + private long startOffset; + + private CountDownLatch startLatch; + + private List<MonitoredThread> threads = new ArrayList<MonitoredThread>(); + + /** + * @param idleTimeOut + * The number of milli seconds one of the threads may be idle (i.e. not having called + * {@link MonitoredThread#heartBeat()}) before {@link #handleTimeoutExpiration(MonitoredThread)} is called. + * @param startOffset + * The number of milli seconds to sleep between threads are started. Zero means not to sleep and + * {@link #SYNCED_START} means that all threads start at the same time by waiting on a shared latch. + */ + public MultiThreadMonitor(long idleTimeOut, long startOffset) + { + this.idleTimeOut = idleTimeOut; + this.startOffset = startOffset; + if (startOffset == SYNCED_START) + { + startLatch = new CountDownLatch(1); + } + } + + /** + * Same as calling <tt>MonitoredThread(idleTimeOut, SYNCED_START)</tt>. + */ + public MultiThreadMonitor(long timeOut) + { + this(timeOut, SYNCED_START); + } + + public long getIdleTimeOut() + { + return idleTimeOut; + } + + public void addThread(MonitoredThread thread) + { + synchronized (threads) + { + threads.add(thread); + } + } + + public void handleStarting(MonitoredThread thread) + { + if (startLatch != null) + { + try + { + startLatch.await(); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + } + else if (startOffset > 0L) + { + ConcurrencyUtil.sleep(startOffset); + } + } + + public void handleFinished(MonitoredThread thread) + { + synchronized (threads) + { + threads.remove(thread); + } + } + + public void run() + { + startupThreads(); + + for (;;) + { + List<MonitoredThread> idleThreads = new ArrayList<MonitoredThread>(); + synchronized (threads) + { + if (threads.isEmpty()) + { + break; + } + + for (MonitoredThread thread : threads) + { + if (thread.isIdleTimeoutExpired(idleTimeOut)) + { + idleThreads.add(thread); + } + } + } + + for (MonitoredThread thread : idleThreads) + { + handleTimeoutExpiration(thread); + } + } + + ConcurrencyUtil.sleep(10); + } + + protected void handleTimeoutExpiration(MonitoredThread thread) + { + synchronized (threads) + { + threads.remove(thread); + } + + shutdownThreads(); + throw new RuntimeException("Idle timeout expired: " + thread.getName()); //$NON-NLS-1$ + } + + private void startupThreads() + { + for (MonitoredThread thread : threads) + { + thread.start(); + } + + if (startLatch != null) + { + startLatch.countDown(); + } + } + + private void shutdownThreads() + { + synchronized (threads) + { + for (MonitoredThread t : threads) + { + t.shutdown(); + } + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java index f3048c5864..ea22fa8895 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingIntCounter.java @@ -1,67 +1,67 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * @author Eike Stepper
- */
-public final class NonBlockingIntCounter
-{
- private AtomicInteger value;
-
- public NonBlockingIntCounter()
- {
- this(0);
- }
-
- public NonBlockingIntCounter(int initialValue)
- {
- value = new AtomicInteger(initialValue);
- }
-
- public int getValue()
- {
- return value.get();
- }
-
- public int increment()
- {
- int v;
- do
- {
- v = value.get();
- } while (!value.compareAndSet(v, v + 1));
-
- return v + 1;
- }
-
- /**
- * @since 3.0
- */
- public int decrement()
- {
- int v;
- do
- {
- v = value.get();
- } while (!value.compareAndSet(v, v - 1));
-
- return v - 1;
- }
-
- @Override
- public String toString()
- {
- return Long.toString(getValue());
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.atomic.AtomicInteger; + +/** + * @author Eike Stepper + */ +public final class NonBlockingIntCounter +{ + private AtomicInteger value; + + public NonBlockingIntCounter() + { + this(0); + } + + public NonBlockingIntCounter(int initialValue) + { + value = new AtomicInteger(initialValue); + } + + public int getValue() + { + return value.get(); + } + + public int increment() + { + int v; + do + { + v = value.get(); + } while (!value.compareAndSet(v, v + 1)); + + return v + 1; + } + + /** + * @since 3.0 + */ + public int decrement() + { + int v; + do + { + v = value.get(); + } while (!value.compareAndSet(v, v - 1)); + + return v - 1; + } + + @Override + public String toString() + { + return Long.toString(getValue()); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java index ae65ae9716..394cfb8139 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/NonBlockingLongCounter.java @@ -1,67 +1,67 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * @author Eike Stepper
- */
-public final class NonBlockingLongCounter
-{
- private AtomicLong value;
-
- public NonBlockingLongCounter()
- {
- this(0L);
- }
-
- public NonBlockingLongCounter(long initialValue)
- {
- value = new AtomicLong(initialValue);
- }
-
- public long getValue()
- {
- return value.get();
- }
-
- public long increment()
- {
- long v;
- do
- {
- v = value.get();
- } while (!value.compareAndSet(v, v + 1));
-
- return v + 1;
- }
-
- /**
- * @since 3.0
- */
- public long decrement()
- {
- long v;
- do
- {
- v = value.get();
- } while (!value.compareAndSet(v, v - 1));
-
- return v - 1;
- }
-
- @Override
- public String toString()
- {
- return Long.toString(getValue());
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * @author Eike Stepper + */ +public final class NonBlockingLongCounter +{ + private AtomicLong value; + + public NonBlockingLongCounter() + { + this(0L); + } + + public NonBlockingLongCounter(long initialValue) + { + value = new AtomicLong(initialValue); + } + + public long getValue() + { + return value.get(); + } + + public long increment() + { + long v; + do + { + v = value.get(); + } while (!value.compareAndSet(v, v + 1)); + + return v + 1; + } + + /** + * @since 3.0 + */ + public long decrement() + { + long v; + do + { + v = value.get(); + } while (!value.compareAndSet(v, v - 1)); + + return v - 1; + } + + @Override + public String toString() + { + return Long.toString(getValue()); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java index 1e40efdb89..2d90029c4d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/OnePendingExecutor.java @@ -1,64 +1,64 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.Executor;
-
-public class OnePendingExecutor implements Executor
-{
- private Runnable command;
-
- private Thread thread;
-
- public OnePendingExecutor()
- {
- }
-
- public synchronized void execute(Runnable command)
- {
- if (this.command != null)
- {
- throw new IllegalStateException("One command already pending"); //$NON-NLS-1$
- }
-
- this.command = command;
- if (thread == null)
- {
- thread = new Thread()
- {
- @Override
- public void run()
- {
- for (;;)
- {
- Runnable command;
- synchronized (OnePendingExecutor.this)
- {
- if (OnePendingExecutor.this.command == null)
- {
- thread = null;
- return;
- }
-
- command = OnePendingExecutor.this.command;
- OnePendingExecutor.this.command = null;
- }
-
- command.run();
- }
- }
- };
-
- thread.setDaemon(true);
- thread.start();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.Executor; + +public class OnePendingExecutor implements Executor +{ + private Runnable command; + + private Thread thread; + + public OnePendingExecutor() + { + } + + public synchronized void execute(Runnable command) + { + if (this.command != null) + { + throw new IllegalStateException("One command already pending"); //$NON-NLS-1$ + } + + this.command = command; + if (thread == null) + { + thread = new Thread() + { + @Override + public void run() + { + for (;;) + { + Runnable command; + synchronized (OnePendingExecutor.this) + { + if (OnePendingExecutor.this.command == null) + { + thread = null; + return; + } + + command = OnePendingExecutor.this.command; + OnePendingExecutor.this.command = null; + } + + command.run(); + } + } + }; + + thread.setDaemon(true); + thread.start(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java index 2d039d8536..f7d76af702 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueRunner.java @@ -1,28 +1,28 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class QueueRunner extends QueueWorker<Runnable>
-{
- public QueueRunner()
- {
- }
-
- @Override
- protected void work(WorkContext context, Runnable runnable)
- {
- runnable.run();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class QueueRunner extends QueueWorker<Runnable> +{ + public QueueRunner() + { + } + + @Override + protected void work(WorkContext context, Runnable runnable) + { + runnable.run(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java index b4993dd5cd..5a13aca1bb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorker.java @@ -1,134 +1,134 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class QueueWorker<E> extends Worker
-{
- /**
- * @since 3.2
- */
- public static final int DEFAULT_POLL_MILLIS = 100;
-
- private BlockingQueue<E> queue;
-
- private long pollMillis;
-
- public QueueWorker()
- {
- setPollMillis(DEFAULT_POLL_MILLIS);
- }
-
- public long getPollMillis()
- {
- return pollMillis;
- }
-
- public void setPollMillis(long pollMillis)
- {
- this.pollMillis = pollMillis;
- }
-
- /**
- * @since 3.0
- */
- public void clearQueue()
- {
- if (queue != null)
- {
- queue.clear();
- }
- }
-
- public boolean addWork(E element)
- {
- if (queue != null)
- {
- return queue.offer(element);
- }
-
- return false;
- }
-
- @Override
- protected void work(WorkContext context) throws Exception
- {
- if (queue == null)
- {
- context.terminate();
- }
- else
- {
- doWork(context);
- }
- }
-
- private void doWork(WorkContext context) throws InterruptedException
- {
- E element = queue.poll(pollMillis, TimeUnit.MILLISECONDS);
- if (element != null)
- {
- work(context, element);
- }
- }
-
- protected abstract void work(WorkContext context, E element);
-
- protected BlockingQueue<E> createQueue()
- {
- return new LinkedBlockingQueue<E>();
- }
-
- /**
- * @since 3.1
- */
- protected boolean doRemainingWorkBeforeDeactivate()
- {
- return false;
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- queue = createQueue();
- super.doActivate();
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- super.doDeactivate();
- if (queue != null)
- {
- if (doRemainingWorkBeforeDeactivate())
- {
- WorkContext context = new WorkContext();
- while (!queue.isEmpty())
- {
- doWork(context);
- }
- }
- else
- {
- queue.clear();
- }
-
- queue = null;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class QueueWorker<E> extends Worker +{ + /** + * @since 3.2 + */ + public static final int DEFAULT_POLL_MILLIS = 100; + + private BlockingQueue<E> queue; + + private long pollMillis; + + public QueueWorker() + { + setPollMillis(DEFAULT_POLL_MILLIS); + } + + public long getPollMillis() + { + return pollMillis; + } + + public void setPollMillis(long pollMillis) + { + this.pollMillis = pollMillis; + } + + /** + * @since 3.0 + */ + public void clearQueue() + { + if (queue != null) + { + queue.clear(); + } + } + + public boolean addWork(E element) + { + if (queue != null) + { + return queue.offer(element); + } + + return false; + } + + @Override + protected void work(WorkContext context) throws Exception + { + if (queue == null) + { + context.terminate(); + } + else + { + doWork(context); + } + } + + private void doWork(WorkContext context) throws InterruptedException + { + E element = queue.poll(pollMillis, TimeUnit.MILLISECONDS); + if (element != null) + { + work(context, element); + } + } + + protected abstract void work(WorkContext context, E element); + + protected BlockingQueue<E> createQueue() + { + return new LinkedBlockingQueue<E>(); + } + + /** + * @since 3.1 + */ + protected boolean doRemainingWorkBeforeDeactivate() + { + return false; + } + + @Override + protected void doActivate() throws Exception + { + queue = createQueue(); + super.doActivate(); + } + + @Override + protected void doDeactivate() throws Exception + { + super.doDeactivate(); + if (queue != null) + { + if (doRemainingWorkBeforeDeactivate()) + { + WorkContext context = new WorkContext(); + while (!queue.isEmpty()) + { + doWork(context); + } + } + else + { + queue.clear(); + } + + queue = null; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java index de4b985f16..5945f96e8e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/QueueWorkerWorkSerializer.java @@ -1,30 +1,30 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
-import org.eclipse.net4j.util.om.log.OMLogger;
-
-/**
- * @author Eike Stepper
- */
-public class QueueWorkerWorkSerializer extends QueueRunner implements IWorkSerializer
-{
- public QueueWorkerWorkSerializer()
- {
- activate();
- }
-
- public void dispose()
- {
- LifecycleUtil.deactivate(this, OMLogger.Level.DEBUG);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.util.lifecycle.LifecycleUtil; +import org.eclipse.net4j.util.om.log.OMLogger; + +/** + * @author Eike Stepper + */ +public class QueueWorkerWorkSerializer extends QueueRunner implements IWorkSerializer +{ + public QueueWorkerWorkSerializer() + { + activate(); + } + + public void dispose() + { + LifecycleUtil.deactivate(this, OMLogger.Level.DEBUG); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java index 8bf444668d..8a0981a585 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLock.java @@ -1,112 +1,112 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.util.WrappedException;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * @author Eike Stepper
- */
-public class RWLock extends ReentrantReadWriteLock
-{
- private static final long serialVersionUID = 1L;
-
- private long timeoutMillis;
-
- public RWLock(long timeoutMillis)
- {
- this.timeoutMillis = timeoutMillis;
- }
-
- public RWLock(long timeoutMillis, boolean fair)
- {
- super(fair);
- this.timeoutMillis = timeoutMillis;
- }
-
- public <V> V read(Callable<V> callable)
- {
- return call(callable, readLock(), timeoutMillis);
- }
-
- public void read(Runnable runnable)
- {
- run(runnable, readLock(), timeoutMillis);
- }
-
- public <V> V write(Callable<V> callable)
- {
- return call(callable, writeLock(), timeoutMillis);
- }
-
- public void write(Runnable runnable)
- {
- run(runnable, writeLock(), timeoutMillis);
- }
-
- public static <V> V call(Callable<V> callable, Lock lock, long timeoutMillis)
- {
- try
- {
- boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS);
- if (locked)
- {
- try
- {
- return callable.call();
- }
- finally
- {
- lock.unlock();
- }
- }
-
- throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- catch (Exception ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- public static void run(Runnable runnable, Lock lock, long timeoutMillis)
- {
- try
- {
- boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS);
- if (locked)
- {
- try
- {
- runnable.run();
- }
- finally
- {
- lock.unlock();
- }
- }
- else
- {
- throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- catch (Exception ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.util.WrappedException; + +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * @author Eike Stepper + */ +public class RWLock extends ReentrantReadWriteLock +{ + private static final long serialVersionUID = 1L; + + private long timeoutMillis; + + public RWLock(long timeoutMillis) + { + this.timeoutMillis = timeoutMillis; + } + + public RWLock(long timeoutMillis, boolean fair) + { + super(fair); + this.timeoutMillis = timeoutMillis; + } + + public <V> V read(Callable<V> callable) + { + return call(callable, readLock(), timeoutMillis); + } + + public void read(Runnable runnable) + { + run(runnable, readLock(), timeoutMillis); + } + + public <V> V write(Callable<V> callable) + { + return call(callable, writeLock(), timeoutMillis); + } + + public void write(Runnable runnable) + { + run(runnable, writeLock(), timeoutMillis); + } + + public static <V> V call(Callable<V> callable, Lock lock, long timeoutMillis) + { + try + { + boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS); + if (locked) + { + try + { + return callable.call(); + } + finally + { + lock.unlock(); + } + } + + throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + public static void run(Runnable runnable, Lock lock, long timeoutMillis) + { + try + { + boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS); + if (locked) + { + try + { + runnable.run(); + } + finally + { + lock.unlock(); + } + } + else + { + throw new TimeoutException("Acquisition of lock timed out after " + timeoutMillis + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java index 50ae00b8af..7e6a9f2b12 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RWLockManager.java @@ -1,793 +1,793 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Simon McDuff - initial API and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.util.ObjectUtil;
-import org.eclipse.net4j.util.collection.HashBag;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * Support Multiple reads/no write and upgrade lock from read to write. Many context could request
- * {@link IRWLockManager.LockType#WRITE write} lock at the same time. It will privileges first context that has already
- * a {@link IRWLockManager.LockType#READ read} lock. If no one has any read lock, it's "first come first serve".
- *
- * @author Simon McDuff
- * @since 2.0
- * @deprecated Use {@link RWOLockManager}
- */
-@Deprecated
-public class RWLockManager<OBJECT, CONTEXT> extends Lifecycle implements IRWLockManager<OBJECT, CONTEXT>
-{
- private LockStrategy<OBJECT, CONTEXT> readLockStrategy = new LockStrategy<OBJECT, CONTEXT>()
- {
- public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.isReadLock(context);
- }
-
- public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.isReadLockByOthers(context);
- }
-
- public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.canObtainReadLock(context);
- }
-
- public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.readLock(context);
- }
-
- public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.readUnlock(context);
- }
-
- @Override
- public String toString()
- {
- return "ReadLockStrategy";
- }
- };
-
- private LockStrategy<OBJECT, CONTEXT> writeLockStrategy = new LockStrategy<OBJECT, CONTEXT>()
- {
- public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.isWriteLock(context);
- }
-
- public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.isWriteLockByOthers(context);
- }
-
- public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.canObtainWriteLock(context);
- }
-
- public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.writeLock(context);
- }
-
- public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context)
- {
- return entry.writeUnlock(context);
- }
-
- @Override
- public String toString()
- {
- return "WriteLockStrategy";
- }
- };
-
- private Map<OBJECT, LockEntry<OBJECT, CONTEXT>> lockEntries = new HashMap<OBJECT, LockEntry<OBJECT, CONTEXT>>();
-
- private LockChanged lockChanged = new LockChanged();
-
- /**
- * @since 3.0
- */
- public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout)
- throws InterruptedException
- {
- LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
- lock(lockingStrategy, context, objectsToLock, timeout);
- }
-
- /**
- * @since 3.0
- */
- public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException
- {
- List<OBJECT> objectsToLock = Collections.singletonList(objectToLock);
- lock(type, context, objectsToLock, timeout);
- }
-
- /**
- * Attempts to release for a given locktype, context and objects.
- *
- * @throws IllegalMonitorStateException
- * Unlocking objects without lock.
- * @since 3.0
- */
- public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock)
- {
- LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
- unlock(lockingStrategy, context, objectsToUnlock);
- }
-
- /**
- * Attempts to release all locks(read and write) for a given context.
- */
- public void unlock(CONTEXT context)
- {
- synchronized (lockChanged)
- {
- List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
- List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
-
- for (Entry<OBJECT, LockEntry<OBJECT, CONTEXT>> entry : lockEntries.entrySet())
- {
- LockEntry<OBJECT, CONTEXT> lockedContext = entry.getValue();
- LockEntry<OBJECT, CONTEXT> newEntry = lockedContext.clearLock(context);
- if (newEntry == null)
- {
- lockEntrysToRemove.add(lockedContext);
- }
- else if (newEntry != entry)
- {
- lockEntrysToAdd.add(newEntry);
- }
- }
-
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove)
- {
- OBJECT object = lockEntry.getObject();
- lockEntries.remove(object);
- }
-
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd)
- {
- OBJECT object = lockEntry.getObject();
- lockEntries.put(object, lockEntry);
- }
-
- lockChanged.notifyAll();
- }
- }
-
- /**
- * @since 3.0
- */
- public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock)
- {
- LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
- return hasLock(lockingStrategy, context, objectToLock);
- }
-
- /**
- * @since 3.0
- */
- public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock)
- {
- LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type);
- LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock);
- return entry != null && lockingStrategy.isLockedByOthers(entry, context);
- }
-
- /**
- * @since 3.1
- */
- protected void handleLockEntries(CONTEXT context, LockEntryHandler<OBJECT, CONTEXT> handler)
- {
- synchronized (lockChanged)
- {
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values())
- {
- if (context == null || lockEntry.hasContext(context))
- {
- if (!handler.handleLockEntry(lockEntry))
- {
- break;
- }
- }
- }
- }
- }
-
- /**
- * @since 3.1
- */
- protected LockEntry<OBJECT, CONTEXT> getLockEntry(OBJECT objectToLock)
- {
- synchronized (lockChanged)
- {
- return lockEntries.get(objectToLock);
- }
- }
-
- /**
- * @since 3.1
- */
- protected LockStrategy<OBJECT, CONTEXT> getLockingStrategy(LockType type)
- {
- if (type == LockType.READ)
- {
- return readLockStrategy;
- }
-
- if (type == LockType.WRITE)
- {
- return writeLockStrategy;
- }
-
- throw new IllegalArgumentException("Invalid lock type: " + type);
- }
-
- /**
- * @since 3.1
- */
- protected void changeContext(CONTEXT oldContext, CONTEXT newContext)
- {
- synchronized (lockChanged)
- {
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values())
- {
- lockEntry.changeContext(oldContext, newContext);
- }
- }
- }
-
- /**
- * Attempts to release this lock.
- * <p>
- * If the number of context is now zero then the lock is made available for write lock attempts.
- *
- * @throws IllegalMonitorStateException
- * Unlocking object not locked.
- */
- private void unlock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context,
- Collection<? extends OBJECT> objectsToLock)
- {
- synchronized (lockChanged)
- {
- List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
- List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
- for (OBJECT objectToLock : objectsToLock)
- {
- LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock);
- if (entry == null)
- {
- throw new IllegalMonitorStateException();
- }
-
- LockEntry<OBJECT, CONTEXT> newEntry = lockingStrategy.unlock(entry, context);
- if (newEntry == null)
- {
- lockEntrysToRemove.add(entry);
- }
- else if (newEntry != entry)
- {
- lockEntrysToAdd.add(newEntry);
- }
- }
-
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove)
- {
- OBJECT object = lockEntry.getObject();
- lockEntries.remove(object);
- }
-
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd)
- {
- OBJECT object = lockEntry.getObject();
- lockEntries.put(object, lockEntry);
- }
-
- lockChanged.notifyAll();
- }
- }
-
- private boolean hasLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, OBJECT objectToLock)
- {
- LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock);
- return entry != null && lockingStrategy.isLocked(entry, context);
- }
-
- private void lock(LockStrategy<OBJECT, CONTEXT> lockStrategy, CONTEXT context,
- Collection<? extends OBJECT> objectsToLocks, long timeout) throws InterruptedException
- {
- long startTime = System.currentTimeMillis();
- while (true)
- {
- synchronized (lockChanged)
- {
- OBJECT conflict = obtainLock(lockStrategy, context, objectsToLocks);
- if (conflict == null)
- {
- lockChanged.notifyAll();
- return;
- }
-
- long elapsedTime = System.currentTimeMillis() - startTime;
- if (timeout != WAIT && elapsedTime > timeout)
- {
- throw new TimeoutRuntimeException("Could not lock " + conflict + " within " + timeout + " milli seconds"); //$NON-NLS-1$
- }
-
- if (timeout == WAIT)
- {
- lockChanged.wait();
- }
- else
- {
- lockChanged.wait(Math.max(1, timeout - elapsedTime));
- }
- }
- }
- }
-
- private OBJECT obtainLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context,
- Collection<? extends OBJECT> objectsToLock)
- {
- List<LockEntry<OBJECT, CONTEXT>> lockEntrys = new ArrayList<LockEntry<OBJECT, CONTEXT>>();
- for (OBJECT objectToLock : objectsToLock)
- {
- LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock);
- if (entry == null)
- {
- entry = new NoLockEntry<OBJECT, CONTEXT>(objectToLock);
- }
-
- if (lockingStrategy.canObtainLock(entry, context))
- {
- lockEntrys.add(entry);
- }
- else
- {
- return objectToLock;
- }
- }
-
- for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrys)
- {
- OBJECT object = lockEntry.getObject();
- LockEntry<OBJECT, CONTEXT> lock = lockingStrategy.lock(lockEntry, context);
- lockEntries.put(object, lock);
- }
-
- return null;
- }
-
- /**
- * @author Simon McDuff
- * @since 3.1
- * @deprecated Use {@link RWOLockManager}
- */
- @Deprecated
- protected interface LockStrategy<OBJECT, CONTEXT>
- {
- public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
-
- public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
-
- public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context);
- }
-
- /**
- * @author Simon McDuff
- * @since 3.1
- * @deprecated Use {@link RWOLockManager}
- */
- @Deprecated
- protected interface LockEntry<OBJECT, CONTEXT>
- {
- public OBJECT getObject();
-
- public boolean isReadLock(CONTEXT context);
-
- public boolean isWriteLock(CONTEXT context);
-
- public boolean isReadLockByOthers(CONTEXT context);
-
- public boolean isWriteLockByOthers(CONTEXT context);
-
- public boolean canObtainReadLock(CONTEXT context);
-
- public boolean canObtainWriteLock(CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context);
-
- public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context);
-
- /**
- * @since 3.1
- */
- public void changeContext(CONTEXT oldContext, CONTEXT newContext);
-
- /**
- * @since 3.1
- */
- public boolean hasContext(CONTEXT context);
- }
-
- /**
- * @author Eike Stepper
- * @since 3.1
- * @deprecated Use {@link RWOLockManager}
- */
- @Deprecated
- protected interface LockEntryHandler<OBJECT, CONTEXT>
- {
- public boolean handleLockEntry(LockEntry<OBJECT, CONTEXT> lockEntry);
- }
-
- /**
- * @author Simon McDuff
- */
- private static final class ReadLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT>
- {
- private OBJECT object;
-
- private Set<CONTEXT> contexts = new HashBag<CONTEXT>();
-
- public ReadLockEntry(OBJECT objectToLock, CONTEXT context)
- {
- this.object = objectToLock;
- contexts.add(context);
- }
-
- public OBJECT getObject()
- {
- return object;
- }
-
- public boolean isReadLock(CONTEXT context)
- {
- return contexts.contains(context);
- }
-
- public boolean isWriteLock(CONTEXT context)
- {
- return false;
- }
-
- public boolean isReadLockByOthers(CONTEXT context)
- {
- if (contexts.isEmpty())
- {
- return false;
- }
-
- return contexts.size() > (isReadLock(context) ? 1 : 0);
- }
-
- public boolean isWriteLockByOthers(CONTEXT context)
- {
- return false;
- }
-
- public boolean canObtainReadLock(CONTEXT context)
- {
- return true;
- }
-
- public boolean canObtainWriteLock(CONTEXT context)
- {
- return contexts.size() == 1 && contexts.contains(context);
- }
-
- public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context)
- {
- contexts.add(context);
- return this;
- }
-
- public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context)
- {
- return new WriteLockEntry<OBJECT, CONTEXT>(object, context, this);
- }
-
- public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context)
- {
- contexts.remove(context);
- return contexts.isEmpty() ? null : this;
- }
-
- public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context)
- {
- throw new IllegalMonitorStateException();
- }
-
- public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context)
- {
- while (contexts.remove(context))
- {
- }
-
- return contexts.isEmpty() ? null : this;
- }
-
- public void changeContext(CONTEXT oldContext, CONTEXT newContext)
- {
- if (contexts.remove(oldContext))
- {
- contexts.add(newContext);
- }
- }
-
- public boolean hasContext(CONTEXT context)
- {
- return contexts.contains(context);
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("ReadLockEntry[object={0}, contexts={1}]", object, contexts);
- }
- }
-
- /**
- * @author Simon McDuff
- */
- private static final class WriteLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT>
- {
- private OBJECT object;
-
- private CONTEXT context;
-
- private int count;
-
- private ReadLockEntry<OBJECT, CONTEXT> readLock;
-
- public WriteLockEntry(OBJECT object, CONTEXT context, ReadLockEntry<OBJECT, CONTEXT> readLock)
- {
- this.object = object;
- this.context = context;
- this.readLock = readLock;
- this.count = 1;
- }
-
- public OBJECT getObject()
- {
- return object;
- }
-
- public boolean isReadLock(CONTEXT context)
- {
- return readLock != null ? readLock.isReadLock(context) : false;
- }
-
- public boolean isWriteLock(CONTEXT context)
- {
- return ObjectUtil.equals(this.context, context);
- }
-
- public boolean isReadLockByOthers(CONTEXT context)
- {
- return readLock != null ? readLock.isReadLockByOthers(context) : false;
- }
-
- public boolean isWriteLockByOthers(CONTEXT context)
- {
- return context != this.context;
- }
-
- public boolean canObtainWriteLock(CONTEXT context)
- {
- return ObjectUtil.equals(this.context, context);
- }
-
- public boolean canObtainReadLock(CONTEXT context)
- {
- return ObjectUtil.equals(this.context, context);
- }
-
- public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context)
- {
- ReadLockEntry<OBJECT, CONTEXT> lock = getReadLock();
- lock.readLock(context);
- return this;
- }
-
- public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context)
- {
- count++;
- return this;
- }
-
- public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context)
- {
- if (readLock != null)
- {
- if (readLock.readUnlock(context) == null)
- {
- readLock = null;
- }
-
- return this;
- }
-
- throw new IllegalMonitorStateException();
- }
-
- public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context)
- {
- return --count <= 0 ? readLock : this;
- }
-
- public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context)
- {
- if (readLock != null)
- {
- if (readLock.clearLock(context) == null)
- {
- readLock = null;
- }
- }
-
- return ObjectUtil.equals(this.context, context) ? readLock : this;
- }
-
- public void changeContext(CONTEXT oldContext, CONTEXT newContext)
- {
- if (ObjectUtil.equals(context, oldContext))
- {
- context = newContext;
- }
- }
-
- public boolean hasContext(CONTEXT context)
- {
- return ObjectUtil.equals(this.context, context);
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("WriteLockEntry[object={0}, context={1}, count={2}]", object, context, count);
- }
-
- private ReadLockEntry<OBJECT, CONTEXT> getReadLock()
- {
- if (readLock == null)
- {
- readLock = new ReadLockEntry<OBJECT, CONTEXT>(object, context);
- }
-
- return readLock;
- }
- }
-
- /**
- * @author Simon McDuff
- */
- private static final class NoLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT>
- {
- private OBJECT object;
-
- public NoLockEntry(OBJECT objectToLock)
- {
- this.object = objectToLock;
- }
-
- public OBJECT getObject()
- {
- return object;
- }
-
- public boolean isReadLock(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean isWriteLock(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean isReadLockByOthers(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean isWriteLockByOthers(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean canObtainWriteLock(CONTEXT context)
- {
- return true;
- }
-
- public boolean canObtainReadLock(CONTEXT context)
- {
- return true;
- }
-
- public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context)
- {
- return new ReadLockEntry<OBJECT, CONTEXT>(object, context);
- }
-
- public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context)
- {
- return new WriteLockEntry<OBJECT, CONTEXT>(object, context, null);
- }
-
- public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context)
- {
- throw new UnsupportedOperationException();
- }
-
- public void changeContext(CONTEXT oldContext, CONTEXT newContext)
- {
- // Do nothing
- }
-
- public boolean hasContext(CONTEXT context)
- {
- return false;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("NoLockEntry[object={0}]", object);
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class LockChanged
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Simon McDuff - initial API and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.util.ObjectUtil; +import org.eclipse.net4j.util.collection.HashBag; +import org.eclipse.net4j.util.lifecycle.Lifecycle; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Support Multiple reads/no write and upgrade lock from read to write. Many context could request + * {@link IRWLockManager.LockType#WRITE write} lock at the same time. It will privileges first context that has already + * a {@link IRWLockManager.LockType#READ read} lock. If no one has any read lock, it's "first come first serve". + * + * @author Simon McDuff + * @since 2.0 + * @deprecated Use {@link RWOLockManager} + */ +@Deprecated +public class RWLockManager<OBJECT, CONTEXT> extends Lifecycle implements IRWLockManager<OBJECT, CONTEXT> +{ + private LockStrategy<OBJECT, CONTEXT> readLockStrategy = new LockStrategy<OBJECT, CONTEXT>() + { + public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.isReadLock(context); + } + + public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.isReadLockByOthers(context); + } + + public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.canObtainReadLock(context); + } + + public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.readLock(context); + } + + public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.readUnlock(context); + } + + @Override + public String toString() + { + return "ReadLockStrategy"; + } + }; + + private LockStrategy<OBJECT, CONTEXT> writeLockStrategy = new LockStrategy<OBJECT, CONTEXT>() + { + public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.isWriteLock(context); + } + + public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.isWriteLockByOthers(context); + } + + public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.canObtainWriteLock(context); + } + + public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.writeLock(context); + } + + public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context) + { + return entry.writeUnlock(context); + } + + @Override + public String toString() + { + return "WriteLockStrategy"; + } + }; + + private Map<OBJECT, LockEntry<OBJECT, CONTEXT>> lockEntries = new HashMap<OBJECT, LockEntry<OBJECT, CONTEXT>>(); + + private LockChanged lockChanged = new LockChanged(); + + /** + * @since 3.0 + */ + public void lock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToLock, long timeout) + throws InterruptedException + { + LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); + lock(lockingStrategy, context, objectsToLock, timeout); + } + + /** + * @since 3.0 + */ + public void lock(LockType type, CONTEXT context, OBJECT objectToLock, long timeout) throws InterruptedException + { + List<OBJECT> objectsToLock = Collections.singletonList(objectToLock); + lock(type, context, objectsToLock, timeout); + } + + /** + * Attempts to release for a given locktype, context and objects. + * + * @throws IllegalMonitorStateException + * Unlocking objects without lock. + * @since 3.0 + */ + public void unlock(LockType type, CONTEXT context, Collection<? extends OBJECT> objectsToUnlock) + { + LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); + unlock(lockingStrategy, context, objectsToUnlock); + } + + /** + * Attempts to release all locks(read and write) for a given context. + */ + public void unlock(CONTEXT context) + { + synchronized (lockChanged) + { + List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); + List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); + + for (Entry<OBJECT, LockEntry<OBJECT, CONTEXT>> entry : lockEntries.entrySet()) + { + LockEntry<OBJECT, CONTEXT> lockedContext = entry.getValue(); + LockEntry<OBJECT, CONTEXT> newEntry = lockedContext.clearLock(context); + if (newEntry == null) + { + lockEntrysToRemove.add(lockedContext); + } + else if (newEntry != entry) + { + lockEntrysToAdd.add(newEntry); + } + } + + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove) + { + OBJECT object = lockEntry.getObject(); + lockEntries.remove(object); + } + + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd) + { + OBJECT object = lockEntry.getObject(); + lockEntries.put(object, lockEntry); + } + + lockChanged.notifyAll(); + } + } + + /** + * @since 3.0 + */ + public boolean hasLock(LockType type, CONTEXT context, OBJECT objectToLock) + { + LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); + return hasLock(lockingStrategy, context, objectToLock); + } + + /** + * @since 3.0 + */ + public boolean hasLockByOthers(LockType type, CONTEXT context, OBJECT objectToLock) + { + LockStrategy<OBJECT, CONTEXT> lockingStrategy = getLockingStrategy(type); + LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock); + return entry != null && lockingStrategy.isLockedByOthers(entry, context); + } + + /** + * @since 3.1 + */ + protected void handleLockEntries(CONTEXT context, LockEntryHandler<OBJECT, CONTEXT> handler) + { + synchronized (lockChanged) + { + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values()) + { + if (context == null || lockEntry.hasContext(context)) + { + if (!handler.handleLockEntry(lockEntry)) + { + break; + } + } + } + } + } + + /** + * @since 3.1 + */ + protected LockEntry<OBJECT, CONTEXT> getLockEntry(OBJECT objectToLock) + { + synchronized (lockChanged) + { + return lockEntries.get(objectToLock); + } + } + + /** + * @since 3.1 + */ + protected LockStrategy<OBJECT, CONTEXT> getLockingStrategy(LockType type) + { + if (type == LockType.READ) + { + return readLockStrategy; + } + + if (type == LockType.WRITE) + { + return writeLockStrategy; + } + + throw new IllegalArgumentException("Invalid lock type: " + type); + } + + /** + * @since 3.1 + */ + protected void changeContext(CONTEXT oldContext, CONTEXT newContext) + { + synchronized (lockChanged) + { + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntries.values()) + { + lockEntry.changeContext(oldContext, newContext); + } + } + } + + /** + * Attempts to release this lock. + * <p> + * If the number of context is now zero then the lock is made available for write lock attempts. + * + * @throws IllegalMonitorStateException + * Unlocking object not locked. + */ + private void unlock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, + Collection<? extends OBJECT> objectsToLock) + { + synchronized (lockChanged) + { + List<LockEntry<OBJECT, CONTEXT>> lockEntrysToRemove = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); + List<LockEntry<OBJECT, CONTEXT>> lockEntrysToAdd = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); + for (OBJECT objectToLock : objectsToLock) + { + LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock); + if (entry == null) + { + throw new IllegalMonitorStateException(); + } + + LockEntry<OBJECT, CONTEXT> newEntry = lockingStrategy.unlock(entry, context); + if (newEntry == null) + { + lockEntrysToRemove.add(entry); + } + else if (newEntry != entry) + { + lockEntrysToAdd.add(newEntry); + } + } + + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToRemove) + { + OBJECT object = lockEntry.getObject(); + lockEntries.remove(object); + } + + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrysToAdd) + { + OBJECT object = lockEntry.getObject(); + lockEntries.put(object, lockEntry); + } + + lockChanged.notifyAll(); + } + } + + private boolean hasLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, OBJECT objectToLock) + { + LockEntry<OBJECT, CONTEXT> entry = getLockEntry(objectToLock); + return entry != null && lockingStrategy.isLocked(entry, context); + } + + private void lock(LockStrategy<OBJECT, CONTEXT> lockStrategy, CONTEXT context, + Collection<? extends OBJECT> objectsToLocks, long timeout) throws InterruptedException + { + long startTime = System.currentTimeMillis(); + while (true) + { + synchronized (lockChanged) + { + OBJECT conflict = obtainLock(lockStrategy, context, objectsToLocks); + if (conflict == null) + { + lockChanged.notifyAll(); + return; + } + + long elapsedTime = System.currentTimeMillis() - startTime; + if (timeout != WAIT && elapsedTime > timeout) + { + throw new TimeoutRuntimeException("Could not lock " + conflict + " within " + timeout + " milli seconds"); //$NON-NLS-1$ + } + + if (timeout == WAIT) + { + lockChanged.wait(); + } + else + { + lockChanged.wait(Math.max(1, timeout - elapsedTime)); + } + } + } + } + + private OBJECT obtainLock(LockStrategy<OBJECT, CONTEXT> lockingStrategy, CONTEXT context, + Collection<? extends OBJECT> objectsToLock) + { + List<LockEntry<OBJECT, CONTEXT>> lockEntrys = new ArrayList<LockEntry<OBJECT, CONTEXT>>(); + for (OBJECT objectToLock : objectsToLock) + { + LockEntry<OBJECT, CONTEXT> entry = lockEntries.get(objectToLock); + if (entry == null) + { + entry = new NoLockEntry<OBJECT, CONTEXT>(objectToLock); + } + + if (lockingStrategy.canObtainLock(entry, context)) + { + lockEntrys.add(entry); + } + else + { + return objectToLock; + } + } + + for (LockEntry<OBJECT, CONTEXT> lockEntry : lockEntrys) + { + OBJECT object = lockEntry.getObject(); + LockEntry<OBJECT, CONTEXT> lock = lockingStrategy.lock(lockEntry, context); + lockEntries.put(object, lock); + } + + return null; + } + + /** + * @author Simon McDuff + * @since 3.1 + * @deprecated Use {@link RWOLockManager} + */ + @Deprecated + protected interface LockStrategy<OBJECT, CONTEXT> + { + public boolean isLocked(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); + + public boolean isLockedByOthers(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); + + public boolean canObtainLock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> lock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> unlock(LockEntry<OBJECT, CONTEXT> entry, CONTEXT context); + } + + /** + * @author Simon McDuff + * @since 3.1 + * @deprecated Use {@link RWOLockManager} + */ + @Deprecated + protected interface LockEntry<OBJECT, CONTEXT> + { + public OBJECT getObject(); + + public boolean isReadLock(CONTEXT context); + + public boolean isWriteLock(CONTEXT context); + + public boolean isReadLockByOthers(CONTEXT context); + + public boolean isWriteLockByOthers(CONTEXT context); + + public boolean canObtainReadLock(CONTEXT context); + + public boolean canObtainWriteLock(CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context); + + public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context); + + /** + * @since 3.1 + */ + public void changeContext(CONTEXT oldContext, CONTEXT newContext); + + /** + * @since 3.1 + */ + public boolean hasContext(CONTEXT context); + } + + /** + * @author Eike Stepper + * @since 3.1 + * @deprecated Use {@link RWOLockManager} + */ + @Deprecated + protected interface LockEntryHandler<OBJECT, CONTEXT> + { + public boolean handleLockEntry(LockEntry<OBJECT, CONTEXT> lockEntry); + } + + /** + * @author Simon McDuff + */ + private static final class ReadLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT> + { + private OBJECT object; + + private Set<CONTEXT> contexts = new HashBag<CONTEXT>(); + + public ReadLockEntry(OBJECT objectToLock, CONTEXT context) + { + this.object = objectToLock; + contexts.add(context); + } + + public OBJECT getObject() + { + return object; + } + + public boolean isReadLock(CONTEXT context) + { + return contexts.contains(context); + } + + public boolean isWriteLock(CONTEXT context) + { + return false; + } + + public boolean isReadLockByOthers(CONTEXT context) + { + if (contexts.isEmpty()) + { + return false; + } + + return contexts.size() > (isReadLock(context) ? 1 : 0); + } + + public boolean isWriteLockByOthers(CONTEXT context) + { + return false; + } + + public boolean canObtainReadLock(CONTEXT context) + { + return true; + } + + public boolean canObtainWriteLock(CONTEXT context) + { + return contexts.size() == 1 && contexts.contains(context); + } + + public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context) + { + contexts.add(context); + return this; + } + + public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context) + { + return new WriteLockEntry<OBJECT, CONTEXT>(object, context, this); + } + + public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context) + { + contexts.remove(context); + return contexts.isEmpty() ? null : this; + } + + public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context) + { + throw new IllegalMonitorStateException(); + } + + public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context) + { + while (contexts.remove(context)) + { + } + + return contexts.isEmpty() ? null : this; + } + + public void changeContext(CONTEXT oldContext, CONTEXT newContext) + { + if (contexts.remove(oldContext)) + { + contexts.add(newContext); + } + } + + public boolean hasContext(CONTEXT context) + { + return contexts.contains(context); + } + + @Override + public String toString() + { + return MessageFormat.format("ReadLockEntry[object={0}, contexts={1}]", object, contexts); + } + } + + /** + * @author Simon McDuff + */ + private static final class WriteLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT> + { + private OBJECT object; + + private CONTEXT context; + + private int count; + + private ReadLockEntry<OBJECT, CONTEXT> readLock; + + public WriteLockEntry(OBJECT object, CONTEXT context, ReadLockEntry<OBJECT, CONTEXT> readLock) + { + this.object = object; + this.context = context; + this.readLock = readLock; + this.count = 1; + } + + public OBJECT getObject() + { + return object; + } + + public boolean isReadLock(CONTEXT context) + { + return readLock != null ? readLock.isReadLock(context) : false; + } + + public boolean isWriteLock(CONTEXT context) + { + return ObjectUtil.equals(this.context, context); + } + + public boolean isReadLockByOthers(CONTEXT context) + { + return readLock != null ? readLock.isReadLockByOthers(context) : false; + } + + public boolean isWriteLockByOthers(CONTEXT context) + { + return context != this.context; + } + + public boolean canObtainWriteLock(CONTEXT context) + { + return ObjectUtil.equals(this.context, context); + } + + public boolean canObtainReadLock(CONTEXT context) + { + return ObjectUtil.equals(this.context, context); + } + + public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context) + { + ReadLockEntry<OBJECT, CONTEXT> lock = getReadLock(); + lock.readLock(context); + return this; + } + + public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context) + { + count++; + return this; + } + + public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context) + { + if (readLock != null) + { + if (readLock.readUnlock(context) == null) + { + readLock = null; + } + + return this; + } + + throw new IllegalMonitorStateException(); + } + + public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context) + { + return --count <= 0 ? readLock : this; + } + + public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context) + { + if (readLock != null) + { + if (readLock.clearLock(context) == null) + { + readLock = null; + } + } + + return ObjectUtil.equals(this.context, context) ? readLock : this; + } + + public void changeContext(CONTEXT oldContext, CONTEXT newContext) + { + if (ObjectUtil.equals(context, oldContext)) + { + context = newContext; + } + } + + public boolean hasContext(CONTEXT context) + { + return ObjectUtil.equals(this.context, context); + } + + @Override + public String toString() + { + return MessageFormat.format("WriteLockEntry[object={0}, context={1}, count={2}]", object, context, count); + } + + private ReadLockEntry<OBJECT, CONTEXT> getReadLock() + { + if (readLock == null) + { + readLock = new ReadLockEntry<OBJECT, CONTEXT>(object, context); + } + + return readLock; + } + } + + /** + * @author Simon McDuff + */ + private static final class NoLockEntry<OBJECT, CONTEXT> implements LockEntry<OBJECT, CONTEXT> + { + private OBJECT object; + + public NoLockEntry(OBJECT objectToLock) + { + this.object = objectToLock; + } + + public OBJECT getObject() + { + return object; + } + + public boolean isReadLock(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public boolean isWriteLock(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public boolean isReadLockByOthers(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public boolean isWriteLockByOthers(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public boolean canObtainWriteLock(CONTEXT context) + { + return true; + } + + public boolean canObtainReadLock(CONTEXT context) + { + return true; + } + + public LockEntry<OBJECT, CONTEXT> readLock(CONTEXT context) + { + return new ReadLockEntry<OBJECT, CONTEXT>(object, context); + } + + public LockEntry<OBJECT, CONTEXT> writeLock(CONTEXT context) + { + return new WriteLockEntry<OBJECT, CONTEXT>(object, context, null); + } + + public LockEntry<OBJECT, CONTEXT> readUnlock(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public LockEntry<OBJECT, CONTEXT> writeUnlock(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public LockEntry<OBJECT, CONTEXT> clearLock(CONTEXT context) + { + throw new UnsupportedOperationException(); + } + + public void changeContext(CONTEXT oldContext, CONTEXT newContext) + { + // Do nothing + } + + public boolean hasContext(CONTEXT context) + { + return false; + } + + @Override + public String toString() + { + return MessageFormat.format("NoLockEntry[object={0}]", object); + } + } + + /** + * @author Eike Stepper + */ + private static final class LockChanged + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java index c723cd87b1..6a8013ce31 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/ResultSynchronizer.java @@ -1,98 +1,98 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.util.WrappedException;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author Eike Stepper
- */
-public final class ResultSynchronizer<RESULT> implements ISynchronizer<RESULT>
-{
- private RESULT result;
-
- private Object consumerLock = new Object();
-
- private CountDownLatch producerLatch = new CountDownLatch(1);
-
- public ResultSynchronizer()
- {
- }
-
- public RESULT get(long timeout)
- {
- try
- {
- final long stop = System.currentTimeMillis() + timeout;
- synchronized (consumerLock)
- {
- while (result == null)
- {
- try
- {
- final long remaining = stop - System.currentTimeMillis();
- if (remaining <= 0)
- {
- return null;
- }
-
- consumerLock.wait(Math.min(remaining, 100L));
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- return result;
- }
- }
- finally
- {
- producerLatch.countDown();
- }
- }
-
- public void put(RESULT result)
- {
- synchronized (consumerLock)
- {
- this.result = result;
- consumerLock.notifyAll();
- }
- }
-
- public boolean put(RESULT result, long timeout)
- {
- synchronized (consumerLock)
- {
- this.result = result;
- consumerLock.notifyAll();
- }
-
- try
- {
- if (!producerLatch.await(timeout, TimeUnit.MILLISECONDS))
- {
- return false;
- }
- }
- catch (InterruptedException ex)
- {
- return false;
- }
-
- return true;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.util.WrappedException; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * @author Eike Stepper + */ +public final class ResultSynchronizer<RESULT> implements ISynchronizer<RESULT> +{ + private RESULT result; + + private Object consumerLock = new Object(); + + private CountDownLatch producerLatch = new CountDownLatch(1); + + public ResultSynchronizer() + { + } + + public RESULT get(long timeout) + { + try + { + final long stop = System.currentTimeMillis() + timeout; + synchronized (consumerLock) + { + while (result == null) + { + try + { + final long remaining = stop - System.currentTimeMillis(); + if (remaining <= 0) + { + return null; + } + + consumerLock.wait(Math.min(remaining, 100L)); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + } + + return result; + } + } + finally + { + producerLatch.countDown(); + } + } + + public void put(RESULT result) + { + synchronized (consumerLock) + { + this.result = result; + consumerLock.notifyAll(); + } + } + + public boolean put(RESULT result, long timeout) + { + synchronized (consumerLock) + { + this.result = result; + consumerLock.notifyAll(); + } + + try + { + if (!producerLatch.await(timeout, TimeUnit.MILLISECONDS)) + { + return false; + } + } + catch (InterruptedException ex) + { + return false; + } + + return true; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java index 7884e1296e..4a9d834241 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/RoundRobinList.java @@ -1,512 +1,512 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-/**
- * @author Eike Stepper
- */
-public final class RoundRobinList<E> extends LinkedList<E>
-{
- private static final long serialVersionUID = 1L;
-
- private ReadWriteLock lock = new ReentrantReadWriteLock();
-
- private Iterator<E> it;
-
- public RoundRobinList()
- {
- }
-
- public RoundRobinList(Collection<? extends E> c)
- {
- super(c);
- }
-
- public void executeReads(Runnable runnable)
- {
- try
- {
- lock.readLock().lock();
- runnable.run();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- public void executeWrites(Runnable runnable)
- {
- try
- {
- lock.writeLock().lock();
- runnable.run();
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public void add(int index, E element)
- {
- try
- {
- lock.writeLock().lock();
- super.add(index, element);
- it = null;
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public boolean add(E o)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.add(o);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public boolean addAll(Collection<? extends E> c)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.addAll(c);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public boolean addAll(int index, Collection<? extends E> c)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.addAll(index, c);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public void addFirst(E o)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- super.addFirst(o);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public void addLast(E o)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- super.addLast(o);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public void clear()
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- super.clear();
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public Object clone()
- {
- try
- {
- lock.readLock().lock();
- return super.clone();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public boolean contains(Object o)
- {
- try
- {
- lock.readLock().lock();
- return super.contains(o);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public boolean containsAll(Collection<?> c)
- {
- try
- {
- lock.readLock().lock();
- return super.containsAll(c);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public E element()
- {
- try
- {
- lock.readLock().lock();
- if (isEmpty())
- {
- return null;
- }
-
- if (it == null || !it.hasNext())
- {
- it = iterator();
- }
-
- return it.next();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public E get(int index)
- {
- try
- {
- lock.readLock().lock();
- return super.get(index);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public E getFirst()
- {
- try
- {
- lock.readLock().lock();
- return super.getFirst();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public E getLast()
- {
- try
- {
- lock.readLock().lock();
- return super.getLast();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public int indexOf(Object o)
- {
- try
- {
- lock.readLock().lock();
- return super.indexOf(o);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public int lastIndexOf(Object o)
- {
- try
- {
- lock.readLock().lock();
- return super.lastIndexOf(o);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public boolean offer(E o)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.offer(o);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public E peek()
- {
- try
- {
- lock.readLock().lock();
- return super.peek();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public E poll()
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.poll();
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public E remove()
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.remove();
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public E remove(int index)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.remove(index);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public boolean remove(Object o)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.remove(o);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public boolean removeAll(Collection<?> c)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.removeAll(c);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public E removeFirst()
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.removeFirst();
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public E removeLast()
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.removeLast();
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public boolean retainAll(Collection<?> c)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.retainAll(c);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public E set(int index, E element)
- {
- try
- {
- lock.writeLock().lock();
- it = null;
- return super.set(index, element);
- }
- finally
- {
- lock.writeLock().unlock();
- }
- }
-
- @Override
- public List<E> subList(int fromIndex, int toIndex)
- {
- try
- {
- lock.readLock().lock();
- return super.subList(fromIndex, toIndex);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public Object[] toArray()
- {
- try
- {
- lock.readLock().lock();
- return super.toArray();
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-
- @Override
- public <T> T[] toArray(T[] a)
- {
- try
- {
- lock.readLock().lock();
- return super.toArray(a);
- }
- finally
- {
- lock.readLock().unlock();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * @author Eike Stepper + */ +public final class RoundRobinList<E> extends LinkedList<E> +{ + private static final long serialVersionUID = 1L; + + private ReadWriteLock lock = new ReentrantReadWriteLock(); + + private Iterator<E> it; + + public RoundRobinList() + { + } + + public RoundRobinList(Collection<? extends E> c) + { + super(c); + } + + public void executeReads(Runnable runnable) + { + try + { + lock.readLock().lock(); + runnable.run(); + } + finally + { + lock.readLock().unlock(); + } + } + + public void executeWrites(Runnable runnable) + { + try + { + lock.writeLock().lock(); + runnable.run(); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public void add(int index, E element) + { + try + { + lock.writeLock().lock(); + super.add(index, element); + it = null; + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean add(E o) + { + try + { + lock.writeLock().lock(); + it = null; + return super.add(o); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean addAll(Collection<? extends E> c) + { + try + { + lock.writeLock().lock(); + it = null; + return super.addAll(c); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean addAll(int index, Collection<? extends E> c) + { + try + { + lock.writeLock().lock(); + it = null; + return super.addAll(index, c); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public void addFirst(E o) + { + try + { + lock.writeLock().lock(); + it = null; + super.addFirst(o); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public void addLast(E o) + { + try + { + lock.writeLock().lock(); + it = null; + super.addLast(o); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public void clear() + { + try + { + lock.writeLock().lock(); + it = null; + super.clear(); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public Object clone() + { + try + { + lock.readLock().lock(); + return super.clone(); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public boolean contains(Object o) + { + try + { + lock.readLock().lock(); + return super.contains(o); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public boolean containsAll(Collection<?> c) + { + try + { + lock.readLock().lock(); + return super.containsAll(c); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public E element() + { + try + { + lock.readLock().lock(); + if (isEmpty()) + { + return null; + } + + if (it == null || !it.hasNext()) + { + it = iterator(); + } + + return it.next(); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public E get(int index) + { + try + { + lock.readLock().lock(); + return super.get(index); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public E getFirst() + { + try + { + lock.readLock().lock(); + return super.getFirst(); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public E getLast() + { + try + { + lock.readLock().lock(); + return super.getLast(); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public int indexOf(Object o) + { + try + { + lock.readLock().lock(); + return super.indexOf(o); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public int lastIndexOf(Object o) + { + try + { + lock.readLock().lock(); + return super.lastIndexOf(o); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public boolean offer(E o) + { + try + { + lock.writeLock().lock(); + it = null; + return super.offer(o); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public E peek() + { + try + { + lock.readLock().lock(); + return super.peek(); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public E poll() + { + try + { + lock.writeLock().lock(); + it = null; + return super.poll(); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public E remove() + { + try + { + lock.writeLock().lock(); + it = null; + return super.remove(); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public E remove(int index) + { + try + { + lock.writeLock().lock(); + it = null; + return super.remove(index); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean remove(Object o) + { + try + { + lock.writeLock().lock(); + it = null; + return super.remove(o); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean removeAll(Collection<?> c) + { + try + { + lock.writeLock().lock(); + it = null; + return super.removeAll(c); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public E removeFirst() + { + try + { + lock.writeLock().lock(); + it = null; + return super.removeFirst(); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public E removeLast() + { + try + { + lock.writeLock().lock(); + it = null; + return super.removeLast(); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public boolean retainAll(Collection<?> c) + { + try + { + lock.writeLock().lock(); + it = null; + return super.retainAll(c); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public E set(int index, E element) + { + try + { + lock.writeLock().lock(); + it = null; + return super.set(index, element); + } + finally + { + lock.writeLock().unlock(); + } + } + + @Override + public List<E> subList(int fromIndex, int toIndex) + { + try + { + lock.readLock().lock(); + return super.subList(fromIndex, toIndex); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public Object[] toArray() + { + try + { + lock.readLock().lock(); + return super.toArray(); + } + finally + { + lock.readLock().unlock(); + } + } + + @Override + public <T> T[] toArray(T[] a) + { + try + { + lock.readLock().lock(); + return super.toArray(a); + } + finally + { + lock.readLock().unlock(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java index 339ef4053f..8da297c269 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Sleeper.java @@ -1,63 +1,63 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-/**
- * @author Eike Stepper
- */
-public class Sleeper
-{
- private static final int DEFAULT_INTERVAL = 10;
-
- private long start;
-
- private int interval;
-
- public Sleeper()
- {
- this(DEFAULT_INTERVAL);
- }
-
- public Sleeper(int interval)
- {
- this.interval = interval;
- restart();
- }
-
- public int getInterval()
- {
- return interval;
- }
-
- public long getStart()
- {
- return start;
- }
-
- public void restart()
- {
- start = System.currentTimeMillis();
- }
-
- public void sleep(long millis)
- {
- while (System.currentTimeMillis() < start + millis)
- {
- ConcurrencyUtil.sleep(interval);
- }
- }
-
- public void resleep(long millis)
- {
- restart();
- sleep(millis);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +/** + * @author Eike Stepper + */ +public class Sleeper +{ + private static final int DEFAULT_INTERVAL = 10; + + private long start; + + private int interval; + + public Sleeper() + { + this(DEFAULT_INTERVAL); + } + + public Sleeper(int interval) + { + this.interval = interval; + restart(); + } + + public int getInterval() + { + return interval; + } + + public long getStart() + { + return start; + } + + public void restart() + { + start = System.currentTimeMillis(); + } + + public void sleep(long millis) + { + while (System.currentTimeMillis() < start + millis) + { + ConcurrencyUtil.sleep(interval); + } + } + + public void resleep(long millis) + { + restart(); + sleep(millis); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java index dcd2a5fb5e..47e07f3ba0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronizingCorrelator.java @@ -1,126 +1,126 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * @author Eike Stepper
- */
-public class SynchronizingCorrelator<CORRELATION, RESULT> implements ICorrelator<CORRELATION, ISynchronizer<RESULT>>
-{
- private ConcurrentMap<CORRELATION, ISynchronizer<RESULT>> map = new ConcurrentHashMap<CORRELATION, ISynchronizer<RESULT>>(
- 0);
-
- /**
- * @since 3.0
- */
- public ISynchronizer<RESULT> getSynchronizer(CORRELATION correlation)
- {
- return map.get(correlation);
- }
-
- public boolean isCorrelated(CORRELATION correlation)
- {
- return map.containsKey(correlation);
- }
-
- public ISynchronizer<RESULT> correlate(CORRELATION correlation)
- {
- ISynchronizer<RESULT> synchronizer = map.get(correlation);
- if (synchronizer == null)
- {
- synchronizer = createSynchronizer(correlation);
- map.put(correlation, synchronizer);
- }
-
- return synchronizer;
- }
-
- public ISynchronizer<RESULT> correlateUnique(CORRELATION correlation)
- {
- ISynchronizer<RESULT> synchronizer = createSynchronizer(correlation);
- if (map.putIfAbsent(correlation, synchronizer) != null)
- {
- throw new IllegalStateException("Already correlated: " + correlation); //$NON-NLS-1$
- }
-
- return synchronizer;
- }
-
- public ISynchronizer<RESULT> uncorrelate(CORRELATION correlation)
- {
- return map.remove(correlation);
- }
-
- public RESULT get(CORRELATION correlation, long timeout)
- {
- return correlate(correlation).get(timeout);
- }
-
- public void put(CORRELATION correlation, RESULT result)
- {
- correlate(correlation).put(result);
- }
-
- /**
- * @since 3.0
- */
- public boolean putIfCorrelated(CORRELATION correlation, RESULT result)
- {
- ISynchronizer<RESULT> synchronizer = getSynchronizer(correlation);
- if (synchronizer != null)
- {
- synchronizer.put(result);
- return true;
- }
-
- return false;
- }
-
- public boolean put(CORRELATION correlation, RESULT result, long timeout)
- {
- return correlate(correlation).put(result, timeout);
- }
-
- protected ISynchronizer<RESULT> createSynchronizer(final CORRELATION correlation)
- {
- // TODO Make top level class
- return new ISynchronizer<RESULT>()
- {
- private ISynchronizer<RESULT> delegate = new ResultSynchronizer<RESULT>();
-
- public RESULT get(long timeout)
- {
- RESULT result = delegate.get(timeout);
- uncorrelate(correlation);
- return result;
- }
-
- public void put(RESULT result)
- {
- delegate.put(result);
- }
-
- public boolean put(RESULT result, long timeout)
- {
- return delegate.put(result, timeout);
- }
- };
- }
-
- @Override
- public String toString()
- {
- return "SynchronizingCorrelator" + map; //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * @author Eike Stepper + */ +public class SynchronizingCorrelator<CORRELATION, RESULT> implements ICorrelator<CORRELATION, ISynchronizer<RESULT>> +{ + private ConcurrentMap<CORRELATION, ISynchronizer<RESULT>> map = new ConcurrentHashMap<CORRELATION, ISynchronizer<RESULT>>( + 0); + + /** + * @since 3.0 + */ + public ISynchronizer<RESULT> getSynchronizer(CORRELATION correlation) + { + return map.get(correlation); + } + + public boolean isCorrelated(CORRELATION correlation) + { + return map.containsKey(correlation); + } + + public ISynchronizer<RESULT> correlate(CORRELATION correlation) + { + ISynchronizer<RESULT> synchronizer = map.get(correlation); + if (synchronizer == null) + { + synchronizer = createSynchronizer(correlation); + map.put(correlation, synchronizer); + } + + return synchronizer; + } + + public ISynchronizer<RESULT> correlateUnique(CORRELATION correlation) + { + ISynchronizer<RESULT> synchronizer = createSynchronizer(correlation); + if (map.putIfAbsent(correlation, synchronizer) != null) + { + throw new IllegalStateException("Already correlated: " + correlation); //$NON-NLS-1$ + } + + return synchronizer; + } + + public ISynchronizer<RESULT> uncorrelate(CORRELATION correlation) + { + return map.remove(correlation); + } + + public RESULT get(CORRELATION correlation, long timeout) + { + return correlate(correlation).get(timeout); + } + + public void put(CORRELATION correlation, RESULT result) + { + correlate(correlation).put(result); + } + + /** + * @since 3.0 + */ + public boolean putIfCorrelated(CORRELATION correlation, RESULT result) + { + ISynchronizer<RESULT> synchronizer = getSynchronizer(correlation); + if (synchronizer != null) + { + synchronizer.put(result); + return true; + } + + return false; + } + + public boolean put(CORRELATION correlation, RESULT result, long timeout) + { + return correlate(correlation).put(result, timeout); + } + + protected ISynchronizer<RESULT> createSynchronizer(final CORRELATION correlation) + { + // TODO Make top level class + return new ISynchronizer<RESULT>() + { + private ISynchronizer<RESULT> delegate = new ResultSynchronizer<RESULT>(); + + public RESULT get(long timeout) + { + RESULT result = delegate.get(timeout); + uncorrelate(correlation); + return result; + } + + public void put(RESULT result) + { + delegate.put(result); + } + + public boolean put(RESULT result, long timeout) + { + return delegate.put(result, timeout); + } + }; + } + + @Override + public String toString() + { + return "SynchronizingCorrelator" + map; //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java index 2427a92378..c75a839470 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/SynchronousWorkSerializer.java @@ -1,37 +1,37 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-/**
- * @author Eike Stepper
- */
-public class SynchronousWorkSerializer implements IWorkSerializer
-{
- public SynchronousWorkSerializer()
- {
- }
-
- public boolean addWork(Runnable work)
- {
- work.run();
- return true;
- }
-
- public void dispose()
- {
- }
-
- @Override
- public String toString()
- {
- return SynchronousWorkSerializer.class.getSimpleName();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +/** + * @author Eike Stepper + */ +public class SynchronousWorkSerializer implements IWorkSerializer +{ + public SynchronousWorkSerializer() + { + } + + public boolean addWork(Runnable work) + { + work.run(); + return true; + } + + public void dispose() + { + } + + @Override + public String toString() + { + return SynchronousWorkSerializer.class.getSimpleName(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java index 5be51f9c17..517a6f3366 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimeoutRuntimeException.java @@ -1,50 +1,50 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import java.util.concurrent.TimeoutException;
-
-/**
- * @author Eike Stepper
- */
-public class TimeoutRuntimeException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public TimeoutRuntimeException()
- {
- }
-
- public TimeoutRuntimeException(String message)
- {
- super(message);
- }
-
- public TimeoutRuntimeException(Throwable cause)
- {
- super(cause);
- }
-
- public TimeoutRuntimeException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * @since 3.0
- */
- public TimeoutException createTimeoutException()
- {
- TimeoutException timeoutException = new TimeoutException(getMessage());
- timeoutException.initCause(this);
- return timeoutException;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import java.util.concurrent.TimeoutException; + +/** + * @author Eike Stepper + */ +public class TimeoutRuntimeException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public TimeoutRuntimeException() + { + } + + public TimeoutRuntimeException(String message) + { + super(message); + } + + public TimeoutRuntimeException(Throwable cause) + { + super(cause); + } + + public TimeoutRuntimeException(String message, Throwable cause) + { + super(message, cause); + } + + /** + * @since 3.0 + */ + public TimeoutException createTimeoutException() + { + TimeoutException timeoutException = new TimeoutException(getMessage()); + timeoutException.initCause(this); + return timeoutException; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java index 2787ac8158..378464492d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Timeouter.java @@ -1,113 +1,113 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class Timeouter
-{
- private Timer timer;
-
- private long timeout;
-
- private TimerTask timeoutTask;
-
- private volatile long touched;
-
- public Timeouter(Timer timer, long timeout)
- {
- this.timer = timer;
- this.timeout = timeout;
-
- touch();
- scheduleTimeout();
- }
-
- public long getTimeout()
- {
- return timeout;
- }
-
- public void setTimeout(long timeout)
- {
- this.timeout = timeout;
- }
-
- public void touch()
- {
- touched = System.currentTimeMillis();
- }
-
- public void dispose()
- {
- if (timeoutTask != null)
- {
- TimerTask task = timeoutTask;
- timeoutTask = null;
- task.cancel();
- }
- }
-
- protected boolean isDisposed()
- {
- return timeoutTask == null;
- }
-
- protected abstract void handleTimeout(long untouched);
-
- private void scheduleTimeout()
- {
- timeoutTask = new TimerTask()
- {
- @Override
- public void run()
- {
- try
- {
- if (!isDisposed())
- {
- long untouched = System.currentTimeMillis() - touched;
- if (untouched > timeout)
- {
- timeoutTask = null;
- handleTimeout(untouched);
- }
- else
- {
- scheduleTimeout();
- }
- }
- }
- catch (Exception ex)
- {
- OM.LOG.error("TimeouterTask failed", ex);
- }
- }
- };
-
- try
- {
- long delay = Math.max(timeout - (System.currentTimeMillis() - touched), 0L);
- timer.schedule(timeoutTask, delay);
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.internal.util.bundle.OM; + +import java.util.Timer; +import java.util.TimerTask; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class Timeouter +{ + private Timer timer; + + private long timeout; + + private TimerTask timeoutTask; + + private volatile long touched; + + public Timeouter(Timer timer, long timeout) + { + this.timer = timer; + this.timeout = timeout; + + touch(); + scheduleTimeout(); + } + + public long getTimeout() + { + return timeout; + } + + public void setTimeout(long timeout) + { + this.timeout = timeout; + } + + public void touch() + { + touched = System.currentTimeMillis(); + } + + public void dispose() + { + if (timeoutTask != null) + { + TimerTask task = timeoutTask; + timeoutTask = null; + task.cancel(); + } + } + + protected boolean isDisposed() + { + return timeoutTask == null; + } + + protected abstract void handleTimeout(long untouched); + + private void scheduleTimeout() + { + timeoutTask = new TimerTask() + { + @Override + public void run() + { + try + { + if (!isDisposed()) + { + long untouched = System.currentTimeMillis() - touched; + if (untouched > timeout) + { + timeoutTask = null; + handleTimeout(untouched); + } + else + { + scheduleTimeout(); + } + } + } + catch (Exception ex) + { + OM.LOG.error("TimeouterTask failed", ex); + } + } + }; + + try + { + long delay = Math.max(timeout - (System.currentTimeMillis() - touched), 0L); + timer.schedule(timeoutTask, delay); + } + catch (Exception ex) + { + OM.LOG.error(ex); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java index 04c09fb86f..27162c17ab 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/TimerLifecycle.java @@ -1,134 +1,134 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.util.container.IManagedContainer;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.factory.Factory;
-import org.eclipse.net4j.util.factory.ProductCreationException;
-import org.eclipse.net4j.util.lifecycle.ILifecycle;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-import org.eclipse.net4j.util.lifecycle.LifecycleException;
-import org.eclipse.net4j.util.lifecycle.LifecycleState;
-
-import java.util.Timer;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class TimerLifecycle extends Timer implements ILifecycle
-{
- public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.timers";
-
- private Lifecycle delegate = new Lifecycle()
- {
- @Override
- protected void doDeactivate() throws Exception
- {
- cancel();
- }
- };
-
- public TimerLifecycle()
- {
- activate();
- }
-
- public TimerLifecycle(boolean isDaemon)
- {
- super(isDaemon);
- activate();
- }
-
- public TimerLifecycle(String name)
- {
- super(name);
- activate();
- }
-
- public TimerLifecycle(String name, boolean isDaemon)
- {
- super(name, isDaemon);
- activate();
- }
-
- /**
- * @since 3.0
- */
- public final LifecycleState getLifecycleState()
- {
- return delegate.getLifecycleState();
- }
-
- public final boolean isActive()
- {
- return delegate.isActive();
- }
-
- public void addListener(IListener listener)
- {
- delegate.addListener(listener);
- }
-
- public void removeListener(IListener listener)
- {
- delegate.removeListener(listener);
- }
-
- public IListener[] getListeners()
- {
- return delegate.getListeners();
- }
-
- public boolean hasListeners()
- {
- return delegate.hasListeners();
- }
-
- public final void activate() throws LifecycleException
- {
- delegate.activate();
- }
-
- public final Exception deactivate()
- {
- return delegate.deactivate();
- }
-
- /**
- * @author Eike Stepper
- */
- public static class DaemonFactory extends Factory
- {
- public static final String TYPE = "daemon";
-
- public DaemonFactory()
- {
- super(PRODUCT_GROUP, TYPE);
- }
-
- public Object create(String name) throws ProductCreationException
- {
- if (name == null)
- {
- return new TimerLifecycle(true);
- }
-
- return new TimerLifecycle(name, true);
- }
-
- public static TimerLifecycle getTimer(IManagedContainer container, String name)
- {
- return (TimerLifecycle)container.getElement(PRODUCT_GROUP, TYPE, name);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.util.container.IManagedContainer; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.factory.Factory; +import org.eclipse.net4j.util.factory.ProductCreationException; +import org.eclipse.net4j.util.lifecycle.ILifecycle; +import org.eclipse.net4j.util.lifecycle.Lifecycle; +import org.eclipse.net4j.util.lifecycle.LifecycleException; +import org.eclipse.net4j.util.lifecycle.LifecycleState; + +import java.util.Timer; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class TimerLifecycle extends Timer implements ILifecycle +{ + public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.timers"; + + private Lifecycle delegate = new Lifecycle() + { + @Override + protected void doDeactivate() throws Exception + { + cancel(); + } + }; + + public TimerLifecycle() + { + activate(); + } + + public TimerLifecycle(boolean isDaemon) + { + super(isDaemon); + activate(); + } + + public TimerLifecycle(String name) + { + super(name); + activate(); + } + + public TimerLifecycle(String name, boolean isDaemon) + { + super(name, isDaemon); + activate(); + } + + /** + * @since 3.0 + */ + public final LifecycleState getLifecycleState() + { + return delegate.getLifecycleState(); + } + + public final boolean isActive() + { + return delegate.isActive(); + } + + public void addListener(IListener listener) + { + delegate.addListener(listener); + } + + public void removeListener(IListener listener) + { + delegate.removeListener(listener); + } + + public IListener[] getListeners() + { + return delegate.getListeners(); + } + + public boolean hasListeners() + { + return delegate.hasListeners(); + } + + public final void activate() throws LifecycleException + { + delegate.activate(); + } + + public final Exception deactivate() + { + return delegate.deactivate(); + } + + /** + * @author Eike Stepper + */ + public static class DaemonFactory extends Factory + { + public static final String TYPE = "daemon"; + + public DaemonFactory() + { + super(PRODUCT_GROUP, TYPE); + } + + public Object create(String name) throws ProductCreationException + { + if (name == null) + { + return new TimerLifecycle(true); + } + + return new TimerLifecycle(name, true); + } + + public static TimerLifecycle getTimer(IManagedContainer container, String name) + { + return (TimerLifecycle)container.getElement(PRODUCT_GROUP, TYPE, name); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java index a0bfe7322b..99d42e85a9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/Worker.java @@ -1,312 +1,312 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.concurrent;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.IErrorHandler;
-import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class Worker extends Lifecycle
-{
- public static final int DEFAULT_TIMEOUT = 10000;
-
- /**
- * @since 3.0
- */
- public static final IErrorHandler DEFAULT_ERROR_HANDLER = new IErrorHandler()
- {
- public void handleError(Throwable t)
- {
- OM.LOG.error(t);
- }
- };
-
- private static IErrorHandler globalErrorHandler = DEFAULT_ERROR_HANDLER;
-
- private boolean daemon;
-
- private long activationTimeout = DEFAULT_TIMEOUT;
-
- private long deactivationTimeout = DEFAULT_TIMEOUT;
-
- @ExcludeFromDump
- private transient CountDownLatch activationLatch;
-
- @ExcludeFromDump
- private transient WorkerThread workerThread;
-
- public Worker()
- {
- }
-
- public boolean isDaemon()
- {
- return daemon;
- }
-
- public void setDaemon(boolean daemon)
- {
- this.daemon = daemon;
- }
-
- public long getActivationTimeout()
- {
- return activationTimeout;
- }
-
- public void setActivationTimeout(long activationTimeout)
- {
- this.activationTimeout = activationTimeout;
- }
-
- public long getDeactivationTimeout()
- {
- return deactivationTimeout;
- }
-
- public void setDeactivationTimeout(long deactivationTimeout)
- {
- this.deactivationTimeout = deactivationTimeout;
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- activationLatch = new CountDownLatch(1);
- String threadName = getThreadName();
- workerThread = threadName == null ? new WorkerThread() : new WorkerThread(threadName);
- workerThread.start();
- if (!activationLatch.await(activationTimeout, TimeUnit.MILLISECONDS))
- {
- try
- {
- workerThread.stopRunning();
- workerThread.interrupt();
- }
- catch (RuntimeException ex)
- {
- OM.LOG.warn(ex);
- }
-
- throw new TimeoutException("Worker thread activation timed out after " + activationTimeout + " millis"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- try
- {
- workerThread.stopRunning();
- workerThread.interrupt();
- workerThread.join(deactivationTimeout);
- }
- catch (RuntimeException ex)
- {
- OM.LOG.warn(ex);
- }
-
- super.doDeactivate();
- }
-
- protected String getThreadName()
- {
- return null;
- }
-
- /**
- * @since 3.1
- */
- protected void handleError(Exception ex)
- {
- try
- {
- if (globalErrorHandler != null)
- {
- globalErrorHandler.handleError(ex);
- }
- }
- catch (Exception ex1)
- {
- OM.LOG.error(ex1);
- }
- }
-
- protected abstract void work(WorkContext context) throws Exception;
-
- /**
- * @since 3.0
- */
- public static IErrorHandler getGlobalErrorHandler()
- {
- return globalErrorHandler;
- }
-
- /**
- * @since 3.0
- */
- public static IErrorHandler setGlobalErrorHandler(IErrorHandler globalErrorHandler)
- {
- IErrorHandler oldHandler = Worker.globalErrorHandler;
- Worker.globalErrorHandler = globalErrorHandler;
- return oldHandler;
- }
-
- /**
- * @author Eike Stepper
- */
- private final class WorkerThread extends Thread
- {
- private boolean running = true;
-
- public WorkerThread()
- {
- setDaemon(daemon);
- }
-
- public WorkerThread(String threadName)
- {
- super(threadName);
- setDaemon(daemon);
- }
-
- public void stopRunning()
- {
- running = false;
- }
-
- @Override
- public void run()
- {
- WorkContext context = new WorkContext();
- activationLatch.countDown();
- while (running && !isInterrupted())
- {
- try
- {
- context.increaseCount();
- work(context);
- }
- catch (NextWork nextWork)
- {
- try
- {
- nextWork.pause();
- }
- catch (InterruptedException ex)
- {
- break;
- }
- }
- catch (Terminate terminate)
- {
- break;
- }
- catch (InterruptedException ex)
- {
- break;
- }
- catch (Exception ex)
- {
- handleError(ex);
- }
- }
-
- deactivate();
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public class WorkContext
- {
- private long count;
-
- public WorkContext()
- {
- }
-
- public long getCount()
- {
- return count;
- }
-
- public void nextWork()
- {
- throw new NextWork();
- }
-
- public void nextWork(long pauseMillis)
- {
- throw new NextWork(pauseMillis);
- }
-
- public void terminate()
- {
- throw new Terminate();
- }
-
- private void increaseCount()
- {
- ++count;
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class NextWork extends RuntimeException
- {
- private static final long serialVersionUID = 1L;
-
- private long pauseMillis;
-
- public NextWork()
- {
- }
-
- public NextWork(long pauseMillis)
- {
- this.pauseMillis = pauseMillis;
- }
-
- public void pause() throws InterruptedException
- {
- if (pauseMillis > 0)
- {
- Thread.sleep(pauseMillis);
- }
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class Terminate extends RuntimeException
- {
- private static final long serialVersionUID = 1L;
-
- public Terminate()
- {
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.concurrent; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.IErrorHandler; +import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; +import org.eclipse.net4j.util.lifecycle.Lifecycle; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class Worker extends Lifecycle +{ + public static final int DEFAULT_TIMEOUT = 10000; + + /** + * @since 3.0 + */ + public static final IErrorHandler DEFAULT_ERROR_HANDLER = new IErrorHandler() + { + public void handleError(Throwable t) + { + OM.LOG.error(t); + } + }; + + private static IErrorHandler globalErrorHandler = DEFAULT_ERROR_HANDLER; + + private boolean daemon; + + private long activationTimeout = DEFAULT_TIMEOUT; + + private long deactivationTimeout = DEFAULT_TIMEOUT; + + @ExcludeFromDump + private transient CountDownLatch activationLatch; + + @ExcludeFromDump + private transient WorkerThread workerThread; + + public Worker() + { + } + + public boolean isDaemon() + { + return daemon; + } + + public void setDaemon(boolean daemon) + { + this.daemon = daemon; + } + + public long getActivationTimeout() + { + return activationTimeout; + } + + public void setActivationTimeout(long activationTimeout) + { + this.activationTimeout = activationTimeout; + } + + public long getDeactivationTimeout() + { + return deactivationTimeout; + } + + public void setDeactivationTimeout(long deactivationTimeout) + { + this.deactivationTimeout = deactivationTimeout; + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + activationLatch = new CountDownLatch(1); + String threadName = getThreadName(); + workerThread = threadName == null ? new WorkerThread() : new WorkerThread(threadName); + workerThread.start(); + if (!activationLatch.await(activationTimeout, TimeUnit.MILLISECONDS)) + { + try + { + workerThread.stopRunning(); + workerThread.interrupt(); + } + catch (RuntimeException ex) + { + OM.LOG.warn(ex); + } + + throw new TimeoutException("Worker thread activation timed out after " + activationTimeout + " millis"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + @Override + protected void doDeactivate() throws Exception + { + try + { + workerThread.stopRunning(); + workerThread.interrupt(); + workerThread.join(deactivationTimeout); + } + catch (RuntimeException ex) + { + OM.LOG.warn(ex); + } + + super.doDeactivate(); + } + + protected String getThreadName() + { + return null; + } + + /** + * @since 3.1 + */ + protected void handleError(Exception ex) + { + try + { + if (globalErrorHandler != null) + { + globalErrorHandler.handleError(ex); + } + } + catch (Exception ex1) + { + OM.LOG.error(ex1); + } + } + + protected abstract void work(WorkContext context) throws Exception; + + /** + * @since 3.0 + */ + public static IErrorHandler getGlobalErrorHandler() + { + return globalErrorHandler; + } + + /** + * @since 3.0 + */ + public static IErrorHandler setGlobalErrorHandler(IErrorHandler globalErrorHandler) + { + IErrorHandler oldHandler = Worker.globalErrorHandler; + Worker.globalErrorHandler = globalErrorHandler; + return oldHandler; + } + + /** + * @author Eike Stepper + */ + private final class WorkerThread extends Thread + { + private boolean running = true; + + public WorkerThread() + { + setDaemon(daemon); + } + + public WorkerThread(String threadName) + { + super(threadName); + setDaemon(daemon); + } + + public void stopRunning() + { + running = false; + } + + @Override + public void run() + { + WorkContext context = new WorkContext(); + activationLatch.countDown(); + while (running && !isInterrupted()) + { + try + { + context.increaseCount(); + work(context); + } + catch (NextWork nextWork) + { + try + { + nextWork.pause(); + } + catch (InterruptedException ex) + { + break; + } + } + catch (Terminate terminate) + { + break; + } + catch (InterruptedException ex) + { + break; + } + catch (Exception ex) + { + handleError(ex); + } + } + + deactivate(); + } + } + + /** + * @author Eike Stepper + */ + public class WorkContext + { + private long count; + + public WorkContext() + { + } + + public long getCount() + { + return count; + } + + public void nextWork() + { + throw new NextWork(); + } + + public void nextWork(long pauseMillis) + { + throw new NextWork(pauseMillis); + } + + public void terminate() + { + throw new Terminate(); + } + + private void increaseCount() + { + ++count; + } + } + + /** + * @author Eike Stepper + */ + private static final class NextWork extends RuntimeException + { + private static final long serialVersionUID = 1L; + + private long pauseMillis; + + public NextWork() + { + } + + public NextWork(long pauseMillis) + { + this.pauseMillis = pauseMillis; + } + + public void pause() throws InterruptedException + { + if (pauseMillis > 0) + { + Thread.sleep(pauseMillis); + } + } + } + + /** + * @author Eike Stepper + */ + private static final class Terminate extends RuntimeException + { + private static final long serialVersionUID = 1L; + + public Terminate() + { + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java index 9392ff754f..454f4a7eff 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/concurrent/package-info.java @@ -1,17 +1,17 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Utility interfaces and classes commonly useful in concurrent programming.
- * @apiviz.exclude .*
- */
-package org.eclipse.net4j.util.concurrent;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Utility interfaces and classes commonly useful in concurrent programming. + * @apiviz.exclude .* + */ +package org.eclipse.net4j.util.concurrent; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java index f2c0dea2f3..1a9a9397c8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerDelta.java @@ -1,45 +1,45 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-/**
- * A default {@link IContainerDelta container delta} implementation.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerDelta<E> implements IContainerDelta<E>
-{
- private E element;
-
- private Kind kind;
-
- public ContainerDelta(E element, Kind kind)
- {
- this.element = element;
- this.kind = kind;
- }
-
- public E getElement()
- {
- return element;
- }
-
- public E setValue(E value)
- {
- throw new UnsupportedOperationException();
- }
-
- public Kind getKind()
- {
- return kind;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +/** + * A default {@link IContainerDelta container delta} implementation. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerDelta<E> implements IContainerDelta<E> +{ + private E element; + + private Kind kind; + + public ContainerDelta(E element, Kind kind) + { + this.element = element; + this.kind = kind; + } + + public E getElement() + { + return element; + } + + public E setValue(E value) + { + throw new UnsupportedOperationException(); + } + + public Kind getKind() + { + return kind; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java index b61d3912a5..d4a9304687 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEvent.java @@ -1,137 +1,137 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered;
-import org.eclipse.net4j.util.event.Event;
-
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A default {@link IContainerEvent container event} implementation.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class ContainerEvent<E> extends Event implements IContainerEvent<E>
-{
- private static final long serialVersionUID = 1L;
-
- private List<IContainerDelta<E>> deltas;
-
- public ContainerEvent(IContainer<E> container)
- {
- super(container);
- deltas = new ArrayList<IContainerDelta<E>>();
- }
-
- public ContainerEvent(IContainer<E> container, List<IContainerDelta<E>> deltas)
- {
- super(container);
- this.deltas = deltas;
- }
-
- /**
- * @since 3.0
- */
- @Override
- @SuppressWarnings("unchecked")
- public IContainer<E> getSource()
- {
- return (IContainer<E>)super.getSource();
- }
-
- public boolean isEmpty()
- {
- return deltas.isEmpty();
- }
-
- @SuppressWarnings("unchecked")
- public IContainerDelta<E>[] getDeltas()
- {
- return deltas.toArray(new IContainerDelta[deltas.size()]);
- }
-
- public IContainerDelta<E> getDelta() throws IllegalStateException
- {
- if (deltas.size() != 1)
- {
- throw new IllegalStateException("deltas.size() != 1"); //$NON-NLS-1$
- }
-
- return deltas.get(0);
- }
-
- public E getDeltaElement() throws IllegalStateException
- {
- return getDelta().getElement();
- }
-
- public IContainerDelta.Kind getDeltaKind() throws IllegalStateException
- {
- return getDelta().getKind();
- }
-
- public void addDelta(E element, IContainerDelta.Kind kind)
- {
- addDelta(new ContainerDelta<E>(element, kind));
- }
-
- public void addDelta(IContainerDelta<E> delta)
- {
- deltas.add(delta);
- }
-
- public void accept(IContainerEventVisitor<E> visitor)
- {
- for (IContainerDelta<E> delta : deltas)
- {
- E element = delta.getElement();
-
- boolean filtered = true;
- if (visitor instanceof Filtered<?>)
- {
- filtered = ((Filtered<E>)visitor).filter(element);
- }
-
- if (filtered)
- {
- switch (delta.getKind())
- {
- case ADDED:
- visitor.added(element);
- break;
- case REMOVED:
- visitor.removed(element);
- break;
- }
- }
- }
- }
-
- @Override
- public String toString()
- {
- StringBuilder builder = new StringBuilder();
- for (IContainerDelta<E> delta : getDeltas())
- {
- builder.append(", "); //$NON-NLS-1$
- builder.append(delta.getKind());
- builder.append("="); //$NON-NLS-1$
- builder.append(delta.getElement());
- }
-
- return MessageFormat.format("ContainerEvent[source={0}{1}]", getSource(), builder.toString()); //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered; +import org.eclipse.net4j.util.event.Event; + +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.List; + +/** + * A default {@link IContainerEvent container event} implementation. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class ContainerEvent<E> extends Event implements IContainerEvent<E> +{ + private static final long serialVersionUID = 1L; + + private List<IContainerDelta<E>> deltas; + + public ContainerEvent(IContainer<E> container) + { + super(container); + deltas = new ArrayList<IContainerDelta<E>>(); + } + + public ContainerEvent(IContainer<E> container, List<IContainerDelta<E>> deltas) + { + super(container); + this.deltas = deltas; + } + + /** + * @since 3.0 + */ + @Override + @SuppressWarnings("unchecked") + public IContainer<E> getSource() + { + return (IContainer<E>)super.getSource(); + } + + public boolean isEmpty() + { + return deltas.isEmpty(); + } + + @SuppressWarnings("unchecked") + public IContainerDelta<E>[] getDeltas() + { + return deltas.toArray(new IContainerDelta[deltas.size()]); + } + + public IContainerDelta<E> getDelta() throws IllegalStateException + { + if (deltas.size() != 1) + { + throw new IllegalStateException("deltas.size() != 1"); //$NON-NLS-1$ + } + + return deltas.get(0); + } + + public E getDeltaElement() throws IllegalStateException + { + return getDelta().getElement(); + } + + public IContainerDelta.Kind getDeltaKind() throws IllegalStateException + { + return getDelta().getKind(); + } + + public void addDelta(E element, IContainerDelta.Kind kind) + { + addDelta(new ContainerDelta<E>(element, kind)); + } + + public void addDelta(IContainerDelta<E> delta) + { + deltas.add(delta); + } + + public void accept(IContainerEventVisitor<E> visitor) + { + for (IContainerDelta<E> delta : deltas) + { + E element = delta.getElement(); + + boolean filtered = true; + if (visitor instanceof Filtered<?>) + { + filtered = ((Filtered<E>)visitor).filter(element); + } + + if (filtered) + { + switch (delta.getKind()) + { + case ADDED: + visitor.added(element); + break; + case REMOVED: + visitor.removed(element); + break; + } + } + } + } + + @Override + public String toString() + { + StringBuilder builder = new StringBuilder(); + for (IContainerDelta<E> delta : getDeltas()) + { + builder.append(", "); //$NON-NLS-1$ + builder.append(delta.getKind()); + builder.append("="); //$NON-NLS-1$ + builder.append(delta.getElement()); + } + + return MessageFormat.format("ContainerEvent[source={0}{1}]", getSource(), builder.toString()); //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java index 5745dbb809..609d67f713 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerEventAdapter.java @@ -1,71 +1,71 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.event.IEvent;
-import org.eclipse.net4j.util.event.IListener;
-
-/**
- * A {@link IListener listener} that dispatches container {@link IContainerEvent events} to methods that can be
- * overridden by extenders.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerEventAdapter<E> implements IListener
-{
- public ContainerEventAdapter()
- {
- }
-
- public final void notifyEvent(IEvent event)
- {
- if (event instanceof IContainerEvent<?>)
- {
- @SuppressWarnings("unchecked")
- IContainerEvent<E> e = (IContainerEvent<E>)event;
- notifyContainerEvent(e);
- }
- else
- {
- notifyOtherEvent(event);
- }
- }
-
- protected void notifyContainerEvent(IContainerEvent<E> event)
- {
- final IContainer<E> container = event.getSource();
- event.accept(new IContainerEventVisitor<E>()
- {
- public void added(E element)
- {
- onAdded(container, element);
- }
-
- public void removed(E element)
- {
- onRemoved(container, element);
- }
- });
- }
-
- protected void notifyOtherEvent(IEvent event)
- {
- }
-
- protected void onAdded(IContainer<E> container, E element)
- {
- }
-
- protected void onRemoved(IContainer<E> container, E element)
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.event.IEvent; +import org.eclipse.net4j.util.event.IListener; + +/** + * A {@link IListener listener} that dispatches container {@link IContainerEvent events} to methods that can be + * overridden by extenders. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerEventAdapter<E> implements IListener +{ + public ContainerEventAdapter() + { + } + + public final void notifyEvent(IEvent event) + { + if (event instanceof IContainerEvent<?>) + { + @SuppressWarnings("unchecked") + IContainerEvent<E> e = (IContainerEvent<E>)event; + notifyContainerEvent(e); + } + else + { + notifyOtherEvent(event); + } + } + + protected void notifyContainerEvent(IContainerEvent<E> event) + { + final IContainer<E> container = event.getSource(); + event.accept(new IContainerEventVisitor<E>() + { + public void added(E element) + { + onAdded(container, element); + } + + public void removed(E element) + { + onRemoved(container, element); + } + }); + } + + protected void notifyOtherEvent(IEvent event) + { + } + + protected void onAdded(IContainer<E> container, E element) + { + } + + protected void onRemoved(IContainer<E> container, E element) + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java index c6032c87b0..40416d0338 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ContainerUtil.java @@ -1,110 +1,110 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.concurrent.ExecutorServiceFactory;
-import org.eclipse.net4j.util.concurrent.TimerLifecycle;
-import org.eclipse.net4j.util.event.EventUtil;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.security.FileUserManagerFactory;
-import org.eclipse.net4j.util.security.RandomizerFactory;
-
-/**
- * Various static helper methods for dealing with {@link IContainer containers}.
- *
- * @author Eike Stepper
- */
-public final class ContainerUtil
-{
- private static final Object[] NO_ELEMENTS = {};
-
- private static final IContainer<Object> EMPTY = new IContainer<Object>()
- {
- public Object[] getElements()
- {
- return NO_ELEMENTS;
- }
-
- public boolean isEmpty()
- {
- return true;
- }
-
- public void addListener(IListener listener)
- {
- }
-
- public void removeListener(IListener listener)
- {
- }
-
- public IListener[] getListeners()
- {
- return EventUtil.NO_LISTENERS;
- }
-
- public boolean hasListeners()
- {
- return false;
- }
-
- @Override
- public String toString()
- {
- return "EMPTY_CONTAINER"; //$NON-NLS-1$
- }
- };
-
- private ContainerUtil()
- {
- }
-
- /**
- * @since 2.0
- */
- public static void prepareContainer(IManagedContainer container)
- {
- container.registerFactory(new TimerLifecycle.DaemonFactory());
- container.registerFactory(new ExecutorServiceFactory());
- container.registerFactory(new RandomizerFactory());
- container.registerFactory(new FileUserManagerFactory());
- }
-
- public static IContainer<Object> emptyContainer()
- {
- return EMPTY;
- }
-
- public static IManagedContainer createContainer()
- {
- return new ManagedContainer();
- }
-
- public static boolean isEmpty(Object container)
- {
- if (container instanceof IContainer<?>)
- {
- return ((IContainer<?>)container).isEmpty();
- }
-
- return true;
- }
-
- public static Object[] getElements(Object container)
- {
- if (container instanceof IContainer<?>)
- {
- return ((IContainer<?>)container).getElements();
- }
-
- return NO_ELEMENTS;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.concurrent.ExecutorServiceFactory; +import org.eclipse.net4j.util.concurrent.TimerLifecycle; +import org.eclipse.net4j.util.event.EventUtil; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.security.FileUserManagerFactory; +import org.eclipse.net4j.util.security.RandomizerFactory; + +/** + * Various static helper methods for dealing with {@link IContainer containers}. + * + * @author Eike Stepper + */ +public final class ContainerUtil +{ + private static final Object[] NO_ELEMENTS = {}; + + private static final IContainer<Object> EMPTY = new IContainer<Object>() + { + public Object[] getElements() + { + return NO_ELEMENTS; + } + + public boolean isEmpty() + { + return true; + } + + public void addListener(IListener listener) + { + } + + public void removeListener(IListener listener) + { + } + + public IListener[] getListeners() + { + return EventUtil.NO_LISTENERS; + } + + public boolean hasListeners() + { + return false; + } + + @Override + public String toString() + { + return "EMPTY_CONTAINER"; //$NON-NLS-1$ + } + }; + + private ContainerUtil() + { + } + + /** + * @since 2.0 + */ + public static void prepareContainer(IManagedContainer container) + { + container.registerFactory(new TimerLifecycle.DaemonFactory()); + container.registerFactory(new ExecutorServiceFactory()); + container.registerFactory(new RandomizerFactory()); + container.registerFactory(new FileUserManagerFactory()); + } + + public static IContainer<Object> emptyContainer() + { + return EMPTY; + } + + public static IManagedContainer createContainer() + { + return new ManagedContainer(); + } + + public static boolean isEmpty(Object container) + { + if (container instanceof IContainer<?>) + { + return ((IContainer<?>)container).isEmpty(); + } + + return true; + } + + public static Object[] getElements(Object container) + { + if (container instanceof IContainer<?>) + { + return ((IContainer<?>)container).getElements(); + } + + return NO_ELEMENTS; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java index 91c25abcae..215c700c05 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/FactoryNotFoundException.java @@ -1,46 +1,46 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.factory.IFactory;
-import org.eclipse.net4j.util.factory.IFactoryKey;
-
-/**
- * An unchecked exception that indicates the absence of a {@link IFactory factory} identified by
- * {@link IFactoryKey#getProductGroup() product group} and {@link IFactoryKey#getType() type}.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class FactoryNotFoundException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public FactoryNotFoundException()
- {
- }
-
- public FactoryNotFoundException(String message)
- {
- super(message);
- }
-
- public FactoryNotFoundException(Throwable cause)
- {
- super(cause);
- }
-
- public FactoryNotFoundException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.factory.IFactory; +import org.eclipse.net4j.util.factory.IFactoryKey; + +/** + * An unchecked exception that indicates the absence of a {@link IFactory factory} identified by + * {@link IFactoryKey#getProductGroup() product group} and {@link IFactoryKey#getType() type}. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class FactoryNotFoundException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public FactoryNotFoundException() + { + } + + public FactoryNotFoundException(String message) + { + super(message); + } + + public FactoryNotFoundException(Throwable cause) + { + super(cause); + } + + public FactoryNotFoundException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java index 7120e43325..81f0ff0072 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerDelta.java @@ -1,34 +1,34 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-/**
- * Describes the addition or removal of a single element from a {@link IContainer container}.
- *
- * @author Eike Stepper
- */
-public interface IContainerDelta<E>
-{
- public E getElement();
-
- public Kind getKind();
-
- /**
- * Enumerates the possible {@link IContainerDelta container delta} kinds {@link #ADDED} or {@link #REMOVED}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
- public enum Kind
- {
- ADDED, REMOVED
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +/** + * Describes the addition or removal of a single element from a {@link IContainer container}. + * + * @author Eike Stepper + */ +public interface IContainerDelta<E> +{ + public E getElement(); + + public Kind getKind(); + + /** + * Enumerates the possible {@link IContainerDelta container delta} kinds {@link #ADDED} or {@link #REMOVED}. + * + * @author Eike Stepper + * @apiviz.exclude + */ + public enum Kind + { + ADDED, REMOVED + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java index c0dec36d55..81c10d8e2c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEvent.java @@ -1,42 +1,42 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.container.IContainerDelta.Kind;
-import org.eclipse.net4j.util.event.IEvent;
-
-/**
- * An {@link IEvent event} fired from a {@link IContainer container} when its elements have changed.
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- * @apiviz.composedOf {@link IContainerDelta} - - deltas
- */
-public interface IContainerEvent<E> extends IEvent
-{
- /**
- * @since 3.0
- */
- public IContainer<E> getSource();
-
- public boolean isEmpty();
-
- public IContainerDelta<E>[] getDeltas();
-
- public IContainerDelta<E> getDelta() throws IllegalStateException;
-
- public E getDeltaElement() throws IllegalStateException;
-
- public Kind getDeltaKind() throws IllegalStateException;
-
- public void accept(IContainerEventVisitor<E> visitor);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.container.IContainerDelta.Kind; +import org.eclipse.net4j.util.event.IEvent; + +/** + * An {@link IEvent event} fired from a {@link IContainer container} when its elements have changed. + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + * @apiviz.composedOf {@link IContainerDelta} - - deltas + */ +public interface IContainerEvent<E> extends IEvent +{ + /** + * @since 3.0 + */ + public IContainer<E> getSource(); + + public boolean isEmpty(); + + public IContainerDelta<E>[] getDeltas(); + + public IContainerDelta<E> getDelta() throws IllegalStateException; + + public E getDeltaElement() throws IllegalStateException; + + public Kind getDeltaKind() throws IllegalStateException; + + public void accept(IContainerEventVisitor<E> visitor); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java index 26f86cf06b..7cc3a4b8cf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IContainerEventVisitor.java @@ -1,38 +1,38 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-/**
- * A callback interface for visiting {@link IContainerDelta container deltas}.
- *
- * @see IContainerEvent#accept(IContainerEventVisitor)
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public interface IContainerEventVisitor<E>
-{
- public void added(E element);
-
- public void removed(E element);
-
- /**
- * An extension interface for {@link IContainerEventVisitor container event visitors} that can {@link #filter(Object)
- * filter} deltas from being visited.
- *
- * @see IContainerEvent#accept(IContainerEventVisitor)
- * @author Eike Stepper
- * @apiviz.exclude
- */
- public interface Filtered<E> extends IContainerEventVisitor<E>
- {
- public boolean filter(E element);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +/** + * A callback interface for visiting {@link IContainerDelta container deltas}. + * + * @see IContainerEvent#accept(IContainerEventVisitor) + * @author Eike Stepper + * @apiviz.exclude + */ +public interface IContainerEventVisitor<E> +{ + public void added(E element); + + public void removed(E element); + + /** + * An extension interface for {@link IContainerEventVisitor container event visitors} that can {@link #filter(Object) + * filter} deltas from being visited. + * + * @see IContainerEvent#accept(IContainerEventVisitor) + * @author Eike Stepper + * @apiviz.exclude + */ + public interface Filtered<E> extends IContainerEventVisitor<E> + { + public boolean filter(E element); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java index 4976b989f7..93b40f3762 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IElementProcessor.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-/**
- * Processes elements of a {@link IManagedContainer managed container} when they're added to the container.
- *
- * @author Eike Stepper
- */
-public interface IElementProcessor
-{
- public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
- Object element);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +/** + * Processes elements of a {@link IManagedContainer managed container} when they're added to the container. + * + * @author Eike Stepper + */ +public interface IElementProcessor +{ + public Object process(IManagedContainer container, String productGroup, String factoryType, String description, + Object element); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java index 8e6664cf99..87f80e0313 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IManagedContainer.java @@ -1,80 +1,80 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.factory.IFactory;
-import org.eclipse.net4j.util.factory.IFactoryKey;
-import org.eclipse.net4j.util.factory.ProductCreationException;
-import org.eclipse.net4j.util.lifecycle.ILifecycle;
-import org.eclipse.net4j.util.registry.IRegistry;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-import java.util.Set;
-
-/**
- * A {@link IContainer container} that populates itself by means of element {@link #getFactoryRegistry() factories} and
- * {@link #getPostProcessors() post processors} .
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- * @apiviz.landmark
- * @apiviz.composedOf {@link org.eclipse.net4j.util.factory.IFactory} - - factoryRegistry
- * @apiviz.composedOf {@link org.eclipse.net4j.util.container.IElementProcessor} - - postProcessors
- */
-public interface IManagedContainer extends IContainer<Object>, ILifecycle
-{
- public IRegistry<IFactoryKey, IFactory> getFactoryRegistry();
-
- public IManagedContainer registerFactory(IFactory factory);
-
- public List<IElementProcessor> getPostProcessors();
-
- public void addPostProcessor(IElementProcessor postProcessor, boolean processExistingElements);
-
- public void addPostProcessor(IElementProcessor postProcessor);
-
- public void removePostProcessor(IElementProcessor postProcessor);
-
- public Set<String> getProductGroups();
-
- public Set<String> getFactoryTypes(String productGroup);
-
- public IFactory getFactory(String productGroup, String factoryType) throws FactoryNotFoundException;
-
- public Object putElement(String productGroup, String factoryType, String description, Object element);
-
- public String[] getElementKey(Object element);
-
- public Object[] getElements(String productGroup);
-
- public Object[] getElements(String productGroup, String factoryType);
-
- public Object getElement(String productGroup, String factoryType, String description)
- throws FactoryNotFoundException, ProductCreationException;
-
- /**
- * @since 2.0
- */
- public Object getElement(String productGroup, String factoryType, String description, boolean activate)
- throws FactoryNotFoundException, ProductCreationException;
-
- public Object removeElement(String productGroup, String factoryType, String description);
-
- public void clearElements();
-
- public void loadElements(InputStream stream) throws IOException, FactoryNotFoundException, ProductCreationException;
-
- public void saveElements(OutputStream stream) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.factory.IFactory; +import org.eclipse.net4j.util.factory.IFactoryKey; +import org.eclipse.net4j.util.factory.ProductCreationException; +import org.eclipse.net4j.util.lifecycle.ILifecycle; +import org.eclipse.net4j.util.registry.IRegistry; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Set; + +/** + * A {@link IContainer container} that populates itself by means of element {@link #getFactoryRegistry() factories} and + * {@link #getPostProcessors() post processors} . + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + * @apiviz.landmark + * @apiviz.composedOf {@link org.eclipse.net4j.util.factory.IFactory} - - factoryRegistry + * @apiviz.composedOf {@link org.eclipse.net4j.util.container.IElementProcessor} - - postProcessors + */ +public interface IManagedContainer extends IContainer<Object>, ILifecycle +{ + public IRegistry<IFactoryKey, IFactory> getFactoryRegistry(); + + public IManagedContainer registerFactory(IFactory factory); + + public List<IElementProcessor> getPostProcessors(); + + public void addPostProcessor(IElementProcessor postProcessor, boolean processExistingElements); + + public void addPostProcessor(IElementProcessor postProcessor); + + public void removePostProcessor(IElementProcessor postProcessor); + + public Set<String> getProductGroups(); + + public Set<String> getFactoryTypes(String productGroup); + + public IFactory getFactory(String productGroup, String factoryType) throws FactoryNotFoundException; + + public Object putElement(String productGroup, String factoryType, String description, Object element); + + public String[] getElementKey(Object element); + + public Object[] getElements(String productGroup); + + public Object[] getElements(String productGroup, String factoryType); + + public Object getElement(String productGroup, String factoryType, String description) + throws FactoryNotFoundException, ProductCreationException; + + /** + * @since 2.0 + */ + public Object getElement(String productGroup, String factoryType, String description, boolean activate) + throws FactoryNotFoundException, ProductCreationException; + + public Object removeElement(String productGroup, String factoryType, String description); + + public void clearElements(); + + public void loadElements(InputStream stream) throws IOException, FactoryNotFoundException, ProductCreationException; + + public void saveElements(OutputStream stream) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java index f62b62b39c..0b9e3cdf60 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/IPluginContainer.java @@ -1,28 +1,28 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.internal.util.container.PluginContainer;
-
-import org.eclipse.core.runtime.IExtensionRegistry;
-
-/**
- * A {@link IManagedContainer managed container} that is configured by the {@link IExtensionRegistry extension registry}
- * .
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface IPluginContainer extends IManagedContainer
-{
- public static final IPluginContainer INSTANCE = PluginContainer.getInstance();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.internal.util.container.PluginContainer; + +import org.eclipse.core.runtime.IExtensionRegistry; + +/** + * A {@link IManagedContainer managed container} that is configured by the {@link IExtensionRegistry extension registry} + * . + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface IPluginContainer extends IManagedContainer +{ + public static final IPluginContainer INSTANCE = PluginContainer.getInstance(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java index e71b7712e5..072b93ee57 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/ISlow.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-/**
- * A marker interface to indicate that some method calls may be slow.
- *
- * @author Eike Stepper
- * @since 3.1
- * @apiviz.exclude
- */
-public interface ISlow
-{
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +/** + * A marker interface to indicate that some method calls may be slow. + * + * @author Eike Stepper + * @since 3.1 + * @apiviz.exclude + */ +public interface ISlow +{ +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java index f0ad96466d..cafb5aee7f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/LifecycleEventConverter.java @@ -1,88 +1,88 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.event.IEvent;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.event.INotifier;
-import org.eclipse.net4j.util.event.Notifier;
-import org.eclipse.net4j.util.lifecycle.ILifecycleEvent;
-
-/**
- * A delegating {@link IListener listener} that converts {@link ILifecycleEvent lifecycle events} into
- * {@link IContainerEvent container events}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class LifecycleEventConverter<E> implements IListener
-{
- private Notifier owner;
-
- public LifecycleEventConverter(Notifier owner)
- {
- this.owner = owner;
- }
-
- public INotifier getOwner()
- {
- return owner;
- }
-
- public void notifyEvent(IEvent event)
- {
- if (event instanceof ILifecycleEvent)
- {
- ILifecycleEvent e = (ILifecycleEvent)event;
- switch (e.getKind())
- {
- case ACTIVATED:
- added(e);
- break;
-
- case DEACTIVATED:
- removed(e);
- break;
- }
- }
- }
-
- protected void added(ILifecycleEvent e)
- {
- fireContainerEvent(e, IContainerDelta.Kind.ADDED);
- }
-
- protected void removed(ILifecycleEvent e)
- {
- fireContainerEvent(e, IContainerDelta.Kind.REMOVED);
- }
-
- @SuppressWarnings("unchecked")
- protected void fireContainerEvent(ILifecycleEvent e, IContainerDelta.Kind kind)
- {
- E element = (E)e.getSource();
- if (element != null)
- {
- IListener[] listeners = owner.getListeners();
- if (listeners != null)
- {
- owner.fireEvent(createContainerEvent((IContainer<E>)owner, element, kind), listeners);
- }
- }
- }
-
- protected IContainerEvent<E> createContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind)
- {
- ContainerEvent<E> event = new ContainerEvent<E>(container);
- event.addDelta(new ContainerDelta<E>(element, kind));
- return event;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.event.IEvent; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.event.INotifier; +import org.eclipse.net4j.util.event.Notifier; +import org.eclipse.net4j.util.lifecycle.ILifecycleEvent; + +/** + * A delegating {@link IListener listener} that converts {@link ILifecycleEvent lifecycle events} into + * {@link IContainerEvent container events}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class LifecycleEventConverter<E> implements IListener +{ + private Notifier owner; + + public LifecycleEventConverter(Notifier owner) + { + this.owner = owner; + } + + public INotifier getOwner() + { + return owner; + } + + public void notifyEvent(IEvent event) + { + if (event instanceof ILifecycleEvent) + { + ILifecycleEvent e = (ILifecycleEvent)event; + switch (e.getKind()) + { + case ACTIVATED: + added(e); + break; + + case DEACTIVATED: + removed(e); + break; + } + } + } + + protected void added(ILifecycleEvent e) + { + fireContainerEvent(e, IContainerDelta.Kind.ADDED); + } + + protected void removed(ILifecycleEvent e) + { + fireContainerEvent(e, IContainerDelta.Kind.REMOVED); + } + + @SuppressWarnings("unchecked") + protected void fireContainerEvent(ILifecycleEvent e, IContainerDelta.Kind kind) + { + E element = (E)e.getSource(); + if (element != null) + { + IListener[] listeners = owner.getListeners(); + if (listeners != null) + { + owner.fireEvent(createContainerEvent((IContainer<E>)owner, element, kind), listeners); + } + } + } + + protected IContainerEvent<E> createContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind) + { + ContainerEvent<E> event = new ContainerEvent<E>(container); + event.addDelta(new ContainerDelta<E>(element, kind)); + return event; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java index 527795b63c..1190824372 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/SingleDeltaContainerEvent.java @@ -1,102 +1,102 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container;
-
-import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered;
-import org.eclipse.net4j.util.event.Event;
-
-import java.text.MessageFormat;
-
-/**
- * A {@link IContainerEvent container event} with a single element {@link IContainerDelta delta}.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class SingleDeltaContainerEvent<E> extends Event implements IContainerEvent<E>
-{
- private static final long serialVersionUID = 1L;
-
- private IContainerDelta<E>[] deltas;
-
- @SuppressWarnings("unchecked")
- public SingleDeltaContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind)
- {
- super(container);
- deltas = new IContainerDelta[] { new ContainerDelta<E>(element, kind) };
- }
-
- /**
- * @since 3.0
- */
- @Override
- @SuppressWarnings("unchecked")
- public IContainer<E> getSource()
- {
- return (IContainer<E>)super.getSource();
- }
-
- public boolean isEmpty()
- {
- return false;
- }
-
- public IContainerDelta<E>[] getDeltas()
- {
- return deltas;
- }
-
- public IContainerDelta<E> getDelta() throws IllegalStateException
- {
- return deltas[0];
- }
-
- public E getDeltaElement() throws IllegalStateException
- {
- return deltas[0].getElement();
- }
-
- public IContainerDelta.Kind getDeltaKind() throws IllegalStateException
- {
- return deltas[0].getKind();
- }
-
- public void accept(IContainerEventVisitor<E> visitor)
- {
- E element = deltas[0].getElement();
-
- boolean filtered = true;
- if (visitor instanceof Filtered<?>)
- {
- filtered = ((Filtered<E>)visitor).filter(element);
- }
-
- if (filtered)
- {
- switch (deltas[0].getKind())
- {
- case ADDED:
- visitor.added(element);
- break;
- case REMOVED:
- visitor.removed(element);
- break;
- }
- }
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("ContainerEvent[source={0}, {1}={2}]", getSource(), getDeltaElement(), getDeltaKind()); //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container; + +import org.eclipse.net4j.util.container.IContainerEventVisitor.Filtered; +import org.eclipse.net4j.util.event.Event; + +import java.text.MessageFormat; + +/** + * A {@link IContainerEvent container event} with a single element {@link IContainerDelta delta}. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class SingleDeltaContainerEvent<E> extends Event implements IContainerEvent<E> +{ + private static final long serialVersionUID = 1L; + + private IContainerDelta<E>[] deltas; + + @SuppressWarnings("unchecked") + public SingleDeltaContainerEvent(IContainer<E> container, E element, IContainerDelta.Kind kind) + { + super(container); + deltas = new IContainerDelta[] { new ContainerDelta<E>(element, kind) }; + } + + /** + * @since 3.0 + */ + @Override + @SuppressWarnings("unchecked") + public IContainer<E> getSource() + { + return (IContainer<E>)super.getSource(); + } + + public boolean isEmpty() + { + return false; + } + + public IContainerDelta<E>[] getDeltas() + { + return deltas; + } + + public IContainerDelta<E> getDelta() throws IllegalStateException + { + return deltas[0]; + } + + public E getDeltaElement() throws IllegalStateException + { + return deltas[0].getElement(); + } + + public IContainerDelta.Kind getDeltaKind() throws IllegalStateException + { + return deltas[0].getKind(); + } + + public void accept(IContainerEventVisitor<E> visitor) + { + E element = deltas[0].getElement(); + + boolean filtered = true; + if (visitor instanceof Filtered<?>) + { + filtered = ((Filtered<E>)visitor).filter(element); + } + + if (filtered) + { + switch (deltas[0].getKind()) + { + case ADDED: + visitor.added(element); + break; + case REMOVED: + visitor.removed(element); + break; + } + } + } + + @Override + public String toString() + { + return MessageFormat.format("ContainerEvent[source={0}, {1}={2}]", getSource(), getDeltaElement(), getDeltaKind()); //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java index 957c7f62a5..3daa932751 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/AbstractDelegator.java @@ -1,131 +1,131 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.ContainerEvent;
-import org.eclipse.net4j.util.container.IContainer;
-import org.eclipse.net4j.util.container.IContainerDelta;
-import org.eclipse.net4j.util.container.IContainerDelta.Kind;
-import org.eclipse.net4j.util.container.SingleDeltaContainerEvent;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.event.Notifier;
-
-import java.util.Collection;
-import java.util.Iterator;
-
-/**
- * A delegating base class for {@link IContainer containers}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public abstract class AbstractDelegator<E> extends Notifier implements IContainer<E>
-{
- public AbstractDelegator()
- {
- }
-
- protected void fireAddedEvent(E o)
- {
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(new SingleDeltaContainerEvent<E>(this, o, IContainerDelta.Kind.ADDED), listeners);
- }
- }
-
- @SuppressWarnings("unchecked")
- protected void fireRemovedEvent(Object o)
- {
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(new SingleDeltaContainerEvent<E>(this, (E)o, IContainerDelta.Kind.REMOVED), listeners);
- }
- }
-
- @SuppressWarnings("unchecked")
- protected ContainerEvent<E> createEvent(Collection<? super E> c, Kind kind)
- {
- ContainerEvent<E> event = new ContainerEvent<E>(this);
- for (Object o : c)
- {
- event.addDelta((E)o, kind);
- }
-
- return event;
- }
-
- protected boolean dispatchEvent(ContainerEvent<E> event)
- {
- if (event.isEmpty())
- {
- return false;
- }
-
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
-
- return true;
- }
-
- /**
- * A delegating {@link Iterator iterator}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
- public class DelegatingIterator implements Iterator<E>
- {
- private Iterator<E> delegate;
-
- protected E last;
-
- public DelegatingIterator(Iterator<E> delegate)
- {
- this.delegate = delegate;
- }
-
- public Iterator<E> getDelegate()
- {
- return delegate;
- }
-
- /**
- * @category READ
- */
- public boolean hasNext()
- {
- return getDelegate().hasNext();
- }
-
- /**
- * @category READ
- */
- public E next()
- {
- return last = getDelegate().next();
- }
-
- /**
- * @category WRITE
- */
- public void remove()
- {
- getDelegate().remove();
- fireRemovedEvent(last);
- last = null;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.ContainerEvent; +import org.eclipse.net4j.util.container.IContainer; +import org.eclipse.net4j.util.container.IContainerDelta; +import org.eclipse.net4j.util.container.IContainerDelta.Kind; +import org.eclipse.net4j.util.container.SingleDeltaContainerEvent; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.event.Notifier; + +import java.util.Collection; +import java.util.Iterator; + +/** + * A delegating base class for {@link IContainer containers}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public abstract class AbstractDelegator<E> extends Notifier implements IContainer<E> +{ + public AbstractDelegator() + { + } + + protected void fireAddedEvent(E o) + { + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new SingleDeltaContainerEvent<E>(this, o, IContainerDelta.Kind.ADDED), listeners); + } + } + + @SuppressWarnings("unchecked") + protected void fireRemovedEvent(Object o) + { + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new SingleDeltaContainerEvent<E>(this, (E)o, IContainerDelta.Kind.REMOVED), listeners); + } + } + + @SuppressWarnings("unchecked") + protected ContainerEvent<E> createEvent(Collection<? super E> c, Kind kind) + { + ContainerEvent<E> event = new ContainerEvent<E>(this); + for (Object o : c) + { + event.addDelta((E)o, kind); + } + + return event; + } + + protected boolean dispatchEvent(ContainerEvent<E> event) + { + if (event.isEmpty()) + { + return false; + } + + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + + return true; + } + + /** + * A delegating {@link Iterator iterator}. + * + * @author Eike Stepper + * @apiviz.exclude + */ + public class DelegatingIterator implements Iterator<E> + { + private Iterator<E> delegate; + + protected E last; + + public DelegatingIterator(Iterator<E> delegate) + { + this.delegate = delegate; + } + + public Iterator<E> getDelegate() + { + return delegate; + } + + /** + * @category READ + */ + public boolean hasNext() + { + return getDelegate().hasNext(); + } + + /** + * @category READ + */ + public E next() + { + return last = getDelegate().next(); + } + + /** + * @category WRITE + */ + public void remove() + { + getDelegate().remove(); + fireRemovedEvent(last); + last = null; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java index dc97e2795c..4368a46313 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerBlockingQueue.java @@ -1,125 +1,125 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.ContainerEvent;
-import org.eclipse.net4j.util.container.IContainerDelta;
-import org.eclipse.net4j.util.event.IListener;
-
-import java.util.Collection;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.TimeUnit;
-
-/**
- * A default implementation of a {@link IContainerBlockingQueue container blocking queue}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerBlockingQueue<E> extends ContainerQueue<E> implements IContainerBlockingQueue<E>
-{
- public ContainerBlockingQueue(BlockingQueue<E> delegate)
- {
- super(delegate);
- }
-
- @Override
- public BlockingQueue<E> getDelegate()
- {
- return (BlockingQueue<E>)super.getDelegate();
- }
-
- /**
- * @category WRITE
- */
- public int drainTo(Collection<? super E> c)
- {
- int drainTo = getDelegate().drainTo(c);
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(createEvent(c, IContainerDelta.Kind.REMOVED), listeners);
- }
-
- return drainTo;
- }
-
- /**
- * @category WRITE
- */
- public int drainTo(Collection<? super E> c, int maxElements)
- {
- int drainTo = getDelegate().drainTo(c, maxElements);
- ContainerEvent<E> event = createEvent(c, IContainerDelta.Kind.REMOVED);
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
-
- return drainTo;
- }
-
- /**
- * @category WRITE
- */
- public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException
- {
- boolean modified = getDelegate().offer(o, timeout, unit);
- if (modified)
- {
- fireAddedEvent(o);
- }
-
- return modified;
- }
-
- /**
- * @category WRITE
- */
- public E poll(long timeout, TimeUnit unit) throws InterruptedException
- {
- E removed = getDelegate().poll(timeout, unit);
- if (removed != null)
- {
- fireRemovedEvent(removed);
- }
-
- return removed;
- }
-
- /**
- * @category WRITE
- */
- public void put(E o) throws InterruptedException
- {
- getDelegate().put(o);
- fireAddedEvent(o);
- }
-
- /**
- * @category READ
- */
- public int remainingCapacity()
- {
- return getDelegate().remainingCapacity();
- }
-
- /**
- * @category WRITE
- */
- public E take() throws InterruptedException
- {
- E element = getDelegate().take();
- fireRemovedEvent(element);
- return element;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.ContainerEvent; +import org.eclipse.net4j.util.container.IContainerDelta; +import org.eclipse.net4j.util.event.IListener; + +import java.util.Collection; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * A default implementation of a {@link IContainerBlockingQueue container blocking queue}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerBlockingQueue<E> extends ContainerQueue<E> implements IContainerBlockingQueue<E> +{ + public ContainerBlockingQueue(BlockingQueue<E> delegate) + { + super(delegate); + } + + @Override + public BlockingQueue<E> getDelegate() + { + return (BlockingQueue<E>)super.getDelegate(); + } + + /** + * @category WRITE + */ + public int drainTo(Collection<? super E> c) + { + int drainTo = getDelegate().drainTo(c); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(createEvent(c, IContainerDelta.Kind.REMOVED), listeners); + } + + return drainTo; + } + + /** + * @category WRITE + */ + public int drainTo(Collection<? super E> c, int maxElements) + { + int drainTo = getDelegate().drainTo(c, maxElements); + ContainerEvent<E> event = createEvent(c, IContainerDelta.Kind.REMOVED); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + + return drainTo; + } + + /** + * @category WRITE + */ + public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException + { + boolean modified = getDelegate().offer(o, timeout, unit); + if (modified) + { + fireAddedEvent(o); + } + + return modified; + } + + /** + * @category WRITE + */ + public E poll(long timeout, TimeUnit unit) throws InterruptedException + { + E removed = getDelegate().poll(timeout, unit); + if (removed != null) + { + fireRemovedEvent(removed); + } + + return removed; + } + + /** + * @category WRITE + */ + public void put(E o) throws InterruptedException + { + getDelegate().put(o); + fireAddedEvent(o); + } + + /** + * @category READ + */ + public int remainingCapacity() + { + return getDelegate().remainingCapacity(); + } + + /** + * @category WRITE + */ + public E take() throws InterruptedException + { + E element = getDelegate().take(); + fireRemovedEvent(element); + return element; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java index 4bc68a58ba..d88ddfa683 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerCollection.java @@ -1,220 +1,220 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.ContainerEvent;
-import org.eclipse.net4j.util.container.IContainerDelta;
-import org.eclipse.net4j.util.event.IListener;
-
-import java.util.Collection;
-import java.util.Iterator;
-
-/**
- * A default implementation of a {@link IContainerCollection container collection}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerCollection<E> extends AbstractDelegator<E> implements IContainerCollection<E>
-{
- private Collection<E> delegate;
-
- public ContainerCollection(Collection<E> delegate)
- {
- this.delegate = delegate;
- }
-
- public Collection<E> getDelegate()
- {
- return delegate;
- }
-
- @SuppressWarnings("unchecked")
- public E[] getElements()
- {
- return (E[])toArray();
- }
-
- /**
- * @category WRITE
- */
- public boolean add(E o)
- {
- boolean modified = getDelegate().add(o);
- if (modified)
- {
- fireAddedEvent(o);
- }
-
- return modified;
- }
-
- /**
- * @category WRITE
- */
- public boolean addAll(Collection<? extends E> c)
- {
- ContainerEvent<E> event = new ContainerEvent<E>(this);
- for (E e : c)
- {
- boolean modified = getDelegate().add(e);
- if (modified)
- {
- event.addDelta(e, IContainerDelta.Kind.ADDED);
- }
- }
-
- return dispatchEvent(event);
- }
-
- /**
- * @category WRITE
- */
- public void clear()
- {
- if (!isEmpty())
- {
- ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.REMOVED);
- getDelegate().clear();
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
- }
- }
-
- /**
- * @category WRITE
- */
- public boolean remove(Object o)
- {
- boolean modified = getDelegate().remove(o);
- if (modified)
- {
- fireRemovedEvent(o);
- }
-
- return modified;
- }
-
- /**
- * @category WRITE
- */
- @SuppressWarnings("unchecked")
- public boolean removeAll(Collection<?> c)
- {
- ContainerEvent<E> event = new ContainerEvent<E>(this);
- for (Object o : c)
- {
- boolean modified = getDelegate().remove(o);
- if (modified)
- {
- event.addDelta((E)o, IContainerDelta.Kind.REMOVED);
- }
- }
-
- return dispatchEvent(event);
- }
-
- /**
- * @category WRITE
- */
- @SuppressWarnings("unchecked")
- public boolean retainAll(Collection<?> c)
- {
- ContainerEvent<E> event = new ContainerEvent<E>(this);
- for (Object o : getDelegate())
- {
- if (!c.contains(o))
- {
- getDelegate().remove(o);
- event.addDelta((E)o, IContainerDelta.Kind.REMOVED);
- }
- }
-
- return dispatchEvent(event);
- }
-
- /**
- * @category READ
- */
- public boolean contains(Object o)
- {
- return getDelegate().contains(o);
- }
-
- /**
- * @category READ
- */
- public boolean containsAll(Collection<?> c)
- {
- return getDelegate().containsAll(c);
- }
-
- /**
- * @category READ
- */
- @Override
- public boolean equals(Object o)
- {
- return getDelegate().equals(o);
- }
-
- /**
- * @category READ
- */
- @Override
- public int hashCode()
- {
- return getDelegate().hashCode();
- }
-
- /**
- * @category READ
- */
- public boolean isEmpty()
- {
- return getDelegate().isEmpty();
- }
-
- /**
- * @category READ
- */
- public Iterator<E> iterator()
- {
- return new DelegatingIterator(getDelegate().iterator());
- }
-
- /**
- * @category READ
- */
- public int size()
- {
- return getDelegate().size();
- }
-
- /**
- * @category READ
- */
- public Object[] toArray()
- {
- return getDelegate().toArray();
- }
-
- /**
- * @category READ
- */
- public <T> T[] toArray(T[] a)
- {
- return getDelegate().toArray(a);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.ContainerEvent; +import org.eclipse.net4j.util.container.IContainerDelta; +import org.eclipse.net4j.util.event.IListener; + +import java.util.Collection; +import java.util.Iterator; + +/** + * A default implementation of a {@link IContainerCollection container collection}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerCollection<E> extends AbstractDelegator<E> implements IContainerCollection<E> +{ + private Collection<E> delegate; + + public ContainerCollection(Collection<E> delegate) + { + this.delegate = delegate; + } + + public Collection<E> getDelegate() + { + return delegate; + } + + @SuppressWarnings("unchecked") + public E[] getElements() + { + return (E[])toArray(); + } + + /** + * @category WRITE + */ + public boolean add(E o) + { + boolean modified = getDelegate().add(o); + if (modified) + { + fireAddedEvent(o); + } + + return modified; + } + + /** + * @category WRITE + */ + public boolean addAll(Collection<? extends E> c) + { + ContainerEvent<E> event = new ContainerEvent<E>(this); + for (E e : c) + { + boolean modified = getDelegate().add(e); + if (modified) + { + event.addDelta(e, IContainerDelta.Kind.ADDED); + } + } + + return dispatchEvent(event); + } + + /** + * @category WRITE + */ + public void clear() + { + if (!isEmpty()) + { + ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.REMOVED); + getDelegate().clear(); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + } + } + + /** + * @category WRITE + */ + public boolean remove(Object o) + { + boolean modified = getDelegate().remove(o); + if (modified) + { + fireRemovedEvent(o); + } + + return modified; + } + + /** + * @category WRITE + */ + @SuppressWarnings("unchecked") + public boolean removeAll(Collection<?> c) + { + ContainerEvent<E> event = new ContainerEvent<E>(this); + for (Object o : c) + { + boolean modified = getDelegate().remove(o); + if (modified) + { + event.addDelta((E)o, IContainerDelta.Kind.REMOVED); + } + } + + return dispatchEvent(event); + } + + /** + * @category WRITE + */ + @SuppressWarnings("unchecked") + public boolean retainAll(Collection<?> c) + { + ContainerEvent<E> event = new ContainerEvent<E>(this); + for (Object o : getDelegate()) + { + if (!c.contains(o)) + { + getDelegate().remove(o); + event.addDelta((E)o, IContainerDelta.Kind.REMOVED); + } + } + + return dispatchEvent(event); + } + + /** + * @category READ + */ + public boolean contains(Object o) + { + return getDelegate().contains(o); + } + + /** + * @category READ + */ + public boolean containsAll(Collection<?> c) + { + return getDelegate().containsAll(c); + } + + /** + * @category READ + */ + @Override + public boolean equals(Object o) + { + return getDelegate().equals(o); + } + + /** + * @category READ + */ + @Override + public int hashCode() + { + return getDelegate().hashCode(); + } + + /** + * @category READ + */ + public boolean isEmpty() + { + return getDelegate().isEmpty(); + } + + /** + * @category READ + */ + public Iterator<E> iterator() + { + return new DelegatingIterator(getDelegate().iterator()); + } + + /** + * @category READ + */ + public int size() + { + return getDelegate().size(); + } + + /** + * @category READ + */ + public Object[] toArray() + { + return getDelegate().toArray(); + } + + /** + * @category READ + */ + public <T> T[] toArray(T[] a) + { + return getDelegate().toArray(a); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java index 5d22ec04c3..c9c9831fbc 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerList.java @@ -1,218 +1,218 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.ContainerEvent;
-import org.eclipse.net4j.util.container.IContainerDelta;
-import org.eclipse.net4j.util.event.IListener;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.ListIterator;
-
-/**
- * A default implementation of a {@link IContainerList container list}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerList<E> extends ContainerCollection<E> implements IContainerList<E>
-{
- public ContainerList(List<E> delegate)
- {
- super(delegate);
- }
-
- @Override
- public List<E> getDelegate()
- {
- return (List<E>)super.getDelegate();
- }
-
- /**
- * @category WRITE
- */
- public void add(int index, E element)
- {
- getDelegate().add(index, element);
- fireAddedEvent(element);
- }
-
- /**
- * @category WRITE
- */
- public boolean addAll(int index, Collection<? extends E> c)
- {
- ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.ADDED);
- getDelegate().addAll(index, c);
- return dispatchEvent(event);
- }
-
- /**
- * @category READ
- */
- public E get(int index)
- {
- return getDelegate().get(index);
- }
-
- /**
- * @category READ
- */
- public int indexOf(Object o)
- {
- return getDelegate().indexOf(o);
- }
-
- /**
- * @category READ
- */
- public int lastIndexOf(Object o)
- {
- return getDelegate().lastIndexOf(o);
- }
-
- /**
- * @category READ
- */
- public ListIterator<E> listIterator()
- {
- return new DelegatingListIterator(getDelegate().listIterator());
- }
-
- /**
- * @category READ
- */
- public ListIterator<E> listIterator(int index)
- {
- return new DelegatingListIterator(getDelegate().listIterator(index));
- }
-
- /**
- * @category WRITE
- */
- public E remove(int index)
- {
- E removed = getDelegate().remove(index);
- if (removed != null)
- {
- fireRemovedEvent(removed);
- }
-
- return removed;
- }
-
- /**
- * @category WRITE
- */
- public E set(int index, E element)
- {
- E removed = getDelegate().set(index, element);
- ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this);
- event.addDelta(removed, IContainerDelta.Kind.REMOVED);
- event.addDelta(element, IContainerDelta.Kind.ADDED);
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
-
- return removed;
- }
-
- /**
- * @category READ
- */
- public List<E> subList(int fromIndex, int toIndex)
- {
- return getDelegate().subList(fromIndex, toIndex);
- }
-
- /**
- * A delegating {@link ListIterator list iterator}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
- public class DelegatingListIterator extends DelegatingIterator implements ListIterator<E>
- {
- public DelegatingListIterator(ListIterator<E> delegate)
- {
- super(delegate);
- }
-
- @Override
- public ListIterator<E> getDelegate()
- {
- return (ListIterator<E>)super.getDelegate();
- }
-
- /**
- * @category WRITE
- */
- public void add(E o)
- {
- getDelegate().add(o);
- fireAddedEvent(o);
- last = o;
- }
-
- /**
- * @category WRITE
- */
- public void set(E o)
- {
- getDelegate().set(o);
- ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this);
- event.addDelta(last, IContainerDelta.Kind.REMOVED);
- event.addDelta(o, IContainerDelta.Kind.ADDED);
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
-
- last = o;
- }
-
- /**
- * @category READ
- */
- public boolean hasPrevious()
- {
- return getDelegate().hasPrevious();
- }
-
- /**
- * @category READ
- */
- public int nextIndex()
- {
- return getDelegate().nextIndex();
- }
-
- /**
- * @category READ
- */
- public E previous()
- {
- return getDelegate().previous();
- }
-
- /**
- * @category READ
- */
- public int previousIndex()
- {
- return getDelegate().previousIndex();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.ContainerEvent; +import org.eclipse.net4j.util.container.IContainerDelta; +import org.eclipse.net4j.util.event.IListener; + +import java.util.Collection; +import java.util.List; +import java.util.ListIterator; + +/** + * A default implementation of a {@link IContainerList container list}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerList<E> extends ContainerCollection<E> implements IContainerList<E> +{ + public ContainerList(List<E> delegate) + { + super(delegate); + } + + @Override + public List<E> getDelegate() + { + return (List<E>)super.getDelegate(); + } + + /** + * @category WRITE + */ + public void add(int index, E element) + { + getDelegate().add(index, element); + fireAddedEvent(element); + } + + /** + * @category WRITE + */ + public boolean addAll(int index, Collection<? extends E> c) + { + ContainerEvent<E> event = createEvent(getDelegate(), IContainerDelta.Kind.ADDED); + getDelegate().addAll(index, c); + return dispatchEvent(event); + } + + /** + * @category READ + */ + public E get(int index) + { + return getDelegate().get(index); + } + + /** + * @category READ + */ + public int indexOf(Object o) + { + return getDelegate().indexOf(o); + } + + /** + * @category READ + */ + public int lastIndexOf(Object o) + { + return getDelegate().lastIndexOf(o); + } + + /** + * @category READ + */ + public ListIterator<E> listIterator() + { + return new DelegatingListIterator(getDelegate().listIterator()); + } + + /** + * @category READ + */ + public ListIterator<E> listIterator(int index) + { + return new DelegatingListIterator(getDelegate().listIterator(index)); + } + + /** + * @category WRITE + */ + public E remove(int index) + { + E removed = getDelegate().remove(index); + if (removed != null) + { + fireRemovedEvent(removed); + } + + return removed; + } + + /** + * @category WRITE + */ + public E set(int index, E element) + { + E removed = getDelegate().set(index, element); + ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this); + event.addDelta(removed, IContainerDelta.Kind.REMOVED); + event.addDelta(element, IContainerDelta.Kind.ADDED); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + + return removed; + } + + /** + * @category READ + */ + public List<E> subList(int fromIndex, int toIndex) + { + return getDelegate().subList(fromIndex, toIndex); + } + + /** + * A delegating {@link ListIterator list iterator}. + * + * @author Eike Stepper + * @apiviz.exclude + */ + public class DelegatingListIterator extends DelegatingIterator implements ListIterator<E> + { + public DelegatingListIterator(ListIterator<E> delegate) + { + super(delegate); + } + + @Override + public ListIterator<E> getDelegate() + { + return (ListIterator<E>)super.getDelegate(); + } + + /** + * @category WRITE + */ + public void add(E o) + { + getDelegate().add(o); + fireAddedEvent(o); + last = o; + } + + /** + * @category WRITE + */ + public void set(E o) + { + getDelegate().set(o); + ContainerEvent<E> event = new ContainerEvent<E>(ContainerList.this); + event.addDelta(last, IContainerDelta.Kind.REMOVED); + event.addDelta(o, IContainerDelta.Kind.ADDED); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + + last = o; + } + + /** + * @category READ + */ + public boolean hasPrevious() + { + return getDelegate().hasPrevious(); + } + + /** + * @category READ + */ + public int nextIndex() + { + return getDelegate().nextIndex(); + } + + /** + * @category READ + */ + public E previous() + { + return getDelegate().previous(); + } + + /** + * @category READ + */ + public int previousIndex() + { + return getDelegate().previousIndex(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java index be111fc73f..a89d7e7a9e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerMap.java @@ -1,209 +1,209 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.collection.MapEntry;
-import org.eclipse.net4j.util.container.ContainerEvent;
-import org.eclipse.net4j.util.container.IContainerDelta;
-import org.eclipse.net4j.util.event.IListener;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A default implementation of a {@link IContainerMap container map}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerMap<K, V> extends AbstractDelegator<Map.Entry<K, V>> implements IContainerMap<K, V>
-{
- private Map<K, V> delegate;
-
- public ContainerMap(Map<K, V> delegate)
- {
- this.delegate = delegate;
- }
-
- public Map<K, V> getDelegate()
- {
- return delegate;
- }
-
- /**
- * @category WRITE
- */
- public void clear()
- {
- if (!isEmpty())
- {
- ContainerEvent<Map.Entry<K, V>> event = createEvent(getDelegate().entrySet(), IContainerDelta.Kind.REMOVED);
- getDelegate().clear();
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
- }
- }
-
- /**
- * @category WRITE
- */
- public V put(K key, V value)
- {
- ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this);
- V removed = getDelegate().put(key, value);
- if (removed != null)
- {
- event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED);
- }
-
- event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED);
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(event, listeners);
- }
-
- return removed;
- }
-
- /**
- * @category WRITE
- */
- public void putAll(Map<? extends K, ? extends V> t)
- {
- ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this);
- Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator();
- while (i.hasNext())
- {
- Entry<? extends K, ? extends V> entry = i.next();
- K key = entry.getKey();
- V value = entry.getValue();
- V removed = getDelegate().put(key, value);
- if (removed != null)
- {
- event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED);
- }
-
- event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED);
- }
-
- dispatchEvent(event);
- }
-
- /**
- * @category WRITE
- */
- public V remove(Object key)
- {
- V removed = getDelegate().remove(key);
- if (removed != null)
- {
- fireRemovedEvent(new ContainerMapEntry<Object, V>(key, removed));
- }
-
- return removed;
- }
-
- /**
- * @category READ
- */
- public boolean containsKey(Object key)
- {
- return getDelegate().containsKey(key);
- }
-
- /**
- * @category READ
- */
- public boolean containsValue(Object value)
- {
- return getDelegate().containsValue(value);
- }
-
- /**
- * @category READ
- */
- public V get(Object key)
- {
- return getDelegate().get(key);
- }
-
- /**
- * @category READ
- */
- public int size()
- {
- return getDelegate().size();
- }
-
- /**
- * @category READ
- */
- @SuppressWarnings("unchecked")
- public Map.Entry<K, V>[] getElements()
- {
- return (Entry<K, V>[])getDelegate().entrySet().toArray();
- }
-
- /**
- * @category READ
- */
- public boolean isEmpty()
- {
- return getDelegate().isEmpty();
- }
-
- /**
- * @category READ
- */
- public Set<Map.Entry<K, V>> entrySet()
- {
- return new ContainerSet<Map.Entry<K, V>>(getDelegate().entrySet());
- }
-
- /**
- * @category READ
- */
- public Set<K> keySet()
- {
- return new ContainerSet<K>(getDelegate().keySet());
- }
-
- /**
- * @category READ
- */
- public Collection<V> values()
- {
- return new ContainerCollection<V>(getDelegate().values());
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class ContainerMapEntry<K, V> extends MapEntry<K, V>
- {
- public ContainerMapEntry(K key, V value)
- {
- super(key, value);
- }
-
- @Override
- public V setValue(V value)
- {
- throw new UnsupportedOperationException();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.collection.MapEntry; +import org.eclipse.net4j.util.container.ContainerEvent; +import org.eclipse.net4j.util.container.IContainerDelta; +import org.eclipse.net4j.util.event.IListener; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * A default implementation of a {@link IContainerMap container map}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerMap<K, V> extends AbstractDelegator<Map.Entry<K, V>> implements IContainerMap<K, V> +{ + private Map<K, V> delegate; + + public ContainerMap(Map<K, V> delegate) + { + this.delegate = delegate; + } + + public Map<K, V> getDelegate() + { + return delegate; + } + + /** + * @category WRITE + */ + public void clear() + { + if (!isEmpty()) + { + ContainerEvent<Map.Entry<K, V>> event = createEvent(getDelegate().entrySet(), IContainerDelta.Kind.REMOVED); + getDelegate().clear(); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + } + } + + /** + * @category WRITE + */ + public V put(K key, V value) + { + ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this); + V removed = getDelegate().put(key, value); + if (removed != null) + { + event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED); + } + + event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(event, listeners); + } + + return removed; + } + + /** + * @category WRITE + */ + public void putAll(Map<? extends K, ? extends V> t) + { + ContainerEvent<Map.Entry<K, V>> event = new ContainerEvent<Map.Entry<K, V>>(this); + Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator(); + while (i.hasNext()) + { + Entry<? extends K, ? extends V> entry = i.next(); + K key = entry.getKey(); + V value = entry.getValue(); + V removed = getDelegate().put(key, value); + if (removed != null) + { + event.addDelta(new ContainerMapEntry<K, V>(key, removed), IContainerDelta.Kind.REMOVED); + } + + event.addDelta(new ContainerMapEntry<K, V>(key, value), IContainerDelta.Kind.ADDED); + } + + dispatchEvent(event); + } + + /** + * @category WRITE + */ + public V remove(Object key) + { + V removed = getDelegate().remove(key); + if (removed != null) + { + fireRemovedEvent(new ContainerMapEntry<Object, V>(key, removed)); + } + + return removed; + } + + /** + * @category READ + */ + public boolean containsKey(Object key) + { + return getDelegate().containsKey(key); + } + + /** + * @category READ + */ + public boolean containsValue(Object value) + { + return getDelegate().containsValue(value); + } + + /** + * @category READ + */ + public V get(Object key) + { + return getDelegate().get(key); + } + + /** + * @category READ + */ + public int size() + { + return getDelegate().size(); + } + + /** + * @category READ + */ + @SuppressWarnings("unchecked") + public Map.Entry<K, V>[] getElements() + { + return (Entry<K, V>[])getDelegate().entrySet().toArray(); + } + + /** + * @category READ + */ + public boolean isEmpty() + { + return getDelegate().isEmpty(); + } + + /** + * @category READ + */ + public Set<Map.Entry<K, V>> entrySet() + { + return new ContainerSet<Map.Entry<K, V>>(getDelegate().entrySet()); + } + + /** + * @category READ + */ + public Set<K> keySet() + { + return new ContainerSet<K>(getDelegate().keySet()); + } + + /** + * @category READ + */ + public Collection<V> values() + { + return new ContainerCollection<V>(getDelegate().values()); + } + + /** + * @author Eike Stepper + */ + private static final class ContainerMapEntry<K, V> extends MapEntry<K, V> + { + public ContainerMapEntry(K key, V value) + { + super(key, value); + } + + @Override + public V setValue(V value) + { + throw new UnsupportedOperationException(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java index 2a6a746730..b016cd8182 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerQueue.java @@ -1,91 +1,91 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import java.util.Queue;
-
-/**
- * A default implementation of a {@link IContainerQueue container queue}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerQueue<E> extends ContainerCollection<E> implements IContainerQueue<E>
-{
- public ContainerQueue(Queue<E> delegate)
- {
- super(delegate);
- }
-
- @Override
- public Queue<E> getDelegate()
- {
- return (Queue<E>)super.getDelegate();
- }
-
- /**
- * @category READ
- */
- public E element()
- {
- return getDelegate().element();
- }
-
- /**
- * @category WRITE
- */
- public boolean offer(E o)
- {
- boolean modified = getDelegate().offer(o);
- if (modified)
- {
- fireAddedEvent(o);
- }
-
- return modified;
- }
-
- /**
- * @category READ
- */
- public E peek()
- {
- return getDelegate().element();
- }
-
- /**
- * @category WRITE
- */
- public E poll()
- {
- E removed = getDelegate().poll();
- if (removed != null)
- {
- fireRemovedEvent(removed);
- }
-
- return removed;
- }
-
- /**
- * @category WRITE
- */
- public E remove()
- {
- E removed = getDelegate().remove();
- if (removed != null)
- {
- fireRemovedEvent(removed);
- }
-
- return removed;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import java.util.Queue; + +/** + * A default implementation of a {@link IContainerQueue container queue}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerQueue<E> extends ContainerCollection<E> implements IContainerQueue<E> +{ + public ContainerQueue(Queue<E> delegate) + { + super(delegate); + } + + @Override + public Queue<E> getDelegate() + { + return (Queue<E>)super.getDelegate(); + } + + /** + * @category READ + */ + public E element() + { + return getDelegate().element(); + } + + /** + * @category WRITE + */ + public boolean offer(E o) + { + boolean modified = getDelegate().offer(o); + if (modified) + { + fireAddedEvent(o); + } + + return modified; + } + + /** + * @category READ + */ + public E peek() + { + return getDelegate().element(); + } + + /** + * @category WRITE + */ + public E poll() + { + E removed = getDelegate().poll(); + if (removed != null) + { + fireRemovedEvent(removed); + } + + return removed; + } + + /** + * @category WRITE + */ + public E remove() + { + E removed = getDelegate().remove(); + if (removed != null) + { + fireRemovedEvent(removed); + } + + return removed; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java index 5b3bf8e7cb..e8cf372c80 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSet.java @@ -1,33 +1,33 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import java.util.Set;
-
-/**
- * A default implementation of a {@link IContainerSet container set}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerSet<E> extends ContainerCollection<E> implements IContainerSet<E>
-{
- public ContainerSet(Set<E> delegate)
- {
- super(delegate);
- }
-
- @Override
- public Set<E> getDelegate()
- {
- return (Set<E>)super.getDelegate();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import java.util.Set; + +/** + * A default implementation of a {@link IContainerSet container set}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerSet<E> extends ContainerCollection<E> implements IContainerSet<E> +{ + public ContainerSet(Set<E> delegate) + { + super(delegate); + } + + @Override + public Set<E> getDelegate() + { + return (Set<E>)super.getDelegate(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java index 4ffb4b891d..351162c38e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/ContainerSortedSet.java @@ -1,82 +1,82 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import java.util.Comparator;
-import java.util.SortedSet;
-
-/**
- * A default implementation of a {@link IContainerSortedSet container sorted set}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class ContainerSortedSet<E> extends ContainerSet<E> implements IContainerSortedSet<E>
-{
- public ContainerSortedSet(SortedSet<E> delegate)
- {
- super(delegate);
- }
-
- @Override
- public SortedSet<E> getDelegate()
- {
- return (SortedSet<E>)super.getDelegate();
- }
-
- /**
- * @category READ
- */
- public Comparator<? super E> comparator()
- {
- return getDelegate().comparator();
- }
-
- /**
- * @category READ
- */
- public E first()
- {
- return getDelegate().first();
- }
-
- /**
- * @category READ
- */
- public E last()
- {
- return getDelegate().last();
- }
-
- /**
- * @category READ
- */
- public SortedSet<E> headSet(E toElement)
- {
- return getDelegate().headSet(toElement);
- }
-
- /**
- * @category READ
- */
- public SortedSet<E> subSet(E fromElement, E toElement)
- {
- return getDelegate().subSet(fromElement, toElement);
- }
-
- /**
- * @category READ
- */
- public SortedSet<E> tailSet(E fromElement)
- {
- return getDelegate().tailSet(fromElement);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import java.util.Comparator; +import java.util.SortedSet; + +/** + * A default implementation of a {@link IContainerSortedSet container sorted set}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class ContainerSortedSet<E> extends ContainerSet<E> implements IContainerSortedSet<E> +{ + public ContainerSortedSet(SortedSet<E> delegate) + { + super(delegate); + } + + @Override + public SortedSet<E> getDelegate() + { + return (SortedSet<E>)super.getDelegate(); + } + + /** + * @category READ + */ + public Comparator<? super E> comparator() + { + return getDelegate().comparator(); + } + + /** + * @category READ + */ + public E first() + { + return getDelegate().first(); + } + + /** + * @category READ + */ + public E last() + { + return getDelegate().last(); + } + + /** + * @category READ + */ + public SortedSet<E> headSet(E toElement) + { + return getDelegate().headSet(toElement); + } + + /** + * @category READ + */ + public SortedSet<E> subSet(E fromElement, E toElement) + { + return getDelegate().subSet(fromElement, toElement); + } + + /** + * @category READ + */ + public SortedSet<E> tailSet(E fromElement) + { + return getDelegate().tailSet(fromElement); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java index 100d57b670..cbc68351bf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerCollection.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.IContainer;
-
-import java.util.Collection;
-
-/**
- * A {@link IContainer container} that is a {@link Collection}.
- *
- * @author Eike Stepper
- */
-public interface IContainerCollection<E> extends IContainer<E>, Collection<E>
-{
- public Collection<E> getDelegate();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.IContainer; + +import java.util.Collection; + +/** + * A {@link IContainer container} that is a {@link Collection}. + * + * @author Eike Stepper + */ +public interface IContainerCollection<E> extends IContainer<E>, Collection<E> +{ + public Collection<E> getDelegate(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java index 2bc34b3401..fce37a7a4a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerList.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.IContainer;
-
-import java.util.List;
-
-/**
- * A {@link IContainer container} that is a {@link List}.
- *
- * @author Eike Stepper
- */
-public interface IContainerList<E> extends IContainerCollection<E>, List<E>
-{
- public List<E> getDelegate();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.IContainer; + +import java.util.List; + +/** + * A {@link IContainer container} that is a {@link List}. + * + * @author Eike Stepper + */ +public interface IContainerList<E> extends IContainerCollection<E>, List<E> +{ + public List<E> getDelegate(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java index 7a69f5248f..1e1da19633 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerMap.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.IContainer;
-
-import java.util.Map;
-
-/**
- * A {@link IContainer container} (of {@link java.util.Map.Entry map entries}) that is a {@link Map}.
- *
- * @author Eike Stepper
- */
-public interface IContainerMap<K, V> extends IContainer<Map.Entry<K, V>>, Map<K, V>
-{
- public Map<K, V> getDelegate();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.IContainer; + +import java.util.Map; + +/** + * A {@link IContainer container} (of {@link java.util.Map.Entry map entries}) that is a {@link Map}. + * + * @author Eike Stepper + */ +public interface IContainerMap<K, V> extends IContainer<Map.Entry<K, V>>, Map<K, V> +{ + public Map<K, V> getDelegate(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java index e552d2ee16..12a85d276b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerQueue.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.IContainer;
-
-import java.util.Queue;
-
-/**
- * A {@link IContainer container} that is a {@link Queue}.
- *
- * @author Eike Stepper
- */
-public interface IContainerQueue<E> extends IContainerCollection<E>, Queue<E>
-{
- public Queue<E> getDelegate();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.IContainer; + +import java.util.Queue; + +/** + * A {@link IContainer container} that is a {@link Queue}. + * + * @author Eike Stepper + */ +public interface IContainerQueue<E> extends IContainerCollection<E>, Queue<E> +{ + public Queue<E> getDelegate(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java index 402b5b3a9a..7a8fda0cb6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/IContainerSortedSet.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.container.delegate;
-
-import org.eclipse.net4j.util.container.IContainer;
-
-import java.util.SortedSet;
-
-/**
- * A {@link IContainer container} that is a {@link SortedSet}.
- *
- * @author Eike Stepper
- */
-public interface IContainerSortedSet<E> extends IContainerSet<E>, SortedSet<E>
-{
- public SortedSet<E> getDelegate();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.container.delegate; + +import org.eclipse.net4j.util.container.IContainer; + +import java.util.SortedSet; + +/** + * A {@link IContainer container} that is a {@link SortedSet}. + * + * @author Eike Stepper + */ +public interface IContainerSortedSet<E> extends IContainerSet<E>, SortedSet<E> +{ + public SortedSet<E> getDelegate(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java index 52c772fe30..b93e346b83 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/delegate/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Hybrid interfaces of notifying containers and the Java Collection Framework.
- */
-package org.eclipse.net4j.util.container.delegate;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Hybrid interfaces of notifying containers and the Java Collection Framework. + */ +package org.eclipse.net4j.util.container.delegate; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java index 9e67eadd66..8c7e9baee2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/container/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework of notifying collections and wiring containers.
- */
-package org.eclipse.net4j.util.container;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework of notifying collections and wiring containers. + */ +package org.eclipse.net4j.util.container; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java index e5539396fd..4ab053bbd3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Event.java @@ -1,51 +1,51 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-import java.text.MessageFormat;
-import java.util.EventObject;
-
-/**
- * A default implementation of an {@link IEvent event}.
- *
- * @author Eike Stepper
- */
-public class Event extends EventObject implements IEvent
-{
- private static final long serialVersionUID = 1L;
-
- public Event(INotifier notifier)
- {
- super(notifier);
- }
-
- @Override
- public INotifier getSource()
- {
- return (INotifier)source;
- }
-
- @Override
- public String toString()
- {
- String params = formatAdditionalParameters();
- params = params == null ? "" : ", " + params;
- return MessageFormat.format("{0}[source={1}{2}]", getClass().getSimpleName(), getSource(), params);
- }
-
- /**
- * @since 3.0
- */
- protected String formatAdditionalParameters()
- {
- return null;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +import java.text.MessageFormat; +import java.util.EventObject; + +/** + * A default implementation of an {@link IEvent event}. + * + * @author Eike Stepper + */ +public class Event extends EventObject implements IEvent +{ + private static final long serialVersionUID = 1L; + + public Event(INotifier notifier) + { + super(notifier); + } + + @Override + public INotifier getSource() + { + return (INotifier)source; + } + + @Override + public String toString() + { + String params = formatAdditionalParameters(); + params = params == null ? "" : ", " + params; + return MessageFormat.format("{0}[source={1}{2}]", getClass().getSimpleName(), getSource(), params); + } + + /** + * @since 3.0 + */ + protected String formatAdditionalParameters() + { + return null; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java index b5803f6332..2c2487033c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ExecutorServiceNotifier.java @@ -1,52 +1,52 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-import java.util.concurrent.ExecutorService;
-
-/**
- * Deprecated.
- *
- * @author Eike Stepper
- * @since 2.0
- * @apiviz.exclude
- */
-@Deprecated
-public class ExecutorServiceNotifier extends Notifier
-{
- private ExecutorService notificationExecutorService;
-
- public ExecutorServiceNotifier()
- {
- }
-
- @Override
- public ExecutorService getNotificationService()
- {
- return notificationExecutorService;
- }
-
- public void setNotificationExecutorService(ExecutorService notificationExecutorService)
- {
- this.notificationExecutorService = notificationExecutorService;
- }
-
- /**
- * Deprecated.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
- @Deprecated
- public static class ThreadPool extends ExecutorServiceNotifier
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +import java.util.concurrent.ExecutorService; + +/** + * Deprecated. + * + * @author Eike Stepper + * @since 2.0 + * @apiviz.exclude + */ +@Deprecated +public class ExecutorServiceNotifier extends Notifier +{ + private ExecutorService notificationExecutorService; + + public ExecutorServiceNotifier() + { + } + + @Override + public ExecutorService getNotificationService() + { + return notificationExecutorService; + } + + public void setNotificationExecutorService(ExecutorService notificationExecutorService) + { + this.notificationExecutorService = notificationExecutorService; + } + + /** + * Deprecated. + * + * @author Eike Stepper + * @apiviz.exclude + */ + @Deprecated + public static class ThreadPool extends ExecutorServiceNotifier + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java index e189d866c2..dda4d88333 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IEvent.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-/**
- * An event that is fired from a {@link INotifier notifier} and can be handled by {@link IListener listeners}.
- *
- * @author Eike Stepper
- * @apiviz.landmark
- */
-public interface IEvent
-{
- public INotifier getSource();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +/** + * An event that is fired from a {@link INotifier notifier} and can be handled by {@link IListener listeners}. + * + * @author Eike Stepper + * @apiviz.landmark + */ +public interface IEvent +{ + public INotifier getSource(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java index c3dd0e557a..2e3043d13f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/IListener.java @@ -1,24 +1,24 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-import java.util.EventListener;
-
-/**
- * A callback interface that {@link INotifier notifiers} use to pass {@link IEvent events} to.
- *
- * @author Eike Stepper
- * @apiviz.landmark
- */
-public interface IListener extends EventListener
-{
- public void notifyEvent(IEvent event);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +import java.util.EventListener; + +/** + * A callback interface that {@link INotifier notifiers} use to pass {@link IEvent events} to. + * + * @author Eike Stepper + * @apiviz.landmark + */ +public interface IListener extends EventListener +{ + public void notifyEvent(IEvent event); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java index c7c4c09d19..2da87e54a3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/INotifier.java @@ -1,57 +1,57 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-/**
- * An entity that a number of {@link IListener listeners} can be registered with and that can fire {@link IEvent events}
- * to these registered listeners.
- * <p>
- * Implementors are encouraged to document the event types that they are able to fire and that their listeners may want
- * to receive and handle.
- * <p>
- * Implementors may want to extend {@link Notifier} instead of implementing this interface directly.
- *
- * @author Eike Stepper
- * @apiviz.landmark
- * @apiviz.owns {@link IListener} - - listeners
- * @apiviz.uses {@link IEvent} - - fires
- */
-public interface INotifier
-{
- /**
- * Adds a listener to this notifier.
- * <p>
- * Depending on the implementation duplicate listeners may lead to duplicate event delivery or not. Implementors are
- * encouraged to prevent events from being delivered more than once to the same listener,
- */
- public void addListener(IListener listener);
-
- /**
- * Removes a listener from this notifier.
- */
- public void removeListener(IListener listener);
-
- /**
- * Returns <code>true</code> if one or more listeners are registered with this notifier, <code>false</code> otherwise.
- *
- * @since 3.0
- */
- public boolean hasListeners();
-
- /**
- * Returns the listeners that are registered with this notifier.
- * <p>
- * Depending on the implementation duplicate listeners may be contained in the returned array.
- *
- * @since 3.0
- */
- public IListener[] getListeners();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +/** + * An entity that a number of {@link IListener listeners} can be registered with and that can fire {@link IEvent events} + * to these registered listeners. + * <p> + * Implementors are encouraged to document the event types that they are able to fire and that their listeners may want + * to receive and handle. + * <p> + * Implementors may want to extend {@link Notifier} instead of implementing this interface directly. + * + * @author Eike Stepper + * @apiviz.landmark + * @apiviz.owns {@link IListener} - - listeners + * @apiviz.uses {@link IEvent} - - fires + */ +public interface INotifier +{ + /** + * Adds a listener to this notifier. + * <p> + * Depending on the implementation duplicate listeners may lead to duplicate event delivery or not. Implementors are + * encouraged to prevent events from being delivered more than once to the same listener, + */ + public void addListener(IListener listener); + + /** + * Removes a listener from this notifier. + */ + public void removeListener(IListener listener); + + /** + * Returns <code>true</code> if one or more listeners are registered with this notifier, <code>false</code> otherwise. + * + * @since 3.0 + */ + public boolean hasListeners(); + + /** + * Returns the listeners that are registered with this notifier. + * <p> + * Depending on the implementation duplicate listeners may be contained in the returned array. + * + * @since 3.0 + */ + public IListener[] getListeners(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java index 3e6bd7335d..6b9f38bca8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/Notifier.java @@ -1,155 +1,155 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.CheckUtil;
-import org.eclipse.net4j.util.collection.ConcurrentArray;
-
-import java.util.concurrent.ExecutorService;
-
-/**
- * A default implementation of a {@link INotifier notifier}.
- *
- * @author Eike Stepper
- * @since 3.0
- */
-public class Notifier implements INotifier
-{
- private ConcurrentArray<IListener> listeners = new ConcurrentArray<IListener>()
- {
- @Override
- protected IListener[] newArray(int length)
- {
- return new IListener[length];
- }
-
- @Override
- protected void firstElementAdded()
- {
- firstListenerAdded();
- }
-
- @Override
- protected void lastElementRemoved()
- {
- lastListenerRemoved();
- }
- };
-
- public Notifier()
- {
- }
-
- public void addListener(IListener listener)
- {
- CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$
- listeners.add(listener);
- }
-
- public void removeListener(IListener listener)
- {
- CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$
- listeners.remove(listener);
- }
-
- public boolean hasListeners()
- {
- return listeners.get() != null;
- }
-
- public IListener[] getListeners()
- {
- return listeners.get();
- }
-
- /**
- * @since 3.2
- */
- public void fireEvent()
- {
- fireEvent(new Event(this));
- }
-
- public void fireEvent(IEvent event)
- {
- if (event != null)
- {
- fireEvent(event, getListeners());
- }
- }
-
- /**
- * @since 3.0
- */
- public void fireEvent(final IEvent event, final IListener[] listeners)
- {
- if (event != null && listeners != null)
- {
- ExecutorService notificationService = getNotificationService();
- if (notificationService != null)
- {
- notificationService.execute(new Runnable()
- {
- public void run()
- {
- fireEventSafe(event, listeners);
- }
- });
- }
- else
- {
- fireEventSafe(event, listeners);
- }
- }
- }
-
- /**
- * @since 3.0
- */
- protected ExecutorService getNotificationService()
- {
- return null;
- }
-
- /**
- * @since 3.0
- */
- protected void firstListenerAdded()
- {
- }
-
- /**
- * @since 3.0
- */
- protected void lastListenerRemoved()
- {
- }
-
- private static void fireEventSafe(IEvent event, IListener[] listeners)
- {
- for (int i = 0; i < listeners.length; i++)
- {
- try
- {
- IListener listener = listeners[i];
- if (listener != null)
- {
- listener.notifyEvent(event);
- }
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.CheckUtil; +import org.eclipse.net4j.util.collection.ConcurrentArray; + +import java.util.concurrent.ExecutorService; + +/** + * A default implementation of a {@link INotifier notifier}. + * + * @author Eike Stepper + * @since 3.0 + */ +public class Notifier implements INotifier +{ + private ConcurrentArray<IListener> listeners = new ConcurrentArray<IListener>() + { + @Override + protected IListener[] newArray(int length) + { + return new IListener[length]; + } + + @Override + protected void firstElementAdded() + { + firstListenerAdded(); + } + + @Override + protected void lastElementRemoved() + { + lastListenerRemoved(); + } + }; + + public Notifier() + { + } + + public void addListener(IListener listener) + { + CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$ + listeners.add(listener); + } + + public void removeListener(IListener listener) + { + CheckUtil.checkArg(listener, "listener"); //$NON-NLS-1$ + listeners.remove(listener); + } + + public boolean hasListeners() + { + return listeners.get() != null; + } + + public IListener[] getListeners() + { + return listeners.get(); + } + + /** + * @since 3.2 + */ + public void fireEvent() + { + fireEvent(new Event(this)); + } + + public void fireEvent(IEvent event) + { + if (event != null) + { + fireEvent(event, getListeners()); + } + } + + /** + * @since 3.0 + */ + public void fireEvent(final IEvent event, final IListener[] listeners) + { + if (event != null && listeners != null) + { + ExecutorService notificationService = getNotificationService(); + if (notificationService != null) + { + notificationService.execute(new Runnable() + { + public void run() + { + fireEventSafe(event, listeners); + } + }); + } + else + { + fireEventSafe(event, listeners); + } + } + } + + /** + * @since 3.0 + */ + protected ExecutorService getNotificationService() + { + return null; + } + + /** + * @since 3.0 + */ + protected void firstListenerAdded() + { + } + + /** + * @since 3.0 + */ + protected void lastListenerRemoved() + { + } + + private static void fireEventSafe(IEvent event, IListener[] listeners) + { + for (int i = 0; i < listeners.length; i++) + { + try + { + IListener listener = listeners[i]; + if (listener != null) + { + listener.notifyEvent(event); + } + } + catch (Exception ex) + { + OM.LOG.error(ex); + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java index e235fcb2f7..e4487667a7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueEvent.java @@ -1,51 +1,51 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-/**
- * An {@link IEvent} fired from {@link ValueNotifier value notifiers} after value changes.
- *
- * @author Eike Stepper
- * @since 3.1
- * @noextend This class is not intended to be subclassed by clients.
- */
-public class ValueEvent<VALUE> extends Event
-{
- private static final long serialVersionUID = 1L;
-
- private VALUE oldValue;
-
- private VALUE newValue;
-
- ValueEvent(ValueNotifier<VALUE> notifier, VALUE oldValue, VALUE newValue)
- {
- super(notifier);
- this.oldValue = oldValue;
- this.newValue = newValue;
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public ValueNotifier<VALUE> getSource()
- {
- return (ValueNotifier<VALUE>)super.getSource();
- }
-
- public VALUE getOldValue()
- {
- return oldValue;
- }
-
- public VALUE getNewValue()
- {
- return newValue;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +/** + * An {@link IEvent} fired from {@link ValueNotifier value notifiers} after value changes. + * + * @author Eike Stepper + * @since 3.1 + * @noextend This class is not intended to be subclassed by clients. + */ +public class ValueEvent<VALUE> extends Event +{ + private static final long serialVersionUID = 1L; + + private VALUE oldValue; + + private VALUE newValue; + + ValueEvent(ValueNotifier<VALUE> notifier, VALUE oldValue, VALUE newValue) + { + super(notifier); + this.oldValue = oldValue; + this.newValue = newValue; + } + + @Override + @SuppressWarnings("unchecked") + public ValueNotifier<VALUE> getSource() + { + return (ValueNotifier<VALUE>)super.getSource(); + } + + public VALUE getOldValue() + { + return oldValue; + } + + public VALUE getNewValue() + { + return newValue; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java index d0c231b62f..36340b456d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/ValueNotifier.java @@ -1,74 +1,74 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.event;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-/**
- * A {@link INotifier notifier} with an {@link #getID() ID} and a single {@link #getValue() value}.
- * <p>
- * A value notifier can fire the following events:
- * <ul>
- * <li> {@link ValueEvent} after value changes.
- * </ul>
- *
- * @author Eike Stepper
- * @since 3.1
- * @apiviz.has {@link java.lang.Object} oneway - - value
- * @apiviz.uses {@link ValueEvent} - - fires
- */
-public class ValueNotifier<VALUE> extends Notifier
-{
- private String id;
-
- private VALUE value;
-
- public ValueNotifier()
- {
- this(null, null);
- }
-
- public ValueNotifier(VALUE value)
- {
- this(null, value);
- }
-
- public ValueNotifier(String id)
- {
- this(id, null);
- }
-
- public ValueNotifier(String id, VALUE value)
- {
- this.id = id;
- this.value = value;
- }
-
- public String getID()
- {
- return id;
- }
-
- public VALUE getValue()
- {
- return value;
- }
-
- public synchronized void setValue(VALUE value)
- {
- VALUE oldValue = this.value;
- if (!ObjectUtil.equals(value, oldValue))
- {
- this.value = value;
- fireEvent(new ValueEvent<VALUE>(this, oldValue, value));
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.event; + +import org.eclipse.net4j.util.ObjectUtil; + +/** + * A {@link INotifier notifier} with an {@link #getID() ID} and a single {@link #getValue() value}. + * <p> + * A value notifier can fire the following events: + * <ul> + * <li> {@link ValueEvent} after value changes. + * </ul> + * + * @author Eike Stepper + * @since 3.1 + * @apiviz.has {@link java.lang.Object} oneway - - value + * @apiviz.uses {@link ValueEvent} - - fires + */ +public class ValueNotifier<VALUE> extends Notifier +{ + private String id; + + private VALUE value; + + public ValueNotifier() + { + this(null, null); + } + + public ValueNotifier(VALUE value) + { + this(null, value); + } + + public ValueNotifier(String id) + { + this(id, null); + } + + public ValueNotifier(String id, VALUE value) + { + this.id = id; + this.value = value; + } + + public String getID() + { + return id; + } + + public VALUE getValue() + { + return value; + } + + public synchronized void setValue(VALUE value) + { + VALUE oldValue = this.value; + if (!ObjectUtil.equals(value, oldValue)) + { + this.value = value; + fireEvent(new ValueEvent<VALUE>(this, oldValue, value)); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java index 96b63150ef..b2b5b195d6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/event/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for sending of and listening to events.
- */
-package org.eclipse.net4j.util.event;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for sending of and listening to events. + */ +package org.eclipse.net4j.util.event; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java index dd20a98445..77ded48ff8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/Factory.java @@ -1,59 +1,59 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-import java.text.MessageFormat;
-
-/**
- * A default implementation of a {@link IFactory factory}.
- *
- * @author Eike Stepper
- */
-public abstract class Factory implements IFactory
-{
- private FactoryKey key;
-
- public Factory(FactoryKey key)
- {
- this.key = key;
- }
-
- public Factory(String productGroup, String type)
- {
- this(new FactoryKey(productGroup, type));
- }
-
- public FactoryKey getKey()
- {
- return key;
- }
-
- public String getProductGroup()
- {
- return key.getProductGroup();
- }
-
- public String getType()
- {
- return key.getType();
- }
-
- public String getDescriptionFor(Object product)
- {
- return null;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("Factory[{0}, {1}]", getProductGroup(), getType()); //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +import java.text.MessageFormat; + +/** + * A default implementation of a {@link IFactory factory}. + * + * @author Eike Stepper + */ +public abstract class Factory implements IFactory +{ + private FactoryKey key; + + public Factory(FactoryKey key) + { + this.key = key; + } + + public Factory(String productGroup, String type) + { + this(new FactoryKey(productGroup, type)); + } + + public FactoryKey getKey() + { + return key; + } + + public String getProductGroup() + { + return key.getProductGroup(); + } + + public String getType() + { + return key.getType(); + } + + public String getDescriptionFor(Object product) + { + return null; + } + + @Override + public String toString() + { + return MessageFormat.format("Factory[{0}, {1}]", getProductGroup(), getType()); //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java index 06da57ccef..aedaac104c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryCreationException.java @@ -1,42 +1,42 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-/**
- * Thrown from {@link FactoryDescriptor#createFactory()} if a {@link IFactory factory} could not be created.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class FactoryCreationException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public FactoryCreationException()
- {
- }
-
- public FactoryCreationException(String message)
- {
- super(message);
- }
-
- public FactoryCreationException(Throwable cause)
- {
- super(cause);
- }
-
- public FactoryCreationException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +/** + * Thrown from {@link FactoryDescriptor#createFactory()} if a {@link IFactory factory} could not be created. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class FactoryCreationException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public FactoryCreationException() + { + } + + public FactoryCreationException(String message) + { + super(message); + } + + public FactoryCreationException(Throwable cause) + { + super(cause); + } + + public FactoryCreationException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java index 51e3030a46..c438d223b9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryDescriptor.java @@ -1,86 +1,86 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionRegistry;
-
-/**
- * A {@link IFactory factory} that delegates to an {@link IExtensionRegistry extension registry} contribution.
- * <p>
- * Example contribution:
- *
- * <pre>
- * <extension
- * point="org.eclipse.net4j.util.factories">
- * <factory
- * class="org.eclipse.net4j.util.concurrent.TimerLifecycle$DaemonFactory"
- * productGroup="org.eclipse.net4j.util.timers"
- * type="daemon"/>
- * </extension>
- * </pre>
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class FactoryDescriptor extends Factory
-{
- private static final String ATTR_PRODUCT_GROUP = "productGroup"; //$NON-NLS-1$
-
- private static final String ATTR_TYPE = "type"; //$NON-NLS-1$
-
- private static final String ATTR_CLASS = "class"; //$NON-NLS-1$
-
- private IConfigurationElement configurationElement;
-
- public FactoryDescriptor(IConfigurationElement configurationElement)
- {
- super(createFactoryKey(configurationElement));
- this.configurationElement = configurationElement;
- }
-
- public IConfigurationElement getConfigurationElement()
- {
- return configurationElement;
- }
-
- public IFactory createFactory()
- {
- try
- {
- return (IFactory)configurationElement.createExecutableExtension(ATTR_CLASS);
- }
- catch (CoreException ex)
- {
- throw new FactoryCreationException(ex);
- }
- }
-
- public Object create(String description)
- {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getDescriptionFor(Object product)
- {
- throw new UnsupportedOperationException();
- }
-
- private static FactoryKey createFactoryKey(IConfigurationElement element)
- {
- String productGroup = element.getAttribute(ATTR_PRODUCT_GROUP);
- String type = element.getAttribute(ATTR_TYPE);
- return new FactoryKey(productGroup, type);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionRegistry; + +/** + * A {@link IFactory factory} that delegates to an {@link IExtensionRegistry extension registry} contribution. + * <p> + * Example contribution: + * + * <pre> + * <extension + * point="org.eclipse.net4j.util.factories"> + * <factory + * class="org.eclipse.net4j.util.concurrent.TimerLifecycle$DaemonFactory" + * productGroup="org.eclipse.net4j.util.timers" + * type="daemon"/> + * </extension> + * </pre> + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class FactoryDescriptor extends Factory +{ + private static final String ATTR_PRODUCT_GROUP = "productGroup"; //$NON-NLS-1$ + + private static final String ATTR_TYPE = "type"; //$NON-NLS-1$ + + private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ + + private IConfigurationElement configurationElement; + + public FactoryDescriptor(IConfigurationElement configurationElement) + { + super(createFactoryKey(configurationElement)); + this.configurationElement = configurationElement; + } + + public IConfigurationElement getConfigurationElement() + { + return configurationElement; + } + + public IFactory createFactory() + { + try + { + return (IFactory)configurationElement.createExecutableExtension(ATTR_CLASS); + } + catch (CoreException ex) + { + throw new FactoryCreationException(ex); + } + } + + public Object create(String description) + { + throw new UnsupportedOperationException(); + } + + @Override + public String getDescriptionFor(Object product) + { + throw new UnsupportedOperationException(); + } + + private static FactoryKey createFactoryKey(IConfigurationElement element) + { + String productGroup = element.getAttribute(ATTR_PRODUCT_GROUP); + String type = element.getAttribute(ATTR_TYPE); + return new FactoryKey(productGroup, type); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java index e61b81e7af..bf94909c05 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/FactoryKey.java @@ -1,98 +1,98 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-import org.eclipse.net4j.util.ObjectUtil;
-import org.eclipse.net4j.util.StringUtil;
-
-import java.io.Serializable;
-import java.text.MessageFormat;
-
-/**
- * A default implementation of a {@link IFactoryKey factory key}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public final class FactoryKey implements IFactoryKey, Serializable, Comparable<FactoryKey>
-{
- private static final long serialVersionUID = 1L;
-
- private String productGroup;
-
- private String type;
-
- public FactoryKey(String productGroup, String type)
- {
- this.productGroup = productGroup;
- this.type = type;
- }
-
- public String getProductGroup()
- {
- return productGroup;
- }
-
- public void setProductGroup(String productGroup)
- {
- this.productGroup = productGroup;
- }
-
- public String getType()
- {
- return type;
- }
-
- public void setType(String type)
- {
- this.type = type;
- }
-
- @Override
- public boolean equals(Object obj)
- {
- if (obj == this)
- {
- return true;
- }
-
- if (obj instanceof FactoryKey)
- {
- FactoryKey key = (FactoryKey)obj;
- return ObjectUtil.equals(productGroup, key.productGroup) && ObjectUtil.equals(type, key.type);
- }
-
- return false;
- }
-
- @Override
- public int hashCode()
- {
- return ObjectUtil.hashCode(productGroup) ^ ObjectUtil.hashCode(type);
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("{0}[{1}]", productGroup, type); //$NON-NLS-1$
- }
-
- public int compareTo(FactoryKey key)
- {
- int result = StringUtil.compare(productGroup, key.productGroup);
- if (result == 0)
- {
- result = StringUtil.compare(type, key.type);
- }
-
- return result;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +import org.eclipse.net4j.util.ObjectUtil; +import org.eclipse.net4j.util.StringUtil; + +import java.io.Serializable; +import java.text.MessageFormat; + +/** + * A default implementation of a {@link IFactoryKey factory key}. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public final class FactoryKey implements IFactoryKey, Serializable, Comparable<FactoryKey> +{ + private static final long serialVersionUID = 1L; + + private String productGroup; + + private String type; + + public FactoryKey(String productGroup, String type) + { + this.productGroup = productGroup; + this.type = type; + } + + public String getProductGroup() + { + return productGroup; + } + + public void setProductGroup(String productGroup) + { + this.productGroup = productGroup; + } + + public String getType() + { + return type; + } + + public void setType(String type) + { + this.type = type; + } + + @Override + public boolean equals(Object obj) + { + if (obj == this) + { + return true; + } + + if (obj instanceof FactoryKey) + { + FactoryKey key = (FactoryKey)obj; + return ObjectUtil.equals(productGroup, key.productGroup) && ObjectUtil.equals(type, key.type); + } + + return false; + } + + @Override + public int hashCode() + { + return ObjectUtil.hashCode(productGroup) ^ ObjectUtil.hashCode(type); + } + + @Override + public String toString() + { + return MessageFormat.format("{0}[{1}]", productGroup, type); //$NON-NLS-1$ + } + + public int compareTo(FactoryKey key) + { + int result = StringUtil.compare(productGroup, key.productGroup); + if (result == 0) + { + result = StringUtil.compare(type, key.type); + } + + return result; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java index d498911d52..23d408d54b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactory.java @@ -1,27 +1,27 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-/**
- * {@link #create(String) Creates} objects from a string {@link #getDescriptionFor(Object) description}.
- *
- * @author Eike Stepper
- * @apiviz.landmark
- * @apiviz.has {@link IFactoryKey}
- */
-public interface IFactory
-{
- public IFactoryKey getKey();
-
- public Object create(String description) throws ProductCreationException;
-
- public String getDescriptionFor(Object product);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +/** + * {@link #create(String) Creates} objects from a string {@link #getDescriptionFor(Object) description}. + * + * @author Eike Stepper + * @apiviz.landmark + * @apiviz.has {@link IFactoryKey} + */ +public interface IFactory +{ + public IFactoryKey getKey(); + + public Object create(String description) throws ProductCreationException; + + public String getDescriptionFor(Object product); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java index 175e6396f6..9ae0c1b812 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/IFactoryKey.java @@ -1,26 +1,26 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-/**
- * Identifies a {@link IFactory factory} by {@link #getProductGroup() product group} and {@link #getType() type}.
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- * @apiviz.landmark
- */
-public interface IFactoryKey
-{
- public String getProductGroup();
-
- public String getType();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +/** + * Identifies a {@link IFactory factory} by {@link #getProductGroup() product group} and {@link #getType() type}. + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + * @apiviz.landmark + */ +public interface IFactoryKey +{ + public String getProductGroup(); + + public String getType(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java index 0304139339..56407c05ed 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/ProductCreationException.java @@ -1,43 +1,43 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.factory;
-
-/**
- * An unchecked exception that may be thrown from {@link IFactory factories} to indicate the inability to create a
- * product.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class ProductCreationException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public ProductCreationException()
- {
- }
-
- public ProductCreationException(String message)
- {
- super(message);
- }
-
- public ProductCreationException(Throwable cause)
- {
- super(cause);
- }
-
- public ProductCreationException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.factory; + +/** + * An unchecked exception that may be thrown from {@link IFactory factories} to indicate the inability to create a + * product. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class ProductCreationException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public ProductCreationException() + { + } + + public ProductCreationException(String message) + { + super(message); + } + + public ProductCreationException(Throwable cause) + { + super(cause); + } + + public ProductCreationException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java index ed3c9cd220..690d576247 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/factory/package-info.java @@ -1,16 +1,16 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for factory based instance creation.
- */
-package org.eclipse.net4j.util.factory;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for factory based instance creation. + */ +package org.eclipse.net4j.util.factory; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java index fcd7f490ca..e334fe254d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/FiniteStateMachine.java @@ -1,390 +1,390 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.fsm;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.event.IEvent;
-import org.eclipse.net4j.util.event.IListener;
-import org.eclipse.net4j.util.event.INotifier;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import java.text.MessageFormat;
-
-/**
- * A <a href="http://en.wikipedia.org/wiki/Finite-state_machine">finite state machine</a> that is based on a matrix of
- * {@link ITransition transitions}.
- * <p>
- * A finite state machine can fire the following events:
- * <ul>
- * <li> {@link StateChangedEvent} after state changes of a <i>subject</i>.
- * </ul>
- *
- * @author Eike Stepper
- * @apiviz.landmark
- * @apiviz.has {@link ITransition} oneway - - matrix
- * @apiviz.uses {@link FiniteStateMachine.StateChangedEvent} - - fires
- */
-public abstract class FiniteStateMachine<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT> extends Lifecycle
-{
- @SuppressWarnings("rawtypes")
- public static final ITransition IGNORE = new InternalIgnoreTransition();
-
- @SuppressWarnings("rawtypes")
- public static final ITransition FAIL = new InternalFailTransition();
-
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, FiniteStateMachine.class);
-
- private static final String MSG_PROCESS = "Processing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$
-
- private static final String MSG_IGNORE = "Ignoring event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$
-
- private static final String MSG_FAIL = "Failing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$
-
- private STATE[] states;
-
- private EVENT[] events;
-
- private ITransition<STATE, EVENT, SUBJECT, ?>[][] transitions;
-
- @SuppressWarnings("unchecked")
- public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum,
- ITransition<STATE, EVENT, SUBJECT, ?> defaultTransition)
- {
- states = stateEnum.getEnumConstants();
- events = eventEnum.getEnumConstants();
- transitions = new ITransition[states.length][events.length];
- initAll(defaultTransition);
- }
-
- @SuppressWarnings("unchecked")
- public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum)
- {
- this(stateEnum, eventEnum, FAIL);
- }
-
- public final STATE[] getStates()
- {
- return states;
- }
-
- public final EVENT[] getEvents()
- {
- return events;
- }
-
- public final ITransition<STATE, EVENT, SUBJECT, ?> getTransition(STATE state, EVENT event)
- {
- int s = state.ordinal();
- int e = event.ordinal();
- return transitions[s][e];
- }
-
- public final void init(STATE state, EVENT event, STATE targetState)
- {
- init(state, event, new ChangeStateTransition(targetState));
- }
-
- public final void init(STATE state, EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition)
- {
- checkTransition(transition);
- int s = state.ordinal();
- int e = event.ordinal();
- transitions[s][e] = transition;
- }
-
- public final void initEvents(STATE state, STATE targetState)
- {
- initEvents(state, new ChangeStateTransition(targetState));
- }
-
- public final void initEvents(STATE state, ITransition<STATE, EVENT, SUBJECT, ?> transition)
- {
- checkTransition(transition);
- int s = state.ordinal();
- for (int e = 0; e < events.length; e++)
- {
- transitions[s][e] = transition;
- }
- }
-
- public final void initStates(EVENT event, STATE targetState)
- {
- initStates(event, new ChangeStateTransition(targetState));
- }
-
- public final void initStates(EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition)
- {
- checkTransition(transition);
- int e = event.ordinal();
- for (int s = 0; s < states.length; s++)
- {
- transitions[s][e] = transition;
- }
- }
-
- public final void initAll(STATE targetState)
- {
- initAll(new ChangeStateTransition(targetState));
- }
-
- public final void initAll(ITransition<STATE, EVENT, SUBJECT, ?> transition)
- {
- checkTransition(transition);
- for (int s = 0; s < states.length; s++)
- {
- for (int e = 0; e < events.length; e++)
- {
- transitions[s][e] = transition;
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- public final <DATA> void process(SUBJECT subject, EVENT event, DATA data)
- {
- STATE state = getState(subject);
- int s = state.ordinal();
- int e = event.ordinal();
- ITransition<STATE, EVENT, SUBJECT, DATA> transition = (ITransition<STATE, EVENT, SUBJECT, DATA>)transitions[s][e];
- if (transition == IGNORE)
- {
- // Do nothing
- }
- else if (transition == FAIL)
- {
- throw new IllegalStateException(formatFailMessage(subject, state, event, data));
- }
- else
- {
- if (TRACER.isEnabled())
- {
- TRACER.trace(formatProcessMessage(subject, state, event, data));
- }
-
- transition.execute(subject, state, event, data);
- }
- }
-
- @SuppressWarnings("unchecked")
- protected ITransition<STATE, EVENT, SUBJECT, ?> createIgnoreTransition(STATE state, EVENT event)
- {
- return IGNORE;
- }
-
- @SuppressWarnings("unchecked")
- protected ITransition<STATE, EVENT, SUBJECT, ?> createFailTransition(STATE state, EVENT event)
- {
- return FAIL;
- }
-
- protected String formatProcessMessage(SUBJECT subject, STATE state, EVENT event, Object data)
- {
- return MessageFormat.format(MSG_PROCESS, event, state, subject, data);
- }
-
- protected String formatIgnoreMessage(SUBJECT subject, STATE state, EVENT event, Object data)
- {
- return MessageFormat.format(MSG_IGNORE, event, state, subject, data);
- }
-
- protected String formatFailMessage(SUBJECT subject, STATE state, EVENT event, Object data)
- {
- return MessageFormat.format(MSG_FAIL, event, state, subject, data);
- }
-
- protected abstract STATE getState(SUBJECT subject);
-
- protected abstract void setState(SUBJECT subject, STATE state);
-
- /**
- * @since 3.0
- */
- protected STATE changeState(SUBJECT subject, STATE state)
- {
- STATE oldState = getState(subject);
- if (oldState != state)
- {
- setState(subject, state);
- IListener[] listeners = getListeners();
- if (listeners != null)
- {
- fireEvent(new StateChangedEvent(subject, oldState, state), listeners);
- }
-
- return oldState;
- }
-
- return null;
- }
-
- private void checkTransition(ITransition<STATE, EVENT, SUBJECT, ?> transition)
- {
- if (transition == null)
- {
- throw new IllegalArgumentException("transition == null"); //$NON-NLS-1$
- }
- }
-
- /**
- * A {@link ITransition transition} that does nothing.
- *
- * @author Eike Stepper
- * @deprecated Use {@link FiniteStateMachine#IGNORE}
- * @apiviz.exclude
- */
- @Deprecated
- public static class IgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
- {
- public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
- {
- // Do nothing
- }
-
- @Override
- public String toString()
- {
- return "IGNORE"; //$NON-NLS-1$
- }
- }
-
- /**
- * A {@link ITransition transition} that throws an {@link IllegalStateException}.
- *
- * @author Eike Stepper
- * @deprecated Use {@link FiniteStateMachine#FAIL}
- * @apiviz.exclude
- */
- @Deprecated
- public static class FailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
- {
- public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
- {
- // Do nothing
- }
-
- @Override
- public String toString()
- {
- return "FAIL"; //$NON-NLS-1$
- }
- }
-
- /**
- * A {@link ITransition transition} that does nothing.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
- private static class InternalIgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
- {
- public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
- {
- // Do nothing
- }
-
- @Override
- public String toString()
- {
- return "IGNORE"; //$NON-NLS-1$
- }
- }
-
- /**
- * A {@link ITransition transition} that throws an {@link IllegalStateException}.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
- private static class InternalFailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object>
- {
- public void execute(Object subject, Enum<?> state, Enum<?> event, Object data)
- {
- // Do nothing
- }
-
- @Override
- public String toString()
- {
- return "FAIL"; //$NON-NLS-1$
- }
- }
-
- /**
- * A {@link ITransition transition} that changes the {@link #getTargetState() state} of a <i>subject</i>.
- *
- * @author Eike Stepper
- */
- public class ChangeStateTransition implements ITransition<STATE, EVENT, SUBJECT, Object>
- {
- private STATE targetState;
-
- public ChangeStateTransition(STATE targetState)
- {
- this.targetState = targetState;
- }
-
- public STATE getTargetState()
- {
- return targetState;
- }
-
- public void execute(SUBJECT subject, STATE state, EVENT event, Object data)
- {
- changeState(subject, targetState);
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("CHANGE_STATE[{0}]", targetState); //$NON-NLS-1$
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public class StateChangedEvent implements IEvent
- {
- private Object subject;
-
- private Enum<?> oldState;
-
- private Enum<?> newState;
-
- public StateChangedEvent(Object subject, Enum<?> oldState, Enum<?> newState)
- {
- this.subject = subject;
- this.oldState = oldState;
- this.newState = newState;
- }
-
- public INotifier getSource()
- {
- return FiniteStateMachine.this;
- }
-
- public Object getSubject()
- {
- return subject;
- }
-
- public Enum<?> getOldState()
- {
- return oldState;
- }
-
- public Enum<?> getNewState()
- {
- return newState;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.fsm; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.event.IEvent; +import org.eclipse.net4j.util.event.IListener; +import org.eclipse.net4j.util.event.INotifier; +import org.eclipse.net4j.util.lifecycle.Lifecycle; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import java.text.MessageFormat; + +/** + * A <a href="http://en.wikipedia.org/wiki/Finite-state_machine">finite state machine</a> that is based on a matrix of + * {@link ITransition transitions}. + * <p> + * A finite state machine can fire the following events: + * <ul> + * <li> {@link StateChangedEvent} after state changes of a <i>subject</i>. + * </ul> + * + * @author Eike Stepper + * @apiviz.landmark + * @apiviz.has {@link ITransition} oneway - - matrix + * @apiviz.uses {@link FiniteStateMachine.StateChangedEvent} - - fires + */ +public abstract class FiniteStateMachine<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT> extends Lifecycle +{ + @SuppressWarnings("rawtypes") + public static final ITransition IGNORE = new InternalIgnoreTransition(); + + @SuppressWarnings("rawtypes") + public static final ITransition FAIL = new InternalFailTransition(); + + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, FiniteStateMachine.class); + + private static final String MSG_PROCESS = "Processing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$ + + private static final String MSG_IGNORE = "Ignoring event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$ + + private static final String MSG_FAIL = "Failing event {0} in state {1} for {2} (data={3})"; //$NON-NLS-1$ + + private STATE[] states; + + private EVENT[] events; + + private ITransition<STATE, EVENT, SUBJECT, ?>[][] transitions; + + @SuppressWarnings("unchecked") + public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum, + ITransition<STATE, EVENT, SUBJECT, ?> defaultTransition) + { + states = stateEnum.getEnumConstants(); + events = eventEnum.getEnumConstants(); + transitions = new ITransition[states.length][events.length]; + initAll(defaultTransition); + } + + @SuppressWarnings("unchecked") + public FiniteStateMachine(Class<STATE> stateEnum, Class<EVENT> eventEnum) + { + this(stateEnum, eventEnum, FAIL); + } + + public final STATE[] getStates() + { + return states; + } + + public final EVENT[] getEvents() + { + return events; + } + + public final ITransition<STATE, EVENT, SUBJECT, ?> getTransition(STATE state, EVENT event) + { + int s = state.ordinal(); + int e = event.ordinal(); + return transitions[s][e]; + } + + public final void init(STATE state, EVENT event, STATE targetState) + { + init(state, event, new ChangeStateTransition(targetState)); + } + + public final void init(STATE state, EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition) + { + checkTransition(transition); + int s = state.ordinal(); + int e = event.ordinal(); + transitions[s][e] = transition; + } + + public final void initEvents(STATE state, STATE targetState) + { + initEvents(state, new ChangeStateTransition(targetState)); + } + + public final void initEvents(STATE state, ITransition<STATE, EVENT, SUBJECT, ?> transition) + { + checkTransition(transition); + int s = state.ordinal(); + for (int e = 0; e < events.length; e++) + { + transitions[s][e] = transition; + } + } + + public final void initStates(EVENT event, STATE targetState) + { + initStates(event, new ChangeStateTransition(targetState)); + } + + public final void initStates(EVENT event, ITransition<STATE, EVENT, SUBJECT, ?> transition) + { + checkTransition(transition); + int e = event.ordinal(); + for (int s = 0; s < states.length; s++) + { + transitions[s][e] = transition; + } + } + + public final void initAll(STATE targetState) + { + initAll(new ChangeStateTransition(targetState)); + } + + public final void initAll(ITransition<STATE, EVENT, SUBJECT, ?> transition) + { + checkTransition(transition); + for (int s = 0; s < states.length; s++) + { + for (int e = 0; e < events.length; e++) + { + transitions[s][e] = transition; + } + } + } + + @SuppressWarnings("unchecked") + public final <DATA> void process(SUBJECT subject, EVENT event, DATA data) + { + STATE state = getState(subject); + int s = state.ordinal(); + int e = event.ordinal(); + ITransition<STATE, EVENT, SUBJECT, DATA> transition = (ITransition<STATE, EVENT, SUBJECT, DATA>)transitions[s][e]; + if (transition == IGNORE) + { + // Do nothing + } + else if (transition == FAIL) + { + throw new IllegalStateException(formatFailMessage(subject, state, event, data)); + } + else + { + if (TRACER.isEnabled()) + { + TRACER.trace(formatProcessMessage(subject, state, event, data)); + } + + transition.execute(subject, state, event, data); + } + } + + @SuppressWarnings("unchecked") + protected ITransition<STATE, EVENT, SUBJECT, ?> createIgnoreTransition(STATE state, EVENT event) + { + return IGNORE; + } + + @SuppressWarnings("unchecked") + protected ITransition<STATE, EVENT, SUBJECT, ?> createFailTransition(STATE state, EVENT event) + { + return FAIL; + } + + protected String formatProcessMessage(SUBJECT subject, STATE state, EVENT event, Object data) + { + return MessageFormat.format(MSG_PROCESS, event, state, subject, data); + } + + protected String formatIgnoreMessage(SUBJECT subject, STATE state, EVENT event, Object data) + { + return MessageFormat.format(MSG_IGNORE, event, state, subject, data); + } + + protected String formatFailMessage(SUBJECT subject, STATE state, EVENT event, Object data) + { + return MessageFormat.format(MSG_FAIL, event, state, subject, data); + } + + protected abstract STATE getState(SUBJECT subject); + + protected abstract void setState(SUBJECT subject, STATE state); + + /** + * @since 3.0 + */ + protected STATE changeState(SUBJECT subject, STATE state) + { + STATE oldState = getState(subject); + if (oldState != state) + { + setState(subject, state); + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new StateChangedEvent(subject, oldState, state), listeners); + } + + return oldState; + } + + return null; + } + + private void checkTransition(ITransition<STATE, EVENT, SUBJECT, ?> transition) + { + if (transition == null) + { + throw new IllegalArgumentException("transition == null"); //$NON-NLS-1$ + } + } + + /** + * A {@link ITransition transition} that does nothing. + * + * @author Eike Stepper + * @deprecated Use {@link FiniteStateMachine#IGNORE} + * @apiviz.exclude + */ + @Deprecated + public static class IgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> + { + public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) + { + // Do nothing + } + + @Override + public String toString() + { + return "IGNORE"; //$NON-NLS-1$ + } + } + + /** + * A {@link ITransition transition} that throws an {@link IllegalStateException}. + * + * @author Eike Stepper + * @deprecated Use {@link FiniteStateMachine#FAIL} + * @apiviz.exclude + */ + @Deprecated + public static class FailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> + { + public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) + { + // Do nothing + } + + @Override + public String toString() + { + return "FAIL"; //$NON-NLS-1$ + } + } + + /** + * A {@link ITransition transition} that does nothing. + * + * @author Eike Stepper + * @apiviz.exclude + */ + private static class InternalIgnoreTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> + { + public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) + { + // Do nothing + } + + @Override + public String toString() + { + return "IGNORE"; //$NON-NLS-1$ + } + } + + /** + * A {@link ITransition transition} that throws an {@link IllegalStateException}. + * + * @author Eike Stepper + * @apiviz.exclude + */ + private static class InternalFailTransition implements ITransition<Enum<?>, Enum<?>, Object, Object> + { + public void execute(Object subject, Enum<?> state, Enum<?> event, Object data) + { + // Do nothing + } + + @Override + public String toString() + { + return "FAIL"; //$NON-NLS-1$ + } + } + + /** + * A {@link ITransition transition} that changes the {@link #getTargetState() state} of a <i>subject</i>. + * + * @author Eike Stepper + */ + public class ChangeStateTransition implements ITransition<STATE, EVENT, SUBJECT, Object> + { + private STATE targetState; + + public ChangeStateTransition(STATE targetState) + { + this.targetState = targetState; + } + + public STATE getTargetState() + { + return targetState; + } + + public void execute(SUBJECT subject, STATE state, EVENT event, Object data) + { + changeState(subject, targetState); + } + + @Override + public String toString() + { + return MessageFormat.format("CHANGE_STATE[{0}]", targetState); //$NON-NLS-1$ + } + } + + /** + * @author Eike Stepper + */ + public class StateChangedEvent implements IEvent + { + private Object subject; + + private Enum<?> oldState; + + private Enum<?> newState; + + public StateChangedEvent(Object subject, Enum<?> oldState, Enum<?> newState) + { + this.subject = subject; + this.oldState = oldState; + this.newState = newState; + } + + public INotifier getSource() + { + return FiniteStateMachine.this; + } + + public Object getSubject() + { + return subject; + } + + public Enum<?> getOldState() + { + return oldState; + } + + public Enum<?> getNewState() + { + return newState; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java index 3866cbfd49..3fb1806195 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/ITransition.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.fsm;
-
-/**
- * Encpsulates the logic to be executed when an <i>event</i> arrives for a <i>subject</i> in a particular <i>state</i>.
- *
- * @author Eike Stepper
- * @apiviz.landmark
- */
-public interface ITransition<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT, DATA>
-{
- public void execute(SUBJECT subject, STATE state, EVENT event, DATA data);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.fsm; + +/** + * Encpsulates the logic to be executed when an <i>event</i> arrives for a <i>subject</i> in a particular <i>state</i>. + * + * @author Eike Stepper + * @apiviz.landmark + */ +public interface ITransition<STATE extends Enum<?>, EVENT extends Enum<?>, SUBJECT, DATA> +{ + public void execute(SUBJECT subject, STATE state, EVENT event, DATA data); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java index d42f1f6cb5..3823dbaecc 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/fsm/package-info.java @@ -1,16 +1,16 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for <a href="http://en.wikipedia.org/wiki/Finite-state_machine">finite state machines</a>.
- */
-package org.eclipse.net4j.util.fsm;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for <a href="http://en.wikipedia.org/wiki/Finite-state_machine">finite state machines</a>. + */ +package org.eclipse.net4j.util.fsm; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java index 1b19f45256..f5d215a2ee 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncOutputStream.java @@ -1,74 +1,74 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.WrappedException;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.util.concurrent.CountDownLatch;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public abstract class AsyncOutputStream extends PipedOutputStream
-{
- private CountDownLatch latch = new CountDownLatch(1);
-
- public AsyncOutputStream() throws IOException
- {
- final PipedInputStream in = new PipedInputStream(this);
- Thread thread = new Thread("AsyncOutputStream")
- {
- @Override
- public void run()
- {
- try
- {
- asyncWrite(in);
- }
- catch (IOException ex)
- {
- OM.LOG.error(ex);
- throw WrappedException.wrap(ex);
- }
- finally
- {
- latch.countDown();
- }
- }
- };
-
- thread.setDaemon(true);
- thread.start();
- }
-
- @Override
- public void close() throws IOException
- {
- super.close();
-
- try
- {
- latch.await();
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- protected abstract void asyncWrite(InputStream in) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.WrappedException; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.util.concurrent.CountDownLatch; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public abstract class AsyncOutputStream extends PipedOutputStream +{ + private CountDownLatch latch = new CountDownLatch(1); + + public AsyncOutputStream() throws IOException + { + final PipedInputStream in = new PipedInputStream(this); + Thread thread = new Thread("AsyncOutputStream") + { + @Override + public void run() + { + try + { + asyncWrite(in); + } + catch (IOException ex) + { + OM.LOG.error(ex); + throw WrappedException.wrap(ex); + } + finally + { + latch.countDown(); + } + } + }; + + thread.setDaemon(true); + thread.start(); + } + + @Override + public void close() throws IOException + { + super.close(); + + try + { + latch.await(); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + } + + protected abstract void asyncWrite(InputStream in) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java index 79cf83bf5a..15bee78794 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/AsyncWriter.java @@ -1,74 +1,74 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.WrappedException;
-
-import java.io.IOException;
-import java.io.PipedReader;
-import java.io.PipedWriter;
-import java.io.Reader;
-import java.util.concurrent.CountDownLatch;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public abstract class AsyncWriter extends PipedWriter
-{
- private CountDownLatch latch = new CountDownLatch(1);
-
- public AsyncWriter() throws IOException
- {
- final PipedReader in = new PipedReader(this);
- Thread thread = new Thread("AsyncWriter")
- {
- @Override
- public void run()
- {
- try
- {
- asyncWrite(in);
- }
- catch (IOException ex)
- {
- OM.LOG.error(ex);
- throw WrappedException.wrap(ex);
- }
- finally
- {
- latch.countDown();
- }
- }
- };
-
- thread.setDaemon(true);
- thread.start();
- }
-
- @Override
- public void close() throws IOException
- {
- super.close();
-
- try
- {
- latch.await();
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- protected abstract void asyncWrite(Reader in) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.WrappedException; + +import java.io.IOException; +import java.io.PipedReader; +import java.io.PipedWriter; +import java.io.Reader; +import java.util.concurrent.CountDownLatch; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public abstract class AsyncWriter extends PipedWriter +{ + private CountDownLatch latch = new CountDownLatch(1); + + public AsyncWriter() throws IOException + { + final PipedReader in = new PipedReader(this); + Thread thread = new Thread("AsyncWriter") + { + @Override + public void run() + { + try + { + asyncWrite(in); + } + catch (IOException ex) + { + OM.LOG.error(ex); + throw WrappedException.wrap(ex); + } + finally + { + latch.countDown(); + } + } + }; + + thread.setDaemon(true); + thread.start(); + } + + @Override + public void close() throws IOException + { + super.close(); + + try + { + latch.await(); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + } + + protected abstract void asyncWrite(Reader in) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java index e212dde5cf..6da666cf09 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/CachedFileMap.java @@ -1,48 +1,48 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public abstract class CachedFileMap<K extends Comparable<K>, V> extends SortedFileMap<K, V>
-{
- private Map<K, V> cache = new HashMap<K, V>();
-
- public CachedFileMap(File file, String mode)
- {
- super(file, mode);
- }
-
- @Override
- public V get(K key)
- {
- V value = cache.get(key);
- if (value == null)
- {
- value = super.get(key);
- cache.put(key, value);
- }
-
- return value;
- }
-
- @Override
- public V put(K key, V value)
- {
- cache.put(key, value);
- return super.put(key, value);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public abstract class CachedFileMap<K extends Comparable<K>, V> extends SortedFileMap<K, V> +{ + private Map<K, V> cache = new HashMap<K, V>(); + + public CachedFileMap(File file, String mode) + { + super(file, mode); + } + + @Override + public V get(K key) + { + V value = cache.get(key); + if (value == null) + { + value = super.get(key); + cache.put(key, value); + } + + return value; + } + + @Override + public V put(K key, V value) + { + cache.put(key, value); + return super.put(key, value); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java index 49478c2409..448d1420db 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataInputExtender.java @@ -1,137 +1,137 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver;
-
-import java.io.DataInput;
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- */
-public class DataInputExtender implements ExtendedDataInput
-{
- private DataInput input;
-
- public DataInputExtender(DataInput input)
- {
- this.input = input;
- }
-
- public boolean readBoolean() throws IOException
- {
- return input.readBoolean();
- }
-
- public byte readByte() throws IOException
- {
- return input.readByte();
- }
-
- public char readChar() throws IOException
- {
- return input.readChar();
- }
-
- public double readDouble() throws IOException
- {
- return input.readDouble();
- }
-
- public float readFloat() throws IOException
- {
- return input.readFloat();
- }
-
- public void readFully(byte[] b, int off, int len) throws IOException
- {
- input.readFully(b, off, len);
- }
-
- public void readFully(byte[] b) throws IOException
- {
- input.readFully(b);
- }
-
- public int readInt() throws IOException
- {
- return input.readInt();
- }
-
- public String readLine() throws IOException
- {
- return input.readLine();
- }
-
- public long readLong() throws IOException
- {
- return input.readLong();
- }
-
- public short readShort() throws IOException
- {
- return input.readShort();
- }
-
- public int readUnsignedByte() throws IOException
- {
- return input.readUnsignedByte();
- }
-
- public int readUnsignedShort() throws IOException
- {
- return input.readUnsignedShort();
- }
-
- public String readUTF() throws IOException
- {
- return input.readUTF();
- }
-
- public byte[] readByteArray() throws IOException
- {
- return ExtendedIOUtil.readByteArray(input);
- }
-
- public Object readObject() throws IOException
- {
- return ExtendedIOUtil.readObject(input);
- }
-
- public Object readObject(ClassLoader classLoader) throws IOException
- {
- return ExtendedIOUtil.readObject(input, classLoader);
- }
-
- public Object readObject(ClassResolver classResolver) throws IOException
- {
- return ExtendedIOUtil.readObject(input, classResolver);
- }
-
- public String readString() throws IOException
- {
- return ExtendedIOUtil.readString(input);
- }
-
- /**
- * @since 3.0
- */
- public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException
- {
- return ExtendedIOUtil.readEnum(input, type);
- }
-
- public int skipBytes(int n) throws IOException
- {
- return input.skipBytes(n);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver; + +import java.io.DataInput; +import java.io.IOException; + +/** + * @author Eike Stepper + */ +public class DataInputExtender implements ExtendedDataInput +{ + private DataInput input; + + public DataInputExtender(DataInput input) + { + this.input = input; + } + + public boolean readBoolean() throws IOException + { + return input.readBoolean(); + } + + public byte readByte() throws IOException + { + return input.readByte(); + } + + public char readChar() throws IOException + { + return input.readChar(); + } + + public double readDouble() throws IOException + { + return input.readDouble(); + } + + public float readFloat() throws IOException + { + return input.readFloat(); + } + + public void readFully(byte[] b, int off, int len) throws IOException + { + input.readFully(b, off, len); + } + + public void readFully(byte[] b) throws IOException + { + input.readFully(b); + } + + public int readInt() throws IOException + { + return input.readInt(); + } + + public String readLine() throws IOException + { + return input.readLine(); + } + + public long readLong() throws IOException + { + return input.readLong(); + } + + public short readShort() throws IOException + { + return input.readShort(); + } + + public int readUnsignedByte() throws IOException + { + return input.readUnsignedByte(); + } + + public int readUnsignedShort() throws IOException + { + return input.readUnsignedShort(); + } + + public String readUTF() throws IOException + { + return input.readUTF(); + } + + public byte[] readByteArray() throws IOException + { + return ExtendedIOUtil.readByteArray(input); + } + + public Object readObject() throws IOException + { + return ExtendedIOUtil.readObject(input); + } + + public Object readObject(ClassLoader classLoader) throws IOException + { + return ExtendedIOUtil.readObject(input, classLoader); + } + + public Object readObject(ClassResolver classResolver) throws IOException + { + return ExtendedIOUtil.readObject(input, classResolver); + } + + public String readString() throws IOException + { + return ExtendedIOUtil.readString(input); + } + + /** + * @since 3.0 + */ + public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException + { + return ExtendedIOUtil.readEnum(input, type); + } + + public int skipBytes(int n) throws IOException + { + return input.skipBytes(n); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java index f3b9e11b74..ad15bf69a6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DataOutputExtender.java @@ -1,120 +1,120 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.DataOutput;
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- */
-public class DataOutputExtender implements ExtendedDataOutput
-{
- private DataOutput output;
-
- public DataOutputExtender(DataOutput output)
- {
- this.output = output;
- }
-
- public void write(byte[] b, int off, int len) throws IOException
- {
- output.write(b, off, len);
- }
-
- public void write(byte[] b) throws IOException
- {
- output.write(b);
- }
-
- public void write(int b) throws IOException
- {
- output.write(b);
- }
-
- public void writeBoolean(boolean v) throws IOException
- {
- output.writeBoolean(v);
- }
-
- public void writeByte(int v) throws IOException
- {
- output.writeByte(v);
- }
-
- public void writeBytes(String s) throws IOException
- {
- output.writeBytes(s);
- }
-
- public void writeChar(int v) throws IOException
- {
- output.writeChar(v);
- }
-
- public void writeChars(String s) throws IOException
- {
- output.writeChars(s);
- }
-
- public void writeDouble(double v) throws IOException
- {
- output.writeDouble(v);
- }
-
- public void writeFloat(float v) throws IOException
- {
- output.writeFloat(v);
- }
-
- public void writeInt(int v) throws IOException
- {
- output.writeInt(v);
- }
-
- public void writeLong(long v) throws IOException
- {
- output.writeLong(v);
- }
-
- public void writeShort(int v) throws IOException
- {
- output.writeShort(v);
- }
-
- public void writeUTF(String str) throws IOException
- {
- output.writeUTF(str);
- }
-
- public void writeByteArray(byte[] b) throws IOException
- {
- ExtendedIOUtil.writeByteArray(output, b);
- }
-
- public void writeObject(Object object) throws IOException
- {
- ExtendedIOUtil.writeObject(output, object);
- }
-
- public void writeString(String str) throws IOException
- {
- ExtendedIOUtil.writeString(output, str);
- }
-
- /**
- * @since 3.0
- */
- public void writeEnum(Enum<?> literal) throws IOException
- {
- ExtendedIOUtil.writeEnum(output, literal);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.DataOutput; +import java.io.IOException; + +/** + * @author Eike Stepper + */ +public class DataOutputExtender implements ExtendedDataOutput +{ + private DataOutput output; + + public DataOutputExtender(DataOutput output) + { + this.output = output; + } + + public void write(byte[] b, int off, int len) throws IOException + { + output.write(b, off, len); + } + + public void write(byte[] b) throws IOException + { + output.write(b); + } + + public void write(int b) throws IOException + { + output.write(b); + } + + public void writeBoolean(boolean v) throws IOException + { + output.writeBoolean(v); + } + + public void writeByte(int v) throws IOException + { + output.writeByte(v); + } + + public void writeBytes(String s) throws IOException + { + output.writeBytes(s); + } + + public void writeChar(int v) throws IOException + { + output.writeChar(v); + } + + public void writeChars(String s) throws IOException + { + output.writeChars(s); + } + + public void writeDouble(double v) throws IOException + { + output.writeDouble(v); + } + + public void writeFloat(float v) throws IOException + { + output.writeFloat(v); + } + + public void writeInt(int v) throws IOException + { + output.writeInt(v); + } + + public void writeLong(long v) throws IOException + { + output.writeLong(v); + } + + public void writeShort(int v) throws IOException + { + output.writeShort(v); + } + + public void writeUTF(String str) throws IOException + { + output.writeUTF(str); + } + + public void writeByteArray(byte[] b) throws IOException + { + ExtendedIOUtil.writeByteArray(output, b); + } + + public void writeObject(Object object) throws IOException + { + ExtendedIOUtil.writeObject(output, object); + } + + public void writeString(String str) throws IOException + { + ExtendedIOUtil.writeString(output, str); + } + + /** + * @since 3.0 + */ + public void writeEnum(Enum<?> literal) throws IOException + { + ExtendedIOUtil.writeEnum(output, literal); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java index 04cfa9a4bd..0a5dd159a1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingInputStream.java @@ -1,179 +1,179 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * A <code>DelegatingInputStream</code> contains some other input stream, which it uses as its basic source of data,
- * possibly transforming the data along the way or providing additional functionality. The class
- * <code>DelegatingInputStream</code> itself simply overrides all (see note below) methods of <code>InputStream</code>
- * with versions that pass all requests to the contained input stream. Subclasses of <code>DelegatingInputStream</code>
- * may further override some of these methods and may also provide additional methods and fields.
- * <p>
- * <b>Note:</b> The only difference to {@link java.io.FilterInputStream} is that <code>DelegatingInputStream</code> does
- * <b>not</b> override {@link #read(byte[])} or {@link #read(byte[], int, int)} but rather exposes the original
- * implementations of <code>InputStream</code> which call {@link #read()} instead of their delegate counterparts.
- *
- * @author Eike Stepper
- */
-public class DelegatingInputStream extends InputStream
-{
- /**
- * The input stream to be filtered.
- */
- protected volatile InputStream in;
-
- /**
- * Creates a <code>DelegatingInputStream</code> by assigning the argument <code>in</code> to the field
- * <code>this.in</code> so as to remember it for later use.
- *
- * @param in
- * the underlying input stream, or <code>null</code> if this instance is to be created without an underlying
- * stream.
- */
- protected DelegatingInputStream(InputStream in)
- {
- this.in = in;
- }
-
- public InputStream getDelegate()
- {
- return in;
- }
-
- /**
- * Reads the next byte of data from this input stream. The value byte is returned as an <code>int</code> in the range
- * <code>0</code> to <code>255</code>. If no byte is available because the end of the stream has been reached, the
- * value <code>-1</code> is returned. This method blocks until input data is available, the end of the stream is
- * detected, or an exception is thrown.
- * <p>
- * This method simply performs <code>in.read()</code> and returns the result.
- *
- * @return the next byte of data, or <code>-1</code> if the end of the stream is reached.
- * @exception IOException
- * if an I/O error occurs.
- * @see DelegatingInputStream#in
- */
- @Override
- public int read() throws IOException
- {
- return in.read();
- }
-
- /**
- * Skips over and discards <code>n</code> bytes of data from the input stream. The <code>skip</code> method may, for a
- * variety of reasons, end up skipping over some smaller number of bytes, possibly <code>0</code>. The actual number
- * of bytes skipped is returned.
- * <p>
- * This method simply performs <code>in.skip(n)</code>.
- *
- * @param n
- * the number of bytes to be skipped.
- * @return the actual number of bytes skipped.
- * @exception IOException
- * if an I/O error occurs.
- */
- @Override
- public long skip(long n) throws IOException
- {
- return in.skip(n);
- }
-
- /**
- * Returns the number of bytes that can be read from this input stream without blocking.
- * <p>
- * This method simply performs <code>in.available()</code> and returns the result.
- *
- * @return the number of bytes that can be read from the input stream without blocking.
- * @exception IOException
- * if an I/O error occurs.
- * @see DelegatingInputStream#in
- */
- @Override
- public int available() throws IOException
- {
- return in.available();
- }
-
- /**
- * Closes this input stream and releases any system resources associated with the stream. This method simply performs
- * <code>in.close()</code>.
- *
- * @exception IOException
- * if an I/O error occurs.
- * @see DelegatingInputStream#in
- */
- @Override
- public void close() throws IOException
- {
- in.close();
- }
-
- /**
- * Marks the current position in this input stream. A subsequent call to the <code>reset</code> method repositions
- * this stream at the last marked position so that subsequent reads re-read the same bytes.
- * <p>
- * The <code>readlimit</code> argument tells this input stream to allow that many bytes to be read before the mark
- * position gets invalidated.
- * <p>
- * This method simply performs <code>in.mark(readlimit)</code>.
- *
- * @param readlimit
- * the maximum limit of bytes that can be read before the mark position becomes invalid.
- * @see DelegatingInputStream#in
- * @see DelegatingInputStream#reset()
- */
- @Override
- public synchronized void mark(int readlimit)
- {
- in.mark(readlimit);
- }
-
- /**
- * Repositions this stream to the position at the time the <code>mark</code> method was last called on this input
- * stream.
- * <p>
- * This method simply performs <code>in.reset()</code>.
- * <p>
- * Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the
- * stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the
- * parse, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it
- * fails. If this happens within readlimit bytes, it allows the outer code to reset the stream and try another parser.
- *
- * @exception IOException
- * if the stream has not been marked or if the mark has been invalidated.
- * @see DelegatingInputStream#in
- * @see DelegatingInputStream#mark(int)
- */
- @Override
- public synchronized void reset() throws IOException
- {
- in.reset();
- }
-
- /**
- * Tests if this input stream supports the <code>mark</code> and <code>reset</code> methods. This method simply
- * performs <code>in.markSupported()</code>.
- *
- * @return <code>true</code> if this stream type supports the <code>mark</code> and <code>reset</code> method;
- * <code>false</code> otherwise.
- * @see DelegatingInputStream#in
- * @see java.io.InputStream#mark(int)
- * @see java.io.InputStream#reset()
- */
- @Override
- public boolean markSupported()
- {
- return in.markSupported();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * A <code>DelegatingInputStream</code> contains some other input stream, which it uses as its basic source of data, + * possibly transforming the data along the way or providing additional functionality. The class + * <code>DelegatingInputStream</code> itself simply overrides all (see note below) methods of <code>InputStream</code> + * with versions that pass all requests to the contained input stream. Subclasses of <code>DelegatingInputStream</code> + * may further override some of these methods and may also provide additional methods and fields. + * <p> + * <b>Note:</b> The only difference to {@link java.io.FilterInputStream} is that <code>DelegatingInputStream</code> does + * <b>not</b> override {@link #read(byte[])} or {@link #read(byte[], int, int)} but rather exposes the original + * implementations of <code>InputStream</code> which call {@link #read()} instead of their delegate counterparts. + * + * @author Eike Stepper + */ +public class DelegatingInputStream extends InputStream +{ + /** + * The input stream to be filtered. + */ + protected volatile InputStream in; + + /** + * Creates a <code>DelegatingInputStream</code> by assigning the argument <code>in</code> to the field + * <code>this.in</code> so as to remember it for later use. + * + * @param in + * the underlying input stream, or <code>null</code> if this instance is to be created without an underlying + * stream. + */ + protected DelegatingInputStream(InputStream in) + { + this.in = in; + } + + public InputStream getDelegate() + { + return in; + } + + /** + * Reads the next byte of data from this input stream. The value byte is returned as an <code>int</code> in the range + * <code>0</code> to <code>255</code>. If no byte is available because the end of the stream has been reached, the + * value <code>-1</code> is returned. This method blocks until input data is available, the end of the stream is + * detected, or an exception is thrown. + * <p> + * This method simply performs <code>in.read()</code> and returns the result. + * + * @return the next byte of data, or <code>-1</code> if the end of the stream is reached. + * @exception IOException + * if an I/O error occurs. + * @see DelegatingInputStream#in + */ + @Override + public int read() throws IOException + { + return in.read(); + } + + /** + * Skips over and discards <code>n</code> bytes of data from the input stream. The <code>skip</code> method may, for a + * variety of reasons, end up skipping over some smaller number of bytes, possibly <code>0</code>. The actual number + * of bytes skipped is returned. + * <p> + * This method simply performs <code>in.skip(n)</code>. + * + * @param n + * the number of bytes to be skipped. + * @return the actual number of bytes skipped. + * @exception IOException + * if an I/O error occurs. + */ + @Override + public long skip(long n) throws IOException + { + return in.skip(n); + } + + /** + * Returns the number of bytes that can be read from this input stream without blocking. + * <p> + * This method simply performs <code>in.available()</code> and returns the result. + * + * @return the number of bytes that can be read from the input stream without blocking. + * @exception IOException + * if an I/O error occurs. + * @see DelegatingInputStream#in + */ + @Override + public int available() throws IOException + { + return in.available(); + } + + /** + * Closes this input stream and releases any system resources associated with the stream. This method simply performs + * <code>in.close()</code>. + * + * @exception IOException + * if an I/O error occurs. + * @see DelegatingInputStream#in + */ + @Override + public void close() throws IOException + { + in.close(); + } + + /** + * Marks the current position in this input stream. A subsequent call to the <code>reset</code> method repositions + * this stream at the last marked position so that subsequent reads re-read the same bytes. + * <p> + * The <code>readlimit</code> argument tells this input stream to allow that many bytes to be read before the mark + * position gets invalidated. + * <p> + * This method simply performs <code>in.mark(readlimit)</code>. + * + * @param readlimit + * the maximum limit of bytes that can be read before the mark position becomes invalid. + * @see DelegatingInputStream#in + * @see DelegatingInputStream#reset() + */ + @Override + public synchronized void mark(int readlimit) + { + in.mark(readlimit); + } + + /** + * Repositions this stream to the position at the time the <code>mark</code> method was last called on this input + * stream. + * <p> + * This method simply performs <code>in.reset()</code>. + * <p> + * Stream marks are intended to be used in situations where you need to read ahead a little to see what's in the + * stream. Often this is most easily done by invoking some general parser. If the stream is of the type handled by the + * parse, it just chugs along happily. If the stream is not of that type, the parser should toss an exception when it + * fails. If this happens within readlimit bytes, it allows the outer code to reset the stream and try another parser. + * + * @exception IOException + * if the stream has not been marked or if the mark has been invalidated. + * @see DelegatingInputStream#in + * @see DelegatingInputStream#mark(int) + */ + @Override + public synchronized void reset() throws IOException + { + in.reset(); + } + + /** + * Tests if this input stream supports the <code>mark</code> and <code>reset</code> methods. This method simply + * performs <code>in.markSupported()</code>. + * + * @return <code>true</code> if this stream type supports the <code>mark</code> and <code>reset</code> method; + * <code>false</code> otherwise. + * @see DelegatingInputStream#in + * @see java.io.InputStream#mark(int) + * @see java.io.InputStream#reset() + */ + @Override + public boolean markSupported() + { + return in.markSupported(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java index 709f630057..df9a05d6ca 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingOutputStream.java @@ -1,114 +1,114 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * This class is the superclass of all classes that filter output streams. These streams sit on top of an already
- * existing output stream (the <i>underlying</i> output stream) which it uses as its basic sink of data, but possibly
- * transforming the data along the way or providing additional functionality.
- * <p>
- * The class <code>DelegatingOutputStream</code> itself simply overrides all methods of <code>OutputStream</code> with
- * versions that pass all requests to the underlying output stream. Subclasses of <code>DelegatingOutputStream</code>
- * may further override some of these methods as well as provide additional methods and fields.
- * <p>
- * <b>Note:</b> The only difference to {@link java.io.FilterOutputStream} is that <code>DelegatingOutputStream</code>
- * does <b>not</b> override {@link #write(byte[])} or {@link #write(byte[], int, int)} but rather exposes the original
- * implementations of <code>InputStream</code> which call {@link #write(int)} instead of their delegate counterparts.
- *
- * @author Eike Stepper
- */
-public class DelegatingOutputStream extends OutputStream
-{
- /**
- * The underlying output stream to be filtered.
- */
- protected OutputStream out;
-
- /**
- * Creates an output stream filter built on top of the specified underlying output stream.
- *
- * @param out
- * the underlying output stream to be assigned to the field <tt>this.out</tt> for later use, or
- * <code>null</code> if this instance is to be created without an underlying stream.
- */
- public DelegatingOutputStream(OutputStream out)
- {
- this.out = out;
- }
-
- public OutputStream getDelegate()
- {
- return out;
- }
-
- /**
- * Writes the specified <code>byte</code> to this output stream.
- * <p>
- * The <code>write</code> method of <code>DelegatingOutputStream</code> calls the <code>write</code> method of its
- * underlying output stream, that is, it performs <tt>out.write(b)</tt>.
- * <p>
- * Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>.
- *
- * @param b
- * the <code>byte</code>.
- * @exception IOException
- * if an I/O error occurs.
- */
- @Override
- public void write(int b) throws IOException
- {
- out.write(b);
- }
-
- /**
- * Flushes this output stream and forces any buffered output bytes to be written out to the stream.
- * <p>
- * The <code>flush</code> method of <code>DelegatingOutputStream</code> calls the <code>flush</code> method of its
- * underlying output stream.
- *
- * @exception IOException
- * if an I/O error occurs.
- * @see DelegatingOutputStream#out
- */
- @Override
- public void flush() throws IOException
- {
- out.flush();
- }
-
- /**
- * Closes this output stream and releases any system resources associated with the stream.
- * <p>
- * The <code>close</code> method of <code>DelegatingOutputStream</code> calls its <code>flush</code> method, and then
- * calls the <code>close</code> method of its underlying output stream.
- *
- * @exception IOException
- * if an I/O error occurs.
- * @see DelegatingOutputStream#flush()
- * @see DelegatingOutputStream#out
- */
- @Override
- public void close() throws IOException
- {
- try
- {
- flush();
- }
- catch (IOException ignored)
- {
- }
-
- out.close();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * This class is the superclass of all classes that filter output streams. These streams sit on top of an already + * existing output stream (the <i>underlying</i> output stream) which it uses as its basic sink of data, but possibly + * transforming the data along the way or providing additional functionality. + * <p> + * The class <code>DelegatingOutputStream</code> itself simply overrides all methods of <code>OutputStream</code> with + * versions that pass all requests to the underlying output stream. Subclasses of <code>DelegatingOutputStream</code> + * may further override some of these methods as well as provide additional methods and fields. + * <p> + * <b>Note:</b> The only difference to {@link java.io.FilterOutputStream} is that <code>DelegatingOutputStream</code> + * does <b>not</b> override {@link #write(byte[])} or {@link #write(byte[], int, int)} but rather exposes the original + * implementations of <code>InputStream</code> which call {@link #write(int)} instead of their delegate counterparts. + * + * @author Eike Stepper + */ +public class DelegatingOutputStream extends OutputStream +{ + /** + * The underlying output stream to be filtered. + */ + protected OutputStream out; + + /** + * Creates an output stream filter built on top of the specified underlying output stream. + * + * @param out + * the underlying output stream to be assigned to the field <tt>this.out</tt> for later use, or + * <code>null</code> if this instance is to be created without an underlying stream. + */ + public DelegatingOutputStream(OutputStream out) + { + this.out = out; + } + + public OutputStream getDelegate() + { + return out; + } + + /** + * Writes the specified <code>byte</code> to this output stream. + * <p> + * The <code>write</code> method of <code>DelegatingOutputStream</code> calls the <code>write</code> method of its + * underlying output stream, that is, it performs <tt>out.write(b)</tt>. + * <p> + * Implements the abstract <tt>write</tt> method of <tt>OutputStream</tt>. + * + * @param b + * the <code>byte</code>. + * @exception IOException + * if an I/O error occurs. + */ + @Override + public void write(int b) throws IOException + { + out.write(b); + } + + /** + * Flushes this output stream and forces any buffered output bytes to be written out to the stream. + * <p> + * The <code>flush</code> method of <code>DelegatingOutputStream</code> calls the <code>flush</code> method of its + * underlying output stream. + * + * @exception IOException + * if an I/O error occurs. + * @see DelegatingOutputStream#out + */ + @Override + public void flush() throws IOException + { + out.flush(); + } + + /** + * Closes this output stream and releases any system resources associated with the stream. + * <p> + * The <code>close</code> method of <code>DelegatingOutputStream</code> calls its <code>flush</code> method, and then + * calls the <code>close</code> method of its underlying output stream. + * + * @exception IOException + * if an I/O error occurs. + * @see DelegatingOutputStream#flush() + * @see DelegatingOutputStream#out + */ + @Override + public void close() throws IOException + { + try + { + flush(); + } + catch (IOException ignored) + { + } + + out.close(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java index 7147cd7924..f91bae9a13 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DelegatingStreamWrapper.java @@ -1,63 +1,63 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public abstract class DelegatingStreamWrapper implements IStreamWrapper
-{
- private IStreamWrapper delegate;
-
- public DelegatingStreamWrapper(IStreamWrapper delegate)
- {
- this.delegate = delegate;
- }
-
- public IStreamWrapper getDelegate()
- {
- return delegate;
- }
-
- public InputStream wrapInputStream(InputStream in) throws IOException
- {
- return doWrapInputStream(delegate.wrapInputStream(in));
- }
-
- public OutputStream wrapOutputStream(OutputStream out) throws IOException
- {
- return doWrapOutputStream(delegate.wrapOutputStream(out));
- }
-
- public void finishInputStream(InputStream in) throws IOException
- {
- delegate.finishInputStream(in);
- doFinishInputStream(in);
- }
-
- public void finishOutputStream(OutputStream out) throws IOException
- {
- delegate.finishOutputStream(out);
- doFinishOutputStream(out);
- }
-
- protected abstract InputStream doWrapInputStream(InputStream in) throws IOException;
-
- protected abstract OutputStream doWrapOutputStream(OutputStream out) throws IOException;
-
- protected abstract void doFinishInputStream(InputStream in) throws IOException;
-
- protected abstract void doFinishOutputStream(OutputStream out) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public abstract class DelegatingStreamWrapper implements IStreamWrapper +{ + private IStreamWrapper delegate; + + public DelegatingStreamWrapper(IStreamWrapper delegate) + { + this.delegate = delegate; + } + + public IStreamWrapper getDelegate() + { + return delegate; + } + + public InputStream wrapInputStream(InputStream in) throws IOException + { + return doWrapInputStream(delegate.wrapInputStream(in)); + } + + public OutputStream wrapOutputStream(OutputStream out) throws IOException + { + return doWrapOutputStream(delegate.wrapOutputStream(out)); + } + + public void finishInputStream(InputStream in) throws IOException + { + delegate.finishInputStream(in); + doFinishInputStream(in); + } + + public void finishOutputStream(OutputStream out) throws IOException + { + delegate.finishOutputStream(out); + doFinishOutputStream(out); + } + + protected abstract InputStream doWrapInputStream(InputStream in) throws IOException; + + protected abstract OutputStream doWrapOutputStream(OutputStream out) throws IOException; + + protected abstract void doFinishInputStream(InputStream in) throws IOException; + + protected abstract void doFinishOutputStream(OutputStream out) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java index f6c1f324a6..143c3ddf2a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/DigestWriter.java @@ -1,135 +1,135 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.FilterWriter;
-import java.io.IOException;
-import java.io.Writer;
-import java.security.MessageDigest;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public class DigestWriter extends FilterWriter
-{
- private boolean on = true;
-
- /**
- * The message digest associated with this stream.
- */
- protected MessageDigest digest;
-
- /**
- * Creates a digest writer, using the specified writer and message digest.
- *
- * @param writer
- * the writer.
- * @param digest
- * the message digest to associate with this writer.
- */
- public DigestWriter(Writer writer, MessageDigest digest)
- {
- super(writer);
- setMessageDigest(digest);
- }
-
- /**
- * Returns the message digest associated with this writer.
- *
- * @return the message digest associated with this writer.
- * @see #setMessageDigest(java.security.MessageDigest)
- */
- public MessageDigest getMessageDigest()
- {
- return digest;
- }
-
- /**
- * Associates the specified message digest with this writer.
- *
- * @param digest
- * the message digest to be associated with this writer.
- * @see #getMessageDigest()
- */
- public void setMessageDigest(MessageDigest digest)
- {
- this.digest = digest;
- }
-
- @Override
- public void write(int c) throws IOException
- {
- if (on)
- {
- updateDigest(c);
- }
-
- out.write(c);
- }
-
- @Override
- public void write(char cbuf[], int off, int len) throws IOException
- {
- if (on)
- {
- int end = off + len;
- for (int i = off; i < end; i++)
- {
- updateDigest(cbuf[i]);
- }
- }
-
- out.write(cbuf, off, len);
- }
-
- @Override
- public void write(String str, int off, int len) throws IOException
- {
- if (on)
- {
- int end = off + len;
- for (int i = off; i < end; i++)
- {
- updateDigest(str.charAt(i));
- }
- }
-
- out.write(str, off, len);
- }
-
- private void updateDigest(int c)
- {
- digest.update((byte)(c >>> 8 & 0xFF));
- digest.update((byte)(c >>> 0 & 0xFF));
- }
-
- /**
- * Turns the digest function on or off. The default is on. When it is on, a call to one of the <code>write</code>
- * methods results in an update on the message digest. But when it is off, the message digest is not updated.
- *
- * @param on
- * true to turn the digest function on, false to turn it off.
- */
- public void on(boolean on)
- {
- this.on = on;
- }
-
- /**
- * Prints a string representation of this digest output stream and its associated message digest object.
- */
- @Override
- public String toString()
- {
- return "[Digest Writer] " + digest.toString();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.FilterWriter; +import java.io.IOException; +import java.io.Writer; +import java.security.MessageDigest; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public class DigestWriter extends FilterWriter +{ + private boolean on = true; + + /** + * The message digest associated with this stream. + */ + protected MessageDigest digest; + + /** + * Creates a digest writer, using the specified writer and message digest. + * + * @param writer + * the writer. + * @param digest + * the message digest to associate with this writer. + */ + public DigestWriter(Writer writer, MessageDigest digest) + { + super(writer); + setMessageDigest(digest); + } + + /** + * Returns the message digest associated with this writer. + * + * @return the message digest associated with this writer. + * @see #setMessageDigest(java.security.MessageDigest) + */ + public MessageDigest getMessageDigest() + { + return digest; + } + + /** + * Associates the specified message digest with this writer. + * + * @param digest + * the message digest to be associated with this writer. + * @see #getMessageDigest() + */ + public void setMessageDigest(MessageDigest digest) + { + this.digest = digest; + } + + @Override + public void write(int c) throws IOException + { + if (on) + { + updateDigest(c); + } + + out.write(c); + } + + @Override + public void write(char cbuf[], int off, int len) throws IOException + { + if (on) + { + int end = off + len; + for (int i = off; i < end; i++) + { + updateDigest(cbuf[i]); + } + } + + out.write(cbuf, off, len); + } + + @Override + public void write(String str, int off, int len) throws IOException + { + if (on) + { + int end = off + len; + for (int i = off; i < end; i++) + { + updateDigest(str.charAt(i)); + } + } + + out.write(str, off, len); + } + + private void updateDigest(int c) + { + digest.update((byte)(c >>> 8 & 0xFF)); + digest.update((byte)(c >>> 0 & 0xFF)); + } + + /** + * Turns the digest function on or off. The default is on. When it is on, a call to one of the <code>write</code> + * methods results in an update on the message digest. But when it is off, the message digest is not updated. + * + * @param on + * true to turn the digest function on, false to turn it off. + */ + public void on(boolean on) + { + this.on = on; + } + + /** + * Prints a string representation of this digest output stream and its associated message digest object. + */ + @Override + public String toString() + { + return "[Digest Writer] " + digest.toString(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java index d8ded5810d..cb22f2059b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileInputStream.java @@ -1,120 +1,120 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public class ExpectedFileInputStream extends FileInputStream
-{
- private long timeout = IOUtil.DEFAULT_TIMEOUT;
-
- private File file;
-
- private long expectedSize;
-
- private long pos;
-
- public ExpectedFileInputStream(File file, long expectedSize) throws FileNotFoundException
- {
- super(file);
- this.file = file;
- this.expectedSize = expectedSize;
- }
-
- public long getTimeout()
- {
- return timeout;
- }
-
- public void setTimeout(long timeout)
- {
- this.timeout = timeout;
- }
-
- @Override
- public long skip(long n) throws IOException
- {
- waitForInput(n);
- return super.skip(n);
- }
-
- @Override
- public int read() throws IOException
- {
- waitForInput(1L);
- return super.read();
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException
- {
- waitForInput(len);
- return super.read(b, off, len);
- }
-
- @Override
- public int read(byte[] b) throws IOException
- {
- return read(b, 0, b.length);
- }
-
- private void waitForInput(long n) throws IOException
- {
- synchronized (this)
- {
- n = Math.min(n, expectedSize - pos);
- long restSize = file.length() - pos;
- long endTime = 0;
-
- while (restSize < n)
- {
- long restTime;
- if (endTime == 0)
- {
- endTime = System.currentTimeMillis() + timeout;
- restTime = timeout;
- }
- else
- {
- restTime = endTime - System.currentTimeMillis();
- }
-
- if (restTime <= 0)
- {
- throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath());
- }
-
- try
- {
- wait(Math.min(100L, restTime));
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
-
- restSize = file.length() - pos;
- }
-
- pos += n;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public class ExpectedFileInputStream extends FileInputStream +{ + private long timeout = IOUtil.DEFAULT_TIMEOUT; + + private File file; + + private long expectedSize; + + private long pos; + + public ExpectedFileInputStream(File file, long expectedSize) throws FileNotFoundException + { + super(file); + this.file = file; + this.expectedSize = expectedSize; + } + + public long getTimeout() + { + return timeout; + } + + public void setTimeout(long timeout) + { + this.timeout = timeout; + } + + @Override + public long skip(long n) throws IOException + { + waitForInput(n); + return super.skip(n); + } + + @Override + public int read() throws IOException + { + waitForInput(1L); + return super.read(); + } + + @Override + public int read(byte[] b, int off, int len) throws IOException + { + waitForInput(len); + return super.read(b, off, len); + } + + @Override + public int read(byte[] b) throws IOException + { + return read(b, 0, b.length); + } + + private void waitForInput(long n) throws IOException + { + synchronized (this) + { + n = Math.min(n, expectedSize - pos); + long restSize = file.length() - pos; + long endTime = 0; + + while (restSize < n) + { + long restTime; + if (endTime == 0) + { + endTime = System.currentTimeMillis() + timeout; + restTime = timeout; + } + else + { + restTime = endTime - System.currentTimeMillis(); + } + + if (restTime <= 0) + { + throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath()); + } + + try + { + wait(Math.min(100L, restTime)); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + + restSize = file.length() - pos; + } + + pos += n; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java index 7692feab8d..eaf11fa514 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExpectedFileReader.java @@ -1,129 +1,129 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.nio.CharBuffer;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public class ExpectedFileReader extends FileReader
-{
- private long timeout = IOUtil.DEFAULT_TIMEOUT;
-
- private File file;
-
- private long expectedSize;
-
- private long pos;
-
- public ExpectedFileReader(File file, long expectedSize) throws FileNotFoundException
- {
- super(file);
- this.file = file;
- this.expectedSize = expectedSize;
- }
-
- public long getTimeout()
- {
- return timeout;
- }
-
- public void setTimeout(long timeout)
- {
- this.timeout = timeout;
- }
-
- @Override
- public long skip(long n) throws IOException
- {
- waitForInput(n);
- return super.skip(n);
- }
-
- @Override
- public int read() throws IOException
- {
- waitForInput(1L);
- return super.read();
- }
-
- @Override
- public int read(char[] cbuf, int offset, int length) throws IOException
- {
- waitForInput(length);
- return super.read(cbuf, offset, length);
- }
-
- @Override
- public int read(CharBuffer target) throws IOException
- {
- waitForInput(target.remaining());
- return super.read(target);
- }
-
- @Override
- public int read(char[] cbuf) throws IOException
- {
- waitForInput(cbuf.length);
- return super.read(cbuf);
- }
-
- private void waitForInput(long n) throws IOException
- {
- synchronized (this)
- {
- n = Math.min(n, expectedSize - pos);
- long restSize = file.length() - pos;
- long endTime = 0;
-
- while (restSize < n)
- {
- long restTime;
- if (endTime == 0)
- {
- endTime = System.currentTimeMillis() + timeout;
- restTime = timeout;
- }
- else
- {
- restTime = endTime - System.currentTimeMillis();
- }
-
- if (restTime <= 0)
- {
- throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath());
- }
-
- try
- {
- wait(Math.max(100L, restTime));
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
-
- restSize = file.length() - pos;
- }
-
- pos += n;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.CharBuffer; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public class ExpectedFileReader extends FileReader +{ + private long timeout = IOUtil.DEFAULT_TIMEOUT; + + private File file; + + private long expectedSize; + + private long pos; + + public ExpectedFileReader(File file, long expectedSize) throws FileNotFoundException + { + super(file); + this.file = file; + this.expectedSize = expectedSize; + } + + public long getTimeout() + { + return timeout; + } + + public void setTimeout(long timeout) + { + this.timeout = timeout; + } + + @Override + public long skip(long n) throws IOException + { + waitForInput(n); + return super.skip(n); + } + + @Override + public int read() throws IOException + { + waitForInput(1L); + return super.read(); + } + + @Override + public int read(char[] cbuf, int offset, int length) throws IOException + { + waitForInput(length); + return super.read(cbuf, offset, length); + } + + @Override + public int read(CharBuffer target) throws IOException + { + waitForInput(target.remaining()); + return super.read(target); + } + + @Override + public int read(char[] cbuf) throws IOException + { + waitForInput(cbuf.length); + return super.read(cbuf); + } + + private void waitForInput(long n) throws IOException + { + synchronized (this) + { + n = Math.min(n, expectedSize - pos); + long restSize = file.length() - pos; + long endTime = 0; + + while (restSize < n) + { + long restTime; + if (endTime == 0) + { + endTime = System.currentTimeMillis() + timeout; + restTime = timeout; + } + else + { + restTime = endTime - System.currentTimeMillis(); + } + + if (restTime <= 0) + { + throw new TimeoutRuntimeException("Timeout while reading from " + file.getAbsolutePath()); + } + + try + { + wait(Math.max(100L, restTime)); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + + restSize = file.length() - pos; + } + + pos += n; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java index e2384fe9fb..c382284c49 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInput.java @@ -1,198 +1,198 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver;
-
-import java.io.DataInput;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * @author Eike Stepper
- */
-public interface ExtendedDataInput extends DataInput
-{
- public byte[] readByteArray() throws IOException;
-
- public Object readObject() throws IOException;
-
- public Object readObject(ClassLoader classLoader) throws IOException;
-
- public Object readObject(ClassResolver classResolver) throws IOException;
-
- public String readString() throws IOException;
-
- /**
- * @since 3.0
- */
- public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException;
-
- /**
- * @author Eike Stepper
- * @since 2.0
- */
- public static class Delegating implements ExtendedDataInput
- {
- private ExtendedDataInput delegate;
-
- public Delegating(ExtendedDataInput delegate)
- {
- this.delegate = delegate;
- }
-
- public ExtendedDataInput getDelegate()
- {
- return delegate;
- }
-
- public boolean readBoolean() throws IOException
- {
- return delegate.readBoolean();
- }
-
- public byte readByte() throws IOException
- {
- return delegate.readByte();
- }
-
- public byte[] readByteArray() throws IOException
- {
- return delegate.readByteArray();
- }
-
- public char readChar() throws IOException
- {
- return delegate.readChar();
- }
-
- public double readDouble() throws IOException
- {
- return delegate.readDouble();
- }
-
- public float readFloat() throws IOException
- {
- return delegate.readFloat();
- }
-
- public void readFully(byte[] b, int off, int len) throws IOException
- {
- delegate.readFully(b, off, len);
- }
-
- public void readFully(byte[] b) throws IOException
- {
- delegate.readFully(b);
- }
-
- public int readInt() throws IOException
- {
- return delegate.readInt();
- }
-
- public String readLine() throws IOException
- {
- return delegate.readLine();
- }
-
- public long readLong() throws IOException
- {
- return delegate.readLong();
- }
-
- public Object readObject() throws IOException
- {
- return delegate.readObject();
- }
-
- public Object readObject(ClassLoader classLoader) throws IOException
- {
- return delegate.readObject(classLoader);
- }
-
- public Object readObject(ClassResolver classResolver) throws IOException
- {
- return delegate.readObject(classResolver);
- }
-
- public short readShort() throws IOException
- {
- return delegate.readShort();
- }
-
- public String readString() throws IOException
- {
- return delegate.readString();
- }
-
- /**
- * @since 3.0
- */
- public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException
- {
- return delegate.readEnum(type);
- }
-
- public int readUnsignedByte() throws IOException
- {
- return delegate.readUnsignedByte();
- }
-
- public int readUnsignedShort() throws IOException
- {
- return delegate.readUnsignedShort();
- }
-
- public String readUTF() throws IOException
- {
- return delegate.readUTF();
- }
-
- public int skipBytes(int n) throws IOException
- {
- return delegate.skipBytes(n);
- }
- }
-
- /**
- * @author Eike Stepper
- * @since 2.0
- */
- public static class Stream extends InputStream
- {
- private ExtendedDataInput delegate;
-
- public Stream(ExtendedDataInput delegate)
- {
- this.delegate = delegate;
- }
-
- public ExtendedDataInput getDelegate()
- {
- return delegate;
- }
-
- @Override
- public int read() throws IOException
- {
- try
- {
- return delegate.readUnsignedByte();
- }
- catch (EOFException ex)
- {
- return -1;
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver; + +import java.io.DataInput; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; + +/** + * @author Eike Stepper + */ +public interface ExtendedDataInput extends DataInput +{ + public byte[] readByteArray() throws IOException; + + public Object readObject() throws IOException; + + public Object readObject(ClassLoader classLoader) throws IOException; + + public Object readObject(ClassResolver classResolver) throws IOException; + + public String readString() throws IOException; + + /** + * @since 3.0 + */ + public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException; + + /** + * @author Eike Stepper + * @since 2.0 + */ + public static class Delegating implements ExtendedDataInput + { + private ExtendedDataInput delegate; + + public Delegating(ExtendedDataInput delegate) + { + this.delegate = delegate; + } + + public ExtendedDataInput getDelegate() + { + return delegate; + } + + public boolean readBoolean() throws IOException + { + return delegate.readBoolean(); + } + + public byte readByte() throws IOException + { + return delegate.readByte(); + } + + public byte[] readByteArray() throws IOException + { + return delegate.readByteArray(); + } + + public char readChar() throws IOException + { + return delegate.readChar(); + } + + public double readDouble() throws IOException + { + return delegate.readDouble(); + } + + public float readFloat() throws IOException + { + return delegate.readFloat(); + } + + public void readFully(byte[] b, int off, int len) throws IOException + { + delegate.readFully(b, off, len); + } + + public void readFully(byte[] b) throws IOException + { + delegate.readFully(b); + } + + public int readInt() throws IOException + { + return delegate.readInt(); + } + + public String readLine() throws IOException + { + return delegate.readLine(); + } + + public long readLong() throws IOException + { + return delegate.readLong(); + } + + public Object readObject() throws IOException + { + return delegate.readObject(); + } + + public Object readObject(ClassLoader classLoader) throws IOException + { + return delegate.readObject(classLoader); + } + + public Object readObject(ClassResolver classResolver) throws IOException + { + return delegate.readObject(classResolver); + } + + public short readShort() throws IOException + { + return delegate.readShort(); + } + + public String readString() throws IOException + { + return delegate.readString(); + } + + /** + * @since 3.0 + */ + public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException + { + return delegate.readEnum(type); + } + + public int readUnsignedByte() throws IOException + { + return delegate.readUnsignedByte(); + } + + public int readUnsignedShort() throws IOException + { + return delegate.readUnsignedShort(); + } + + public String readUTF() throws IOException + { + return delegate.readUTF(); + } + + public int skipBytes(int n) throws IOException + { + return delegate.skipBytes(n); + } + } + + /** + * @author Eike Stepper + * @since 2.0 + */ + public static class Stream extends InputStream + { + private ExtendedDataInput delegate; + + public Stream(ExtendedDataInput delegate) + { + this.delegate = delegate; + } + + public ExtendedDataInput getDelegate() + { + return delegate; + } + + @Override + public int read() throws IOException + { + try + { + return delegate.readUnsignedByte(); + } + catch (EOFException ex) + { + return -1; + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java index 1f9b61a241..2368076845 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataInputStream.java @@ -1,81 +1,81 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver;
-
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * @author Eike Stepper
- */
-public class ExtendedDataInputStream extends DataInputStream implements ExtendedDataInput
-{
- public ExtendedDataInputStream(InputStream in)
- {
- super(in);
- }
-
- public byte[] readByteArray() throws IOException
- {
- return ExtendedIOUtil.readByteArray(this);
- }
-
- public String readString() throws IOException
- {
- return ExtendedIOUtil.readString(this);
- }
-
- public Object readObject() throws IOException
- {
- return ExtendedIOUtil.readObject(this);
- }
-
- /**
- * @since 3.0
- */
- public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException
- {
- return ExtendedIOUtil.readEnum(this, type);
- }
-
- public Object readObject(ClassLoader classLoader) throws IOException
- {
- return ExtendedIOUtil.readObject(this, classLoader);
- }
-
- public Object readObject(ClassResolver classResolver) throws IOException
- {
- return ExtendedIOUtil.readObject(this, classResolver);
- }
-
- public static ExtendedDataInputStream wrap(InputStream stream)
- {
- if (stream instanceof ExtendedDataInputStream)
- {
- return (ExtendedDataInputStream)stream;
- }
-
- return new ExtendedDataInputStream(stream);
- }
-
- public static InputStream unwrap(InputStream stream)
- {
- if (stream instanceof ExtendedDataInputStream)
- {
- return ((ExtendedDataInputStream)stream).in;
- }
-
- return stream;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.io.ExtendedIOUtil.ClassResolver; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * @author Eike Stepper + */ +public class ExtendedDataInputStream extends DataInputStream implements ExtendedDataInput +{ + public ExtendedDataInputStream(InputStream in) + { + super(in); + } + + public byte[] readByteArray() throws IOException + { + return ExtendedIOUtil.readByteArray(this); + } + + public String readString() throws IOException + { + return ExtendedIOUtil.readString(this); + } + + public Object readObject() throws IOException + { + return ExtendedIOUtil.readObject(this); + } + + /** + * @since 3.0 + */ + public <T extends Enum<?>> T readEnum(Class<T> type) throws IOException + { + return ExtendedIOUtil.readEnum(this, type); + } + + public Object readObject(ClassLoader classLoader) throws IOException + { + return ExtendedIOUtil.readObject(this, classLoader); + } + + public Object readObject(ClassResolver classResolver) throws IOException + { + return ExtendedIOUtil.readObject(this, classResolver); + } + + public static ExtendedDataInputStream wrap(InputStream stream) + { + if (stream instanceof ExtendedDataInputStream) + { + return (ExtendedDataInputStream)stream; + } + + return new ExtendedDataInputStream(stream); + } + + public static InputStream unwrap(InputStream stream) + { + if (stream instanceof ExtendedDataInputStream) + { + return ((ExtendedDataInputStream)stream).in; + } + + return stream; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java index 7b6feaa3e5..98383b6882 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutput.java @@ -1,169 +1,169 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.DataOutput;
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public interface ExtendedDataOutput extends DataOutput
-{
- public void writeByteArray(byte[] b) throws IOException;
-
- public void writeObject(Object object) throws IOException;
-
- public void writeString(String str) throws IOException;
-
- /**
- * @since 3.0
- */
- public void writeEnum(Enum<?> literal) throws IOException;
-
- /**
- * @author Eike Stepper
- * @since 2.0
- */
- public static class Delegating implements ExtendedDataOutput
- {
- private ExtendedDataOutput delegate;
-
- public Delegating(ExtendedDataOutput delegate)
- {
- this.delegate = delegate;
- }
-
- public ExtendedDataOutput getDelegate()
- {
- return delegate;
- }
-
- public void write(byte[] b, int off, int len) throws IOException
- {
- delegate.write(b, off, len);
- }
-
- public void write(byte[] b) throws IOException
- {
- delegate.write(b);
- }
-
- public void write(int b) throws IOException
- {
- delegate.write(b);
- }
-
- public void writeBoolean(boolean v) throws IOException
- {
- delegate.writeBoolean(v);
- }
-
- public void writeByte(int v) throws IOException
- {
- delegate.writeByte(v);
- }
-
- public void writeByteArray(byte[] b) throws IOException
- {
- delegate.writeByteArray(b);
- }
-
- public void writeBytes(String s) throws IOException
- {
- delegate.writeBytes(s);
- }
-
- public void writeChar(int v) throws IOException
- {
- delegate.writeChar(v);
- }
-
- public void writeChars(String s) throws IOException
- {
- delegate.writeChars(s);
- }
-
- public void writeDouble(double v) throws IOException
- {
- delegate.writeDouble(v);
- }
-
- public void writeFloat(float v) throws IOException
- {
- delegate.writeFloat(v);
- }
-
- public void writeInt(int v) throws IOException
- {
- delegate.writeInt(v);
- }
-
- public void writeLong(long v) throws IOException
- {
- delegate.writeLong(v);
- }
-
- public void writeObject(Object object) throws IOException
- {
- delegate.writeObject(object);
- }
-
- public void writeShort(int v) throws IOException
- {
- delegate.writeShort(v);
- }
-
- public void writeString(String str) throws IOException
- {
- delegate.writeString(str);
- }
-
- /**
- * @since 3.0
- */
- public void writeEnum(Enum<?> literal) throws IOException
- {
- delegate.writeEnum(literal);
- }
-
- public void writeUTF(String str) throws IOException
- {
- delegate.writeUTF(str);
- }
- }
-
- /**
- * @author Eike Stepper
- * @since 2.0
- */
- public static class Stream extends OutputStream
- {
- private ExtendedDataOutput delegate;
-
- public Stream(ExtendedDataOutput delegate)
- {
- this.delegate = delegate;
- }
-
- public ExtendedDataOutput getDelegate()
- {
- return delegate;
- }
-
- @Override
- public void write(int b) throws IOException
- {
- delegate.write(b);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.DataOutput; +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public interface ExtendedDataOutput extends DataOutput +{ + public void writeByteArray(byte[] b) throws IOException; + + public void writeObject(Object object) throws IOException; + + public void writeString(String str) throws IOException; + + /** + * @since 3.0 + */ + public void writeEnum(Enum<?> literal) throws IOException; + + /** + * @author Eike Stepper + * @since 2.0 + */ + public static class Delegating implements ExtendedDataOutput + { + private ExtendedDataOutput delegate; + + public Delegating(ExtendedDataOutput delegate) + { + this.delegate = delegate; + } + + public ExtendedDataOutput getDelegate() + { + return delegate; + } + + public void write(byte[] b, int off, int len) throws IOException + { + delegate.write(b, off, len); + } + + public void write(byte[] b) throws IOException + { + delegate.write(b); + } + + public void write(int b) throws IOException + { + delegate.write(b); + } + + public void writeBoolean(boolean v) throws IOException + { + delegate.writeBoolean(v); + } + + public void writeByte(int v) throws IOException + { + delegate.writeByte(v); + } + + public void writeByteArray(byte[] b) throws IOException + { + delegate.writeByteArray(b); + } + + public void writeBytes(String s) throws IOException + { + delegate.writeBytes(s); + } + + public void writeChar(int v) throws IOException + { + delegate.writeChar(v); + } + + public void writeChars(String s) throws IOException + { + delegate.writeChars(s); + } + + public void writeDouble(double v) throws IOException + { + delegate.writeDouble(v); + } + + public void writeFloat(float v) throws IOException + { + delegate.writeFloat(v); + } + + public void writeInt(int v) throws IOException + { + delegate.writeInt(v); + } + + public void writeLong(long v) throws IOException + { + delegate.writeLong(v); + } + + public void writeObject(Object object) throws IOException + { + delegate.writeObject(object); + } + + public void writeShort(int v) throws IOException + { + delegate.writeShort(v); + } + + public void writeString(String str) throws IOException + { + delegate.writeString(str); + } + + /** + * @since 3.0 + */ + public void writeEnum(Enum<?> literal) throws IOException + { + delegate.writeEnum(literal); + } + + public void writeUTF(String str) throws IOException + { + delegate.writeUTF(str); + } + } + + /** + * @author Eike Stepper + * @since 2.0 + */ + public static class Stream extends OutputStream + { + private ExtendedDataOutput delegate; + + public Stream(ExtendedDataOutput delegate) + { + this.delegate = delegate; + } + + public ExtendedDataOutput getDelegate() + { + return delegate; + } + + @Override + public void write(int b) throws IOException + { + delegate.write(b); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java index df8d5ec590..6d924e2b9b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedDataOutputStream.java @@ -1,69 +1,69 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public class ExtendedDataOutputStream extends DataOutputStream implements ExtendedDataOutput
-{
- public ExtendedDataOutputStream(OutputStream out)
- {
- super(out);
- }
-
- public void writeByteArray(byte[] b) throws IOException
- {
- ExtendedIOUtil.writeByteArray(this, b);
- }
-
- public void writeString(String str) throws IOException
- {
- ExtendedIOUtil.writeString(this, str);
- }
-
- /**
- * @since 3.0
- */
- public void writeEnum(Enum<?> literal) throws IOException
- {
- ExtendedIOUtil.writeEnum(this, literal);
- }
-
- public void writeObject(Object object) throws IOException
- {
- ExtendedIOUtil.writeObject(this, object);
- }
-
- public static ExtendedDataOutputStream wrap(OutputStream stream)
- {
- if (stream instanceof ExtendedDataOutputStream)
- {
- return (ExtendedDataOutputStream)stream;
- }
-
- return new ExtendedDataOutputStream(stream);
- }
-
- public static OutputStream unwrap(OutputStream stream)
- {
- if (stream instanceof ExtendedDataOutputStream)
- {
- return ((ExtendedDataOutputStream)stream).out;
- }
-
- return stream;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public class ExtendedDataOutputStream extends DataOutputStream implements ExtendedDataOutput +{ + public ExtendedDataOutputStream(OutputStream out) + { + super(out); + } + + public void writeByteArray(byte[] b) throws IOException + { + ExtendedIOUtil.writeByteArray(this, b); + } + + public void writeString(String str) throws IOException + { + ExtendedIOUtil.writeString(this, str); + } + + /** + * @since 3.0 + */ + public void writeEnum(Enum<?> literal) throws IOException + { + ExtendedIOUtil.writeEnum(this, literal); + } + + public void writeObject(Object object) throws IOException + { + ExtendedIOUtil.writeObject(this, object); + } + + public static ExtendedDataOutputStream wrap(OutputStream stream) + { + if (stream instanceof ExtendedDataOutputStream) + { + return (ExtendedDataOutputStream)stream; + } + + return new ExtendedDataOutputStream(stream); + } + + public static OutputStream unwrap(OutputStream stream) + { + if (stream instanceof ExtendedDataOutputStream) + { + return ((ExtendedDataOutputStream)stream).out; + } + + return stream; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java index d7d6e940e6..a65eeed94b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOAdapter.java @@ -1,32 +1,32 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class ExtendedIOAdapter implements ExtendedIOHandler
-{
- public ExtendedIOAdapter()
- {
- }
-
- public void handleIn(ExtendedDataInputStream in) throws IOException
- {
- }
-
- public void handleOut(ExtendedDataOutputStream out) throws IOException
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class ExtendedIOAdapter implements ExtendedIOHandler +{ + public ExtendedIOAdapter() + { + } + + public void handleIn(ExtendedDataInputStream in) throws IOException + { + } + + public void handleOut(ExtendedDataOutputStream out) throws IOException + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java index 398a395d66..b1de386966 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOHandler.java @@ -1,19 +1,19 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface ExtendedIOHandler extends ExtendedInputHandler, ExtendedOutputHandler
-{
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface ExtendedIOHandler extends ExtendedInputHandler, ExtendedOutputHandler +{ +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java index 70fa06290c..19dd8e26ab 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedIOUtil.java @@ -1,297 +1,297 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInput;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public final class ExtendedIOUtil
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ExtendedIOUtil.class);
-
- private static final int UTF_HEADER_SIZE = 2;
-
- private static final int MAX_16_BIT = (1 << 16) - 1;
-
- private static final int MAX_UTF_LENGTH = MAX_16_BIT - UTF_HEADER_SIZE;
-
- private static final int MAX_UTF_CHARS = MAX_UTF_LENGTH / 3;
-
- private static final int MAX_ENUM_LITERALS = Byte.MAX_VALUE - Byte.MIN_VALUE;
-
- private static final byte NO_ENUM_LITERAL = Byte.MIN_VALUE;
-
- private ExtendedIOUtil()
- {
- }
-
- public static void writeByteArray(DataOutput out, byte[] b) throws IOException
- {
- if (b != null)
- {
- out.writeInt(b.length);
- out.write(b);
- }
- else
- {
- out.writeInt(-1);
- }
- }
-
- public static byte[] readByteArray(DataInput in) throws IOException
- {
- int length = in.readInt();
- if (length < 0)
- {
- return null;
- }
-
- byte[] b;
- try
- {
- b = new byte[length];
- }
- catch (Throwable t)
- {
- throw new IOException("Unable to allocate " + length + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- in.readFully(b);
- return b;
- }
-
- public static void writeObject(final DataOutput out, Object object) throws IOException
- {
- ObjectOutput wrapper = null;
- if (out instanceof ObjectOutput)
- {
- wrapper = (ObjectOutput)out;
- }
- else
- {
- wrapper = new ObjectOutputStream(new OutputStream()
- {
- @Override
- public void write(int b) throws IOException
- {
- out.writeByte((b & 0xff) + Byte.MIN_VALUE);
- }
- });
- }
-
- wrapper.writeObject(object);
- }
-
- public static Object readObject(final DataInput in) throws IOException
- {
- return readObject(in, (ClassResolver)null);
- }
-
- public static Object readObject(final DataInput in, ClassLoader classLoader) throws IOException
- {
- return readObject(in, new ClassLoaderClassResolver(classLoader));
- }
-
- public static Object readObject(final DataInput in, final ClassResolver classResolver) throws IOException
- {
- ObjectInput wrapper = null;
- if (in instanceof ObjectInput)
- {
- wrapper = (ObjectInput)in;
- }
- else
- {
- wrapper = new ObjectInputStream(new InputStream()
- {
- @Override
- public int read() throws IOException
- {
- return in.readByte() - Byte.MIN_VALUE;
- }
- })
-
- {
- @Override
- protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException
- {
- if (classResolver != null)
- {
- if (TRACER.isEnabled())
- {
- TRACER.format("Deserializing class {0}", desc.getName()); //$NON-NLS-1$
- }
-
- Class<?> c = classResolver.resolveClass(desc);
- if (c != null)
- {
- return c;
- }
- }
-
- return super.resolveClass(desc);
- }
- };
- }
-
- try
- {
- return wrapper.readObject();
- }
- catch (ClassNotFoundException ex)
- {
- OM.LOG.error(ex);
- throw WrappedException.wrap(ex);
- }
- }
-
- public static void writeString(DataOutput out, String str) throws IOException
- {
- if (str != null)
- {
- int size = str.length();
- int start = 0;
- do
- {
- out.writeBoolean(true);
- int chunk = Math.min(size, MAX_UTF_CHARS);
- int end = start + chunk;
- out.writeUTF(str.substring(start, end));
- start = end;
- size -= chunk;
- } while (size > 0);
- }
-
- out.writeBoolean(false);
- }
-
- public static String readString(DataInput in) throws IOException
- {
- boolean more = in.readBoolean();
- if (!more)
- {
- return null;
- }
-
- StringBuilder builder = new StringBuilder();
- do
- {
- String chunk = in.readUTF();
- builder.append(chunk);
- more = in.readBoolean();
- } while (more);
-
- return builder.toString();
- }
-
- /**
- * @since 3.0
- */
- public static void writeEnum(DataOutput out, Enum<?> literal) throws IOException
- {
- if (literal == null)
- {
- out.writeByte(NO_ENUM_LITERAL);
- }
- else
- {
- getEnumLiterals(literal.getDeclaringClass()); // Check valid size
-
- int ordinal = literal.ordinal();
- out.writeByte(ordinal + Byte.MIN_VALUE + 1);
- }
- }
-
- /**
- * @since 3.0
- */
- public static <T extends Enum<?>> T readEnum(DataInput in, Class<T> type) throws IOException
- {
- T[] literals = getEnumLiterals(type);
-
- int ordinal = in.readByte();
- if (ordinal == NO_ENUM_LITERAL)
- {
- return null;
- }
-
- return literals[ordinal - Byte.MIN_VALUE - 1];
- }
-
- private static <T> T[] getEnumLiterals(Class<T> type)
- {
- T[] literals = type.getEnumConstants();
-
- int size = literals.length;
- if (size > MAX_ENUM_LITERALS)
- {
- throw new AssertionError("Enum too large: " + size + " literals");
- }
-
- return literals;
- }
-
- /**
- * @author Eike Stepper
- */
- public interface ClassResolver
- {
- public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException;
- }
-
- /**
- * @author Eike Stepper
- */
- public static class ClassLoaderClassResolver implements ClassResolver
- {
- private static final String STACK_TRACE_ELEMENT = StackTraceElement[].class.getName();
-
- private ClassLoader classLoader;
-
- public ClassLoaderClassResolver(ClassLoader classLoader)
- {
- this.classLoader = classLoader;
- }
-
- public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException
- {
- String className = v.getName();
-
- try
- {
- return classLoader.loadClass(className);
- }
- catch (ClassNotFoundException ex)
- {
- if (!STACK_TRACE_ELEMENT.equals(className))
- {
- OM.LOG.error(ex);
- }
-
- return null;
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public final class ExtendedIOUtil +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, ExtendedIOUtil.class); + + private static final int UTF_HEADER_SIZE = 2; + + private static final int MAX_16_BIT = (1 << 16) - 1; + + private static final int MAX_UTF_LENGTH = MAX_16_BIT - UTF_HEADER_SIZE; + + private static final int MAX_UTF_CHARS = MAX_UTF_LENGTH / 3; + + private static final int MAX_ENUM_LITERALS = Byte.MAX_VALUE - Byte.MIN_VALUE; + + private static final byte NO_ENUM_LITERAL = Byte.MIN_VALUE; + + private ExtendedIOUtil() + { + } + + public static void writeByteArray(DataOutput out, byte[] b) throws IOException + { + if (b != null) + { + out.writeInt(b.length); + out.write(b); + } + else + { + out.writeInt(-1); + } + } + + public static byte[] readByteArray(DataInput in) throws IOException + { + int length = in.readInt(); + if (length < 0) + { + return null; + } + + byte[] b; + try + { + b = new byte[length]; + } + catch (Throwable t) + { + throw new IOException("Unable to allocate " + length + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + in.readFully(b); + return b; + } + + public static void writeObject(final DataOutput out, Object object) throws IOException + { + ObjectOutput wrapper = null; + if (out instanceof ObjectOutput) + { + wrapper = (ObjectOutput)out; + } + else + { + wrapper = new ObjectOutputStream(new OutputStream() + { + @Override + public void write(int b) throws IOException + { + out.writeByte((b & 0xff) + Byte.MIN_VALUE); + } + }); + } + + wrapper.writeObject(object); + } + + public static Object readObject(final DataInput in) throws IOException + { + return readObject(in, (ClassResolver)null); + } + + public static Object readObject(final DataInput in, ClassLoader classLoader) throws IOException + { + return readObject(in, new ClassLoaderClassResolver(classLoader)); + } + + public static Object readObject(final DataInput in, final ClassResolver classResolver) throws IOException + { + ObjectInput wrapper = null; + if (in instanceof ObjectInput) + { + wrapper = (ObjectInput)in; + } + else + { + wrapper = new ObjectInputStream(new InputStream() + { + @Override + public int read() throws IOException + { + return in.readByte() - Byte.MIN_VALUE; + } + }) + + { + @Override + protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException + { + if (classResolver != null) + { + if (TRACER.isEnabled()) + { + TRACER.format("Deserializing class {0}", desc.getName()); //$NON-NLS-1$ + } + + Class<?> c = classResolver.resolveClass(desc); + if (c != null) + { + return c; + } + } + + return super.resolveClass(desc); + } + }; + } + + try + { + return wrapper.readObject(); + } + catch (ClassNotFoundException ex) + { + OM.LOG.error(ex); + throw WrappedException.wrap(ex); + } + } + + public static void writeString(DataOutput out, String str) throws IOException + { + if (str != null) + { + int size = str.length(); + int start = 0; + do + { + out.writeBoolean(true); + int chunk = Math.min(size, MAX_UTF_CHARS); + int end = start + chunk; + out.writeUTF(str.substring(start, end)); + start = end; + size -= chunk; + } while (size > 0); + } + + out.writeBoolean(false); + } + + public static String readString(DataInput in) throws IOException + { + boolean more = in.readBoolean(); + if (!more) + { + return null; + } + + StringBuilder builder = new StringBuilder(); + do + { + String chunk = in.readUTF(); + builder.append(chunk); + more = in.readBoolean(); + } while (more); + + return builder.toString(); + } + + /** + * @since 3.0 + */ + public static void writeEnum(DataOutput out, Enum<?> literal) throws IOException + { + if (literal == null) + { + out.writeByte(NO_ENUM_LITERAL); + } + else + { + getEnumLiterals(literal.getDeclaringClass()); // Check valid size + + int ordinal = literal.ordinal(); + out.writeByte(ordinal + Byte.MIN_VALUE + 1); + } + } + + /** + * @since 3.0 + */ + public static <T extends Enum<?>> T readEnum(DataInput in, Class<T> type) throws IOException + { + T[] literals = getEnumLiterals(type); + + int ordinal = in.readByte(); + if (ordinal == NO_ENUM_LITERAL) + { + return null; + } + + return literals[ordinal - Byte.MIN_VALUE - 1]; + } + + private static <T> T[] getEnumLiterals(Class<T> type) + { + T[] literals = type.getEnumConstants(); + + int size = literals.length; + if (size > MAX_ENUM_LITERALS) + { + throw new AssertionError("Enum too large: " + size + " literals"); + } + + return literals; + } + + /** + * @author Eike Stepper + */ + public interface ClassResolver + { + public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException; + } + + /** + * @author Eike Stepper + */ + public static class ClassLoaderClassResolver implements ClassResolver + { + private static final String STACK_TRACE_ELEMENT = StackTraceElement[].class.getName(); + + private ClassLoader classLoader; + + public ClassLoaderClassResolver(ClassLoader classLoader) + { + this.classLoader = classLoader; + } + + public Class<?> resolveClass(ObjectStreamClass v) throws ClassNotFoundException + { + String className = v.getName(); + + try + { + return classLoader.loadClass(className); + } + catch (ClassNotFoundException ex) + { + if (!STACK_TRACE_ELEMENT.equals(className)) + { + OM.LOG.error(ex); + } + + return null; + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java index acbfd304e7..a009e9fad1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedInputHandler.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface ExtendedInputHandler
-{
- public void handleIn(ExtendedDataInputStream in) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface ExtendedInputHandler +{ + public void handleIn(ExtendedDataInputStream in) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java index f5f4f8fcd8..026d4e4936 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ExtendedOutputHandler.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface ExtendedOutputHandler
-{
- public void handleOut(ExtendedDataOutputStream out) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface ExtendedOutputHandler +{ + public void handleOut(ExtendedDataOutputStream out) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java index 5db6013e2a..6d297f25d0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/GZIPStreamWrapper.java @@ -1,100 +1,100 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PipedInputStream;
-import java.io.PipedOutputStream;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
-
-/**
- * @author Eike Stepper
- */
-public class GZIPStreamWrapper implements IStreamWrapper
-{
- public GZIPStreamWrapper()
- {
- }
-
- public GZIPInputStream wrapInputStream(InputStream in) throws IOException
- {
- if (in instanceof GZIPInputStream)
- {
- return (GZIPInputStream)in;
- }
-
- return new GZIPInputStream(in);
- }
-
- public GZIPOutputStream wrapOutputStream(OutputStream out) throws IOException
- {
- if (out instanceof GZIPOutputStream)
- {
- return (GZIPOutputStream)out;
- }
-
- return new GZIPOutputStream(out);
- }
-
- public void finishInputStream(InputStream in) throws IOException
- {
- }
-
- public void finishOutputStream(OutputStream out) throws IOException
- {
- ((GZIPOutputStream)out).finish();
- }
-
- /**
- * TODO Move or remove me
- */
- public static void main(String[] args) throws Exception
- {
- final PipedOutputStream pos = new PipedOutputStream();
- final PipedInputStream pis = new PipedInputStream(pos);
-
- final GZIPOutputStream gos = new GZIPOutputStream(pos);
- final byte[] out = "eike".getBytes(); //$NON-NLS-1$
-
- Thread thread = new Thread()
- {
- @Override
- public void run()
- {
- try
- {
- GZIPInputStream gis = new GZIPInputStream(pis);
-
- byte[] in = new byte[out.length];
- gis.read(in);
- gis.close();
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
- };
-
- thread.start();
- ConcurrencyUtil.sleep(1000);
-
- gos.write(out);
- gos.close();
-
- ConcurrencyUtil.sleep(2000);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +/** + * @author Eike Stepper + */ +public class GZIPStreamWrapper implements IStreamWrapper +{ + public GZIPStreamWrapper() + { + } + + public GZIPInputStream wrapInputStream(InputStream in) throws IOException + { + if (in instanceof GZIPInputStream) + { + return (GZIPInputStream)in; + } + + return new GZIPInputStream(in); + } + + public GZIPOutputStream wrapOutputStream(OutputStream out) throws IOException + { + if (out instanceof GZIPOutputStream) + { + return (GZIPOutputStream)out; + } + + return new GZIPOutputStream(out); + } + + public void finishInputStream(InputStream in) throws IOException + { + } + + public void finishOutputStream(OutputStream out) throws IOException + { + ((GZIPOutputStream)out).finish(); + } + + /** + * TODO Move or remove me + */ + public static void main(String[] args) throws Exception + { + final PipedOutputStream pos = new PipedOutputStream(); + final PipedInputStream pis = new PipedInputStream(pos); + + final GZIPOutputStream gos = new GZIPOutputStream(pos); + final byte[] out = "eike".getBytes(); //$NON-NLS-1$ + + Thread thread = new Thread() + { + @Override + public void run() + { + try + { + GZIPInputStream gis = new GZIPInputStream(pis); + + byte[] in = new byte[out.length]; + gis.read(in); + gis.close(); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + }; + + thread.start(); + ConcurrencyUtil.sleep(1000); + + gos.write(out); + gos.close(); + + ConcurrencyUtil.sleep(2000); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java index 07ecb2bf20..1c2e9ae6cb 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOFilter.java @@ -1,19 +1,19 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-/**
- * @author Eike Stepper
- */
-public interface IOFilter<T>
-{
- public T filter(T data);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +/** + * @author Eike Stepper + */ +public interface IOFilter<T> +{ + public T filter(T data); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java index 51c4bfc9cb..3ab067cefc 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORunnable.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.Closeable;
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- */
-public interface IORunnable<IO extends Closeable>
-{
- public void run(IO io) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.Closeable; +import java.io.IOException; + +/** + * @author Eike Stepper + */ +public interface IORunnable<IO extends Closeable> +{ + public void run(IO io) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java index d2055ce440..32c3ef2c08 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IORuntimeException.java @@ -1,38 +1,38 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-/**
- * @author Eike Stepper
- */
-public class IORuntimeException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public IORuntimeException()
- {
- }
-
- public IORuntimeException(String message)
- {
- super(message);
- }
-
- public IORuntimeException(Throwable cause)
- {
- super(cause);
- }
-
- public IORuntimeException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +/** + * @author Eike Stepper + */ +public class IORuntimeException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public IORuntimeException() + { + } + + public IORuntimeException(String message) + { + super(message); + } + + public IORuntimeException(Throwable cause) + { + super(cause); + } + + public IORuntimeException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java index 94bf7053ba..aec35bb3d3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOTimeoutException.java @@ -1,50 +1,50 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.util.concurrent.TimeoutException;
-
-/**
- * @author Eike Stepper
- * @since 3.0
- */
-public class IOTimeoutException extends IOException
-{
- private static final long serialVersionUID = 1L;
-
- public IOTimeoutException()
- {
- }
-
- public IOTimeoutException(String message, Throwable cause)
- {
- super(message);
- initCause(cause);
- }
-
- public IOTimeoutException(String message)
- {
- super(message);
- }
-
- public IOTimeoutException(Throwable cause)
- {
- initCause(cause);
- }
-
- public TimeoutException createTimeoutException()
- {
- TimeoutException timeoutException = new TimeoutException(getMessage());
- timeoutException.initCause(this);
- return timeoutException;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.util.concurrent.TimeoutException; + +/** + * @author Eike Stepper + * @since 3.0 + */ +public class IOTimeoutException extends IOException +{ + private static final long serialVersionUID = 1L; + + public IOTimeoutException() + { + } + + public IOTimeoutException(String message, Throwable cause) + { + super(message); + initCause(cause); + } + + public IOTimeoutException(String message) + { + super(message); + } + + public IOTimeoutException(Throwable cause) + { + initCause(cause); + } + + public TimeoutException createTimeoutException() + { + TimeoutException timeoutException = new TimeoutException(getMessage()); + timeoutException.initCause(this); + return timeoutException; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java index 359a79e9cc..cef2510199 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOUtil.java @@ -1,932 +1,932 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.StringUtil;
-import org.eclipse.net4j.util.WrappedException;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.CharArrayReader;
-import java.io.CharArrayWriter;
-import java.io.Closeable;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * @author Eike Stepper
- */
-public final class IOUtil
-{
- /**
- * @since 3.1
- */
- public static final int EOF = -1;
-
- /**
- * @since 3.1
- */
- public static final long DEFAULT_TIMEOUT = 2500;
-
- public static final int DEFAULT_BUFFER_SIZE = 8192;
-
- /**
- * @since 2.0
- */
- public static final String WILDCARD_SINGLE_CHAR = "?"; //$NON-NLS-1$
-
- /**
- * @since 2.0
- */
- public static final String WILDCARD_MULTI_CHARS = "*"; //$NON-NLS-1$
-
- /**
- * @since 2.0
- */
- public static final String WILDCARD_MULTI_DIRS = "**"; //$NON-NLS-1$
-
- private static final char SEP = File.separatorChar;
-
- private static final char SEP_UNIX = '/';
-
- private static final char SEP_WINDOWS = '\\';
-
- private IOUtil()
- {
- }
-
- public static InputStream IN()
- {
- return System.in;
- }
-
- public static PrintStream OUT()
- {
- return System.out;
- }
-
- public static PrintStream ERR()
- {
- return System.err;
- }
-
- /**
- * @since 3.1
- */
- public static void print(StackTraceElement[] elements)
- {
- print(elements, System.err);
- }
-
- /**
- * @since 3.1
- */
- public static void print(StackTraceElement[] elements, PrintStream stream)
- {
- synchronized (stream)
- {
- for (int i = 0; i < elements.length; i++)
- {
- stream.println("\tat " + elements[i]);
- }
- }
- }
-
- public static void print(Throwable t, PrintStream stream)
- {
- t.printStackTrace(stream);
- }
-
- public static void print(Throwable t)
- {
- print(t, System.err);
- }
-
- /**
- * @since 2.0
- */
- public static String toString(Throwable t)
- {
- try
- {
- ByteArrayOutputStream bytes = new ByteArrayOutputStream();
- String message = t.getMessage() + "\n"; //$NON-NLS-1$
- bytes.write(message.getBytes());
- print(t, new PrintStream(bytes));
-
- return bytes.toString();
- }
- catch (IOException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- public static FileInputStream openInputStream(String fileName) throws IORuntimeException
- {
- return openInputStream(new File(fileName));
- }
-
- public static FileInputStream openInputStream(File file) throws IORuntimeException
- {
- try
- {
- return new FileInputStream(file);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static FileOutputStream openOutputStream(String fileName) throws IORuntimeException
- {
- return openOutputStream(new File(fileName));
- }
-
- public static FileOutputStream openOutputStream(File file) throws IORuntimeException
- {
- try
- {
- return new FileOutputStream(file);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static FileReader openReader(String fileName) throws IORuntimeException
- {
- return openReader(new File(fileName));
- }
-
- public static FileReader openReader(File file) throws IORuntimeException
- {
- try
- {
- return new FileReader(file);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static FileWriter openWriter(String fileName) throws IORuntimeException
- {
- return openWriter(new File(fileName));
- }
-
- public static FileWriter openWriter(File file) throws IORuntimeException
- {
- try
- {
- return new FileWriter(file);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static Exception closeSilent(Closeable closeable)
- {
- try
- {
- if (closeable != null)
- {
- closeable.close();
- }
-
- return null;
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- return ex;
- }
- }
-
- public static void close(Closeable closeable) throws IORuntimeException
- {
- try
- {
- if (closeable != null)
- {
- closeable.close();
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static Exception closeSilent(org.eclipse.net4j.util.collection.Closeable closeable)
- {
- try
- {
- if (closeable != null)
- {
- closeable.close();
- }
-
- return null;
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- return ex;
- }
- }
-
- public static void close(org.eclipse.net4j.util.collection.Closeable closeable) throws IORuntimeException
- {
- if (closeable != null)
- {
- closeable.close();
- }
- }
-
- /**
- * @since 2.0
- */
- public static String makeRelative(File file, File toFolder)
- {
- String fileName = normalizeSeparator(file.getAbsolutePath());
- String folderName = normalizeSeparator(toFolder.getAbsolutePath());
- if (fileName.startsWith(folderName))
- {
- String relative = fileName.substring(folderName.length());
- if (relative.startsWith(File.separator))
- {
- relative = relative.substring(1);
- }
-
- return relative;
- }
-
- throw new IllegalArgumentException("Different prefixes: " + fileName + " != " + folderName); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * @since 2.0
- */
- public static String normalizeSeparator(String string)
- {
- if (SEP == SEP_UNIX)
- {
- return string.replace(SEP_WINDOWS, SEP_UNIX);
- }
- else if (SEP == SEP_WINDOWS)
- {
- return string.replace(SEP_UNIX, SEP_WINDOWS);
- }
-
- return string;
- }
-
- public static void mkdirs(File folder)
- {
- if (!folder.exists())
- {
- if (!folder.mkdirs())
- {
- throw new IORuntimeException("Unable to create directory " + folder.getAbsolutePath()); //$NON-NLS-1$
- }
- }
- }
-
- public static int delete(File file)
- {
- if (file == null)
- {
- return 0;
- }
-
- int deleted = 0;
- if (file.isDirectory())
- {
- for (File child : file.listFiles())
- {
- deleted += delete(child);
- }
- }
-
- if (file.delete())
- {
- return deleted + 1;
- }
-
- file.deleteOnExit();
- return deleted;
- }
-
- public static void copyTree(File source, File target) throws IORuntimeException
- {
- if (source.isDirectory())
- {
- mkdirs(target);
- File[] files = source.listFiles();
- for (File file : files)
- {
- String name = file.getName();
- copyTree(new File(source, name), new File(target, name));
- }
- }
- else
- {
- copyFile(source, target);
- }
- }
-
- public static void copyTrees(Collection<File> sources, File target) throws IORuntimeException
- {
- for (File source : sources)
- {
- copyTree(source, target);
- }
- }
-
- public static void copyText(File source, File target, IOFilter<String>... lineFilters) throws IORuntimeException
- {
- BufferedReader reader = null;
- BufferedWriter writer = null;
-
- try
- {
- reader = new BufferedReader(openReader(source));
- writer = new BufferedWriter(openWriter(target));
- copyText(reader, writer, lineFilters);
- }
- finally
- {
- closeSilent(reader);
- closeSilent(writer);
- }
- }
-
- public static void copyText(BufferedReader reader, BufferedWriter writer, IOFilter<String>... lineFilters)
- {
- try
- {
- String line;
- while ((line = reader.readLine()) != null)
- {
- for (IOFilter<String> lineFilter : lineFilters)
- {
- line = lineFilter.filter(line);
- }
-
- writer.write(line);
- writer.newLine();
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- /**
- * @since 3.1
- */
- public static long copyBinary(InputStream inputStream, OutputStream outputStream) throws IOException
- {
- if (!(inputStream instanceof BufferedInputStream) && !(inputStream instanceof ByteArrayInputStream))
- {
- inputStream = new BufferedInputStream(inputStream);
- }
-
- if (!(outputStream instanceof BufferedOutputStream) && !(outputStream instanceof ByteArrayOutputStream))
- {
- outputStream = new BufferedOutputStream(outputStream);
- }
-
- long size = 0;
- int b;
- while ((b = inputStream.read()) != EOF)
- {
- outputStream.write(b);
- ++size;
- }
-
- outputStream.flush();
- return size;
- }
-
- /**
- * @since 3.1
- */
- public static void copyBinary(InputStream inputStream, OutputStream outputStream, long size) throws IOException
- {
- byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
-
- while (size > 0L)
- {
- int bytesToCopy = (int)Math.min(size, buffer.length);
-
- int bytesRead = inputStream.read(buffer, 0, bytesToCopy);
- if (bytesRead < bytesToCopy)
- {
- throw new EOFException();
- }
-
- outputStream.write(buffer, 0, bytesToCopy);
- size -= bytesRead;
- }
-
- outputStream.flush();
- }
-
- /**
- * @since 3.1
- */
- public static long copyCharacter(Reader reader, Writer writer) throws IOException
- {
- if (!(reader instanceof BufferedReader) && !(reader instanceof CharArrayReader))
- {
- reader = new BufferedReader(reader);
- }
-
- if (!(writer instanceof BufferedWriter) && !(writer instanceof CharArrayWriter))
- {
- writer = new BufferedWriter(writer);
- }
-
- long size = 0;
- int c;
- while ((c = reader.read()) != EOF)
- {
- writer.write(c);
- ++size;
- }
-
- writer.flush();
- return size;
- }
-
- /**
- * @since 3.1
- */
- public static void copyCharacter(Reader reader, Writer writer, long size) throws IOException
- {
- char[] buffer = new char[DEFAULT_BUFFER_SIZE];
-
- while (size > 0L)
- {
- int charsToCopy = (int)Math.min(size, buffer.length);
-
- int charsRead = reader.read(buffer, 0, charsToCopy);
- if (charsRead < charsToCopy)
- {
- throw new EOFException();
- }
-
- writer.write(buffer, 0, charsRead);
- size -= charsRead;
- }
-
- writer.flush();
- }
-
- public static int copy(InputStream input, OutputStream output, int size, byte buffer[]) throws IORuntimeException
- {
- try
- {
- int written = 0;
- int bufferSize = buffer.length;
- int n = Math.min(size, bufferSize);
- while (n > 0 && (n = input.read(buffer, 0, n)) != -1)
- {
- output.write(buffer, 0, n);
- written += n;
- size -= n;
- n = Math.min(size, bufferSize);
- }
-
- return written;
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static void copy(InputStream input, OutputStream output, byte buffer[]) throws IORuntimeException
- {
- try
- {
- int n;
- while ((n = input.read(buffer)) != -1)
- {
- output.write(buffer, 0, n);
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static void copy(InputStream input, OutputStream output, int bufferSize) throws IORuntimeException
- {
- copy(input, output, new byte[bufferSize]);
- }
-
- public static void copy(InputStream input, OutputStream output) throws IORuntimeException
- {
- copy(input, output, DEFAULT_BUFFER_SIZE);
- }
-
- /**
- * @see NIOUtil#copyFile(File, File)
- */
- public static void copyFile(File source, File target) throws IORuntimeException
- {
- mkdirs(target.getParentFile());
- FileInputStream input = null;
- FileOutputStream output = null;
-
- try
- {
- input = openInputStream(source);
- output = openOutputStream(target);
- copy(input, output);
- }
- finally
- {
- closeSilent(input);
- closeSilent(output);
- }
- }
-
- /**
- * @since 3.1
- */
- public static String readTextFile(File file) throws IORuntimeException
- {
- Reader input = openReader(file);
-
- try
- {
- CharArrayWriter output = new CharArrayWriter();
- copyCharacter(input, output);
- return output.toString();
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- closeSilent(input);
- }
- }
-
- public static byte[] readFile(File file) throws IORuntimeException
- {
- if (file.length() > Integer.MAX_VALUE)
- {
- throw new IllegalArgumentException("File too long: " + file.length()); //$NON-NLS-1$
- }
-
- int size = (int)file.length();
- FileInputStream input = openInputStream(file);
-
- try
- {
- ByteArrayOutputStream output = new ByteArrayOutputStream(size);
- copy(input, output);
- return output.toByteArray();
- }
- finally
- {
- closeSilent(input);
- }
- }
-
- public static void writeFile(File file, byte[] bytes) throws IORuntimeException
- {
- FileOutputStream output = openOutputStream(file);
-
- try
- {
- ByteArrayInputStream input = new ByteArrayInputStream(bytes);
- copy(input, output);
- }
- finally
- {
- closeSilent(output);
- }
- }
-
- public static List<File> listDepthFirst(File file)
- {
- FileCollector collector = new FileCollector();
- visitDepthFirst(file, collector);
- return collector.getFiles();
- }
-
- public static List<File> listBreadthFirst(File file)
- {
- FileCollector collector = new FileCollector();
- visitBreadthFirst(file, collector);
- return collector.getFiles();
- }
-
- public static void visitDepthFirst(File file, IOVisitor visitor) throws IORuntimeException
- {
- try
- {
- boolean recurse = visitor.visit(file);
- if (recurse && file.isDirectory())
- {
- visitDepthFirst(file.listFiles(), visitor);
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static void visitDepthFirst(File[] files, IOVisitor visitor)
- {
- for (File file : files)
- {
- visitDepthFirst(file, visitor);
- }
- }
-
- public static void visitBreadthFirst(File file, IOVisitor visitor) throws IORuntimeException
- {
- File[] files = { file };
- visitBreadthFirst(files, visitor);
- }
-
- public static void visitBreadthFirst(File[] files, IOVisitor visitor) throws IORuntimeException
- {
- try
- {
- boolean[] recurse = new boolean[files.length];
- for (int i = 0; i < files.length; i++)
- {
- File file = files[i];
- recurse[i] = visitor.visit(file);
- }
-
- for (int i = 0; i < files.length; i++)
- {
- File file = files[i];
- if (file.isDirectory() && recurse[i])
- {
- File[] children = file.listFiles();
- for (File child : children)
- {
- visitBreadthFirst(child, visitor);
- }
- }
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static <IO extends Closeable> void safeRun(IO io, IORunnable<IO> runnable) throws IORuntimeException
- {
- try
- {
- runnable.run(io);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- close(io);
- }
- }
-
- public static void safeInput(File file, IORunnable<FileInputStream> runnable) throws IORuntimeException
- {
- safeRun(openInputStream(file), runnable);
- }
-
- public static void safeOutput(File file, IORunnable<FileOutputStream> runnable) throws IORuntimeException
- {
- safeRun(openOutputStream(file), runnable);
- }
-
- public static void safeRead(File file, IORunnable<FileReader> runnable) throws IORuntimeException
- {
- safeRun(openReader(file), runnable);
- }
-
- public static void safeWrite(File file, IORunnable<FileWriter> runnable) throws IORuntimeException
- {
- safeRun(openWriter(file), runnable);
- }
-
- public static boolean equals(InputStream stream1, InputStream stream2) throws IORuntimeException
- {
- try
- {
- for (;;)
- {
- int byte1 = stream1.read();
- int byte2 = stream2.read();
-
- if (byte1 != byte2)
- {
- return false;
- }
-
- if (byte1 == -1)// Implies byte2 == -1
- {
- return true;
- }
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- /**
- * @since 3.2
- */
- public static boolean equals(Reader reader1, Reader reader2) throws IORuntimeException
- {
- try
- {
- for (;;)
- {
- int char1 = reader1.read();
- int char2 = reader2.read();
-
- if (char1 != char2)
- {
- return false;
- }
-
- if (char1 == -1)// Implies char2 == -1
- {
- return true;
- }
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public static boolean equals(File file1, File file2) throws IORuntimeException
- {
- if (file1.length() != file2.length())
- {
- return false;
- }
-
- FileInputStream stream1 = null;
- FileInputStream stream2 = null;
-
- try
- {
- stream1 = new FileInputStream(file1);
- stream2 = new FileInputStream(file2);
- return equals(stream1, stream2);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- closeSilent(stream1);
- closeSilent(stream2);
- }
- }
-
- /**
- * @since 2.0
- */
- public static List<File> glob(String pattern, File folder)
- {
- List<File> result = new ArrayList<File>();
- pattern = normalizeSeparator(pattern);
- if (pattern.endsWith(File.separator))
- {
- pattern += WILDCARD_MULTI_DIRS;
- }
-
- globRecurse(pattern, folder, result);
- return result;
- }
-
- private static void globRecurse(String pattern, File folder, List<File> result)
- {
- int sep = pattern.indexOf(SEP);
- if (sep != -1)
- {
- globSegment(pattern.substring(0, sep), pattern.substring(sep + 1), folder, result);
- }
- else
- {
- globSegment(pattern, null, folder, result);
- }
- }
-
- private static void globSegment(String segment, String pattern, File folder, List<File> result)
- {
- boolean multiDirs = false;
- if (segment.contains(WILDCARD_MULTI_DIRS))
- {
- if (!segment.equals(WILDCARD_MULTI_DIRS))
- {
- throw new IllegalArgumentException("Invalid pattern segment: " + segment); //$NON-NLS-1$
- }
-
- multiDirs = true;
- }
-
- for (File file : folder.listFiles())
- {
- String tmp = segment;
- if (multiDirs && file.isDirectory())
- {
- globRecurse(WILDCARD_MULTI_DIRS + File.separator + pattern, file, result);
- tmp = WILDCARD_MULTI_CHARS;
- }
-
- if (StringUtil.glob(tmp, file.getName()))
- {
- if (pattern == null)
- {
- // Match
- result.add(file);
- }
- else if (file.isDirectory())
- {
- // Recurse
- globRecurse(pattern, file, result);
- }
- }
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class FileCollector implements IOVisitor
- {
- private List<File> files = new ArrayList<File>();
-
- public FileCollector()
- {
- }
-
- public List<File> getFiles()
- {
- return files;
- }
-
- public boolean visit(File file) throws IOException
- {
- files.add(file);
- return true;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.StringUtil; +import org.eclipse.net4j.util.WrappedException; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.CharArrayReader; +import java.io.CharArrayWriter; +import java.io.Closeable; +import java.io.EOFException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.Reader; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * @author Eike Stepper + */ +public final class IOUtil +{ + /** + * @since 3.1 + */ + public static final int EOF = -1; + + /** + * @since 3.1 + */ + public static final long DEFAULT_TIMEOUT = 2500; + + public static final int DEFAULT_BUFFER_SIZE = 8192; + + /** + * @since 2.0 + */ + public static final String WILDCARD_SINGLE_CHAR = "?"; //$NON-NLS-1$ + + /** + * @since 2.0 + */ + public static final String WILDCARD_MULTI_CHARS = "*"; //$NON-NLS-1$ + + /** + * @since 2.0 + */ + public static final String WILDCARD_MULTI_DIRS = "**"; //$NON-NLS-1$ + + private static final char SEP = File.separatorChar; + + private static final char SEP_UNIX = '/'; + + private static final char SEP_WINDOWS = '\\'; + + private IOUtil() + { + } + + public static InputStream IN() + { + return System.in; + } + + public static PrintStream OUT() + { + return System.out; + } + + public static PrintStream ERR() + { + return System.err; + } + + /** + * @since 3.1 + */ + public static void print(StackTraceElement[] elements) + { + print(elements, System.err); + } + + /** + * @since 3.1 + */ + public static void print(StackTraceElement[] elements, PrintStream stream) + { + synchronized (stream) + { + for (int i = 0; i < elements.length; i++) + { + stream.println("\tat " + elements[i]); + } + } + } + + public static void print(Throwable t, PrintStream stream) + { + t.printStackTrace(stream); + } + + public static void print(Throwable t) + { + print(t, System.err); + } + + /** + * @since 2.0 + */ + public static String toString(Throwable t) + { + try + { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + String message = t.getMessage() + "\n"; //$NON-NLS-1$ + bytes.write(message.getBytes()); + print(t, new PrintStream(bytes)); + + return bytes.toString(); + } + catch (IOException ex) + { + throw WrappedException.wrap(ex); + } + } + + public static FileInputStream openInputStream(String fileName) throws IORuntimeException + { + return openInputStream(new File(fileName)); + } + + public static FileInputStream openInputStream(File file) throws IORuntimeException + { + try + { + return new FileInputStream(file); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static FileOutputStream openOutputStream(String fileName) throws IORuntimeException + { + return openOutputStream(new File(fileName)); + } + + public static FileOutputStream openOutputStream(File file) throws IORuntimeException + { + try + { + return new FileOutputStream(file); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static FileReader openReader(String fileName) throws IORuntimeException + { + return openReader(new File(fileName)); + } + + public static FileReader openReader(File file) throws IORuntimeException + { + try + { + return new FileReader(file); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static FileWriter openWriter(String fileName) throws IORuntimeException + { + return openWriter(new File(fileName)); + } + + public static FileWriter openWriter(File file) throws IORuntimeException + { + try + { + return new FileWriter(file); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static Exception closeSilent(Closeable closeable) + { + try + { + if (closeable != null) + { + closeable.close(); + } + + return null; + } + catch (Exception ex) + { + OM.LOG.error(ex); + return ex; + } + } + + public static void close(Closeable closeable) throws IORuntimeException + { + try + { + if (closeable != null) + { + closeable.close(); + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static Exception closeSilent(org.eclipse.net4j.util.collection.Closeable closeable) + { + try + { + if (closeable != null) + { + closeable.close(); + } + + return null; + } + catch (Exception ex) + { + OM.LOG.error(ex); + return ex; + } + } + + public static void close(org.eclipse.net4j.util.collection.Closeable closeable) throws IORuntimeException + { + if (closeable != null) + { + closeable.close(); + } + } + + /** + * @since 2.0 + */ + public static String makeRelative(File file, File toFolder) + { + String fileName = normalizeSeparator(file.getAbsolutePath()); + String folderName = normalizeSeparator(toFolder.getAbsolutePath()); + if (fileName.startsWith(folderName)) + { + String relative = fileName.substring(folderName.length()); + if (relative.startsWith(File.separator)) + { + relative = relative.substring(1); + } + + return relative; + } + + throw new IllegalArgumentException("Different prefixes: " + fileName + " != " + folderName); //$NON-NLS-1$ //$NON-NLS-2$ + } + + /** + * @since 2.0 + */ + public static String normalizeSeparator(String string) + { + if (SEP == SEP_UNIX) + { + return string.replace(SEP_WINDOWS, SEP_UNIX); + } + else if (SEP == SEP_WINDOWS) + { + return string.replace(SEP_UNIX, SEP_WINDOWS); + } + + return string; + } + + public static void mkdirs(File folder) + { + if (!folder.exists()) + { + if (!folder.mkdirs()) + { + throw new IORuntimeException("Unable to create directory " + folder.getAbsolutePath()); //$NON-NLS-1$ + } + } + } + + public static int delete(File file) + { + if (file == null) + { + return 0; + } + + int deleted = 0; + if (file.isDirectory()) + { + for (File child : file.listFiles()) + { + deleted += delete(child); + } + } + + if (file.delete()) + { + return deleted + 1; + } + + file.deleteOnExit(); + return deleted; + } + + public static void copyTree(File source, File target) throws IORuntimeException + { + if (source.isDirectory()) + { + mkdirs(target); + File[] files = source.listFiles(); + for (File file : files) + { + String name = file.getName(); + copyTree(new File(source, name), new File(target, name)); + } + } + else + { + copyFile(source, target); + } + } + + public static void copyTrees(Collection<File> sources, File target) throws IORuntimeException + { + for (File source : sources) + { + copyTree(source, target); + } + } + + public static void copyText(File source, File target, IOFilter<String>... lineFilters) throws IORuntimeException + { + BufferedReader reader = null; + BufferedWriter writer = null; + + try + { + reader = new BufferedReader(openReader(source)); + writer = new BufferedWriter(openWriter(target)); + copyText(reader, writer, lineFilters); + } + finally + { + closeSilent(reader); + closeSilent(writer); + } + } + + public static void copyText(BufferedReader reader, BufferedWriter writer, IOFilter<String>... lineFilters) + { + try + { + String line; + while ((line = reader.readLine()) != null) + { + for (IOFilter<String> lineFilter : lineFilters) + { + line = lineFilter.filter(line); + } + + writer.write(line); + writer.newLine(); + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + /** + * @since 3.1 + */ + public static long copyBinary(InputStream inputStream, OutputStream outputStream) throws IOException + { + if (!(inputStream instanceof BufferedInputStream) && !(inputStream instanceof ByteArrayInputStream)) + { + inputStream = new BufferedInputStream(inputStream); + } + + if (!(outputStream instanceof BufferedOutputStream) && !(outputStream instanceof ByteArrayOutputStream)) + { + outputStream = new BufferedOutputStream(outputStream); + } + + long size = 0; + int b; + while ((b = inputStream.read()) != EOF) + { + outputStream.write(b); + ++size; + } + + outputStream.flush(); + return size; + } + + /** + * @since 3.1 + */ + public static void copyBinary(InputStream inputStream, OutputStream outputStream, long size) throws IOException + { + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + + while (size > 0L) + { + int bytesToCopy = (int)Math.min(size, buffer.length); + + int bytesRead = inputStream.read(buffer, 0, bytesToCopy); + if (bytesRead < bytesToCopy) + { + throw new EOFException(); + } + + outputStream.write(buffer, 0, bytesToCopy); + size -= bytesRead; + } + + outputStream.flush(); + } + + /** + * @since 3.1 + */ + public static long copyCharacter(Reader reader, Writer writer) throws IOException + { + if (!(reader instanceof BufferedReader) && !(reader instanceof CharArrayReader)) + { + reader = new BufferedReader(reader); + } + + if (!(writer instanceof BufferedWriter) && !(writer instanceof CharArrayWriter)) + { + writer = new BufferedWriter(writer); + } + + long size = 0; + int c; + while ((c = reader.read()) != EOF) + { + writer.write(c); + ++size; + } + + writer.flush(); + return size; + } + + /** + * @since 3.1 + */ + public static void copyCharacter(Reader reader, Writer writer, long size) throws IOException + { + char[] buffer = new char[DEFAULT_BUFFER_SIZE]; + + while (size > 0L) + { + int charsToCopy = (int)Math.min(size, buffer.length); + + int charsRead = reader.read(buffer, 0, charsToCopy); + if (charsRead < charsToCopy) + { + throw new EOFException(); + } + + writer.write(buffer, 0, charsRead); + size -= charsRead; + } + + writer.flush(); + } + + public static int copy(InputStream input, OutputStream output, int size, byte buffer[]) throws IORuntimeException + { + try + { + int written = 0; + int bufferSize = buffer.length; + int n = Math.min(size, bufferSize); + while (n > 0 && (n = input.read(buffer, 0, n)) != -1) + { + output.write(buffer, 0, n); + written += n; + size -= n; + n = Math.min(size, bufferSize); + } + + return written; + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static void copy(InputStream input, OutputStream output, byte buffer[]) throws IORuntimeException + { + try + { + int n; + while ((n = input.read(buffer)) != -1) + { + output.write(buffer, 0, n); + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static void copy(InputStream input, OutputStream output, int bufferSize) throws IORuntimeException + { + copy(input, output, new byte[bufferSize]); + } + + public static void copy(InputStream input, OutputStream output) throws IORuntimeException + { + copy(input, output, DEFAULT_BUFFER_SIZE); + } + + /** + * @see NIOUtil#copyFile(File, File) + */ + public static void copyFile(File source, File target) throws IORuntimeException + { + mkdirs(target.getParentFile()); + FileInputStream input = null; + FileOutputStream output = null; + + try + { + input = openInputStream(source); + output = openOutputStream(target); + copy(input, output); + } + finally + { + closeSilent(input); + closeSilent(output); + } + } + + /** + * @since 3.1 + */ + public static String readTextFile(File file) throws IORuntimeException + { + Reader input = openReader(file); + + try + { + CharArrayWriter output = new CharArrayWriter(); + copyCharacter(input, output); + return output.toString(); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + closeSilent(input); + } + } + + public static byte[] readFile(File file) throws IORuntimeException + { + if (file.length() > Integer.MAX_VALUE) + { + throw new IllegalArgumentException("File too long: " + file.length()); //$NON-NLS-1$ + } + + int size = (int)file.length(); + FileInputStream input = openInputStream(file); + + try + { + ByteArrayOutputStream output = new ByteArrayOutputStream(size); + copy(input, output); + return output.toByteArray(); + } + finally + { + closeSilent(input); + } + } + + public static void writeFile(File file, byte[] bytes) throws IORuntimeException + { + FileOutputStream output = openOutputStream(file); + + try + { + ByteArrayInputStream input = new ByteArrayInputStream(bytes); + copy(input, output); + } + finally + { + closeSilent(output); + } + } + + public static List<File> listDepthFirst(File file) + { + FileCollector collector = new FileCollector(); + visitDepthFirst(file, collector); + return collector.getFiles(); + } + + public static List<File> listBreadthFirst(File file) + { + FileCollector collector = new FileCollector(); + visitBreadthFirst(file, collector); + return collector.getFiles(); + } + + public static void visitDepthFirst(File file, IOVisitor visitor) throws IORuntimeException + { + try + { + boolean recurse = visitor.visit(file); + if (recurse && file.isDirectory()) + { + visitDepthFirst(file.listFiles(), visitor); + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static void visitDepthFirst(File[] files, IOVisitor visitor) + { + for (File file : files) + { + visitDepthFirst(file, visitor); + } + } + + public static void visitBreadthFirst(File file, IOVisitor visitor) throws IORuntimeException + { + File[] files = { file }; + visitBreadthFirst(files, visitor); + } + + public static void visitBreadthFirst(File[] files, IOVisitor visitor) throws IORuntimeException + { + try + { + boolean[] recurse = new boolean[files.length]; + for (int i = 0; i < files.length; i++) + { + File file = files[i]; + recurse[i] = visitor.visit(file); + } + + for (int i = 0; i < files.length; i++) + { + File file = files[i]; + if (file.isDirectory() && recurse[i]) + { + File[] children = file.listFiles(); + for (File child : children) + { + visitBreadthFirst(child, visitor); + } + } + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static <IO extends Closeable> void safeRun(IO io, IORunnable<IO> runnable) throws IORuntimeException + { + try + { + runnable.run(io); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + close(io); + } + } + + public static void safeInput(File file, IORunnable<FileInputStream> runnable) throws IORuntimeException + { + safeRun(openInputStream(file), runnable); + } + + public static void safeOutput(File file, IORunnable<FileOutputStream> runnable) throws IORuntimeException + { + safeRun(openOutputStream(file), runnable); + } + + public static void safeRead(File file, IORunnable<FileReader> runnable) throws IORuntimeException + { + safeRun(openReader(file), runnable); + } + + public static void safeWrite(File file, IORunnable<FileWriter> runnable) throws IORuntimeException + { + safeRun(openWriter(file), runnable); + } + + public static boolean equals(InputStream stream1, InputStream stream2) throws IORuntimeException + { + try + { + for (;;) + { + int byte1 = stream1.read(); + int byte2 = stream2.read(); + + if (byte1 != byte2) + { + return false; + } + + if (byte1 == -1)// Implies byte2 == -1 + { + return true; + } + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + /** + * @since 3.2 + */ + public static boolean equals(Reader reader1, Reader reader2) throws IORuntimeException + { + try + { + for (;;) + { + int char1 = reader1.read(); + int char2 = reader2.read(); + + if (char1 != char2) + { + return false; + } + + if (char1 == -1)// Implies char2 == -1 + { + return true; + } + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public static boolean equals(File file1, File file2) throws IORuntimeException + { + if (file1.length() != file2.length()) + { + return false; + } + + FileInputStream stream1 = null; + FileInputStream stream2 = null; + + try + { + stream1 = new FileInputStream(file1); + stream2 = new FileInputStream(file2); + return equals(stream1, stream2); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + closeSilent(stream1); + closeSilent(stream2); + } + } + + /** + * @since 2.0 + */ + public static List<File> glob(String pattern, File folder) + { + List<File> result = new ArrayList<File>(); + pattern = normalizeSeparator(pattern); + if (pattern.endsWith(File.separator)) + { + pattern += WILDCARD_MULTI_DIRS; + } + + globRecurse(pattern, folder, result); + return result; + } + + private static void globRecurse(String pattern, File folder, List<File> result) + { + int sep = pattern.indexOf(SEP); + if (sep != -1) + { + globSegment(pattern.substring(0, sep), pattern.substring(sep + 1), folder, result); + } + else + { + globSegment(pattern, null, folder, result); + } + } + + private static void globSegment(String segment, String pattern, File folder, List<File> result) + { + boolean multiDirs = false; + if (segment.contains(WILDCARD_MULTI_DIRS)) + { + if (!segment.equals(WILDCARD_MULTI_DIRS)) + { + throw new IllegalArgumentException("Invalid pattern segment: " + segment); //$NON-NLS-1$ + } + + multiDirs = true; + } + + for (File file : folder.listFiles()) + { + String tmp = segment; + if (multiDirs && file.isDirectory()) + { + globRecurse(WILDCARD_MULTI_DIRS + File.separator + pattern, file, result); + tmp = WILDCARD_MULTI_CHARS; + } + + if (StringUtil.glob(tmp, file.getName())) + { + if (pattern == null) + { + // Match + result.add(file); + } + else if (file.isDirectory()) + { + // Recurse + globRecurse(pattern, file, result); + } + } + } + } + + /** + * @author Eike Stepper + */ + public static class FileCollector implements IOVisitor + { + private List<File> files = new ArrayList<File>(); + + public FileCollector() + { + } + + public List<File> getFiles() + { + return files; + } + + public boolean visit(File file) throws IOException + { + files.add(file); + return true; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java index 8a8679feb1..46c7c8c945 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IOVisitor.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- */
-public interface IOVisitor
-{
- public boolean visit(File file) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.File; +import java.io.IOException; + +/** + * @author Eike Stepper + */ +public interface IOVisitor +{ + public boolean visit(File file) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java index cd299367be..2b0467c280 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/IStreamWrapper.java @@ -1,29 +1,29 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public interface IStreamWrapper
-{
- public InputStream wrapInputStream(InputStream in) throws IOException;
-
- public OutputStream wrapOutputStream(OutputStream out) throws IOException;
-
- public void finishInputStream(InputStream in) throws IOException;
-
- public void finishOutputStream(OutputStream out) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public interface IStreamWrapper +{ + public InputStream wrapInputStream(InputStream in) throws IOException; + + public OutputStream wrapOutputStream(OutputStream out) throws IOException; + + public void finishInputStream(InputStream in) throws IOException; + + public void finishOutputStream(OutputStream out) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java index 0780744c0a..5f3e6e787d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedInputStream.java @@ -1,112 +1,112 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * @author Eike Stepper
- * @since 3.2
- */
-public class LimitedInputStream extends InputStream
-{
- private InputStream in;
-
- private long remaining;
-
- private long remainingAtMark = 0;
-
- public LimitedInputStream(InputStream in, long length)
- {
- this.in = in;
- remaining = length;
- }
-
- @Override
- public int read() throws IOException
- {
- if ((remaining -= 1) < 0)
- {
- return -1;
- }
-
- return in.read();
- }
-
- @Override
- public int read(byte[] cbuf, int off, int len) throws IOException
- {
- if (remaining <= 0)
- {
- return -1;
- }
-
- if (len > remaining)
- {
- len = (int)remaining;
- }
-
- len = in.read(cbuf, off, len);
- if (len > 0)
- {
- remaining -= len;
- }
- else
- {
- remaining -= remaining;
- }
-
- return len;
- }
-
- @Override
- public long skip(long n) throws IOException
- {
- if (n > remaining)
- {
- n = remaining;
- }
-
- remaining -= n = in.skip(n);
- return n;
- }
-
- @Override
- public boolean markSupported()
- {
- return in.markSupported();
- }
-
- @Override
- public synchronized void mark(int readlimit)
- {
- if (markSupported())
- {
- in.mark(readlimit);
- remainingAtMark = remaining;
- }
- }
-
- @Override
- public synchronized void reset() throws IOException
- {
- in.reset();
- remaining = remainingAtMark;
- }
-
- @Override
- public void close() throws IOException
- {
- remaining = 0;
- in.close();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * @author Eike Stepper + * @since 3.2 + */ +public class LimitedInputStream extends InputStream +{ + private InputStream in; + + private long remaining; + + private long remainingAtMark = 0; + + public LimitedInputStream(InputStream in, long length) + { + this.in = in; + remaining = length; + } + + @Override + public int read() throws IOException + { + if ((remaining -= 1) < 0) + { + return -1; + } + + return in.read(); + } + + @Override + public int read(byte[] cbuf, int off, int len) throws IOException + { + if (remaining <= 0) + { + return -1; + } + + if (len > remaining) + { + len = (int)remaining; + } + + len = in.read(cbuf, off, len); + if (len > 0) + { + remaining -= len; + } + else + { + remaining -= remaining; + } + + return len; + } + + @Override + public long skip(long n) throws IOException + { + if (n > remaining) + { + n = remaining; + } + + remaining -= n = in.skip(n); + return n; + } + + @Override + public boolean markSupported() + { + return in.markSupported(); + } + + @Override + public synchronized void mark(int readlimit) + { + if (markSupported()) + { + in.mark(readlimit); + remainingAtMark = remaining; + } + } + + @Override + public synchronized void reset() throws IOException + { + in.reset(); + remaining = remainingAtMark; + } + + @Override + public void close() throws IOException + { + remaining = 0; + in.close(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java index e1839cfbf9..deb805eedf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/LimitedReader.java @@ -1,112 +1,112 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.Reader;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public class LimitedReader extends Reader
-{
- private Reader in;
-
- private long remaining;
-
- private long remainingAtMark = 0;
-
- public LimitedReader(Reader in, long length)
- {
- this.in = in;
- remaining = length;
- }
-
- @Override
- public int read() throws IOException
- {
- if ((remaining -= 1) < 0)
- {
- return -1;
- }
-
- return in.read();
- }
-
- @Override
- public int read(char[] cbuf, int off, int len) throws IOException
- {
- if (remaining <= 0)
- {
- return -1;
- }
-
- if (len > remaining)
- {
- len = (int)remaining;
- }
-
- len = in.read(cbuf, off, len);
- if (len > 0)
- {
- remaining -= len;
- }
- else
- {
- remaining -= remaining;
- }
-
- return len;
- }
-
- @Override
- public long skip(long n) throws IOException
- {
- if (n > remaining)
- {
- n = remaining;
- }
-
- remaining -= n = in.skip(n);
- return n;
- }
-
- @Override
- public boolean markSupported()
- {
- return in.markSupported();
- }
-
- @Override
- public void mark(int readlimit) throws IOException
- {
- if (markSupported())
- {
- in.mark(readlimit);
- remainingAtMark = remaining;
- }
- }
-
- @Override
- public void reset() throws IOException
- {
- in.reset();
- remaining = remainingAtMark;
- }
-
- @Override
- public void close() throws IOException
- {
- remaining = 0;
- in.close();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.Reader; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public class LimitedReader extends Reader +{ + private Reader in; + + private long remaining; + + private long remainingAtMark = 0; + + public LimitedReader(Reader in, long length) + { + this.in = in; + remaining = length; + } + + @Override + public int read() throws IOException + { + if ((remaining -= 1) < 0) + { + return -1; + } + + return in.read(); + } + + @Override + public int read(char[] cbuf, int off, int len) throws IOException + { + if (remaining <= 0) + { + return -1; + } + + if (len > remaining) + { + len = (int)remaining; + } + + len = in.read(cbuf, off, len); + if (len > 0) + { + remaining -= len; + } + else + { + remaining -= remaining; + } + + return len; + } + + @Override + public long skip(long n) throws IOException + { + if (n > remaining) + { + n = remaining; + } + + remaining -= n = in.skip(n); + return n; + } + + @Override + public boolean markSupported() + { + return in.markSupported(); + } + + @Override + public void mark(int readlimit) throws IOException + { + if (markSupported()) + { + in.mark(readlimit); + remainingAtMark = remaining; + } + } + + @Override + public void reset() throws IOException + { + in.reset(); + remaining = remainingAtMark; + } + + @Override + public void close() throws IOException + { + remaining = 0; + in.close(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java index cff41b6bd9..ddd2dce2ec 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/NIOUtil.java @@ -1,219 +1,219 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.ImplementationError;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.nio.channels.FileChannel;
-
-/**
- * @author Eike Stepper
- */
-public final class NIOUtil
-{
- private NIOUtil()
- {
- }
-
- /**
- * TODO Look at {@link #copy(File, File, boolean)}
- */
- public static void copyFile(File source, File target)
- {
- // http://www.javalobby.org/java/forums/t17036.html
- // http://java.sun.com/developer/JDCTechTips/2002/tt0507.html#tip1
- FileChannel sourceChannel = null;
- FileChannel targetChannel = null;
-
- try
- {
- if (!target.getParentFile().exists())
- {
- target.getParentFile().mkdirs();
- }
-
- if (!target.exists())
- {
- target.createNewFile();
- }
-
- sourceChannel = new FileInputStream(source).getChannel();
- targetChannel = new FileOutputStream(target).getChannel();
-
- long size = sourceChannel.size();
- long transfered = sourceChannel.transferTo(0, size, targetChannel);
- if (transfered != size)
- {
- throw new ImplementationError("Seems as if a loop must be implemented here"); //$NON-NLS-1$
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- IOUtil.closeSilent(sourceChannel);
- IOUtil.closeSilent(targetChannel);
- }
- }
-
- /**
- * Copy source file to destination. If destination is a path then source file name is appended. If destination file
- * exists then: overwrite=true - destination file is replaced; overwite=false - exception is thrown.
- *
- * @param src
- * source file
- * @param dst
- * destination file or path
- * @param overwrite
- * overwrite destination file
- * @exception IOException
- * I/O problem
- */
- @SuppressWarnings("unused")
- private static void copy(final File src, File dst, final boolean overwrite) throws IOException
- {
- if (!src.isFile() || !src.exists())
- {
- throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- if (dst.exists())
- {
- if (dst.isDirectory())
- {
- // name
- dst = new File(dst, src.getName());
- }
- else if (dst.isFile())
- {
- if (!overwrite)
- {
- throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
- else
- {
- throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- File dstParent = dst.getParentFile();
- if (!dstParent.exists())
- {
- if (!dstParent.mkdirs())
- {
- throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); //$NON-NLS-1$
- }
- }
-
- long fileSize = src.length();
- if (fileSize > 20971520l)
- { // for larger files (20Mb) use streams
- FileInputStream in = new FileInputStream(src);
- FileOutputStream out = new FileOutputStream(dst);
- try
- {
- int doneCnt = -1, bufSize = 32768;
- byte buf[] = new byte[bufSize];
- while ((doneCnt = in.read(buf, 0, bufSize)) >= 0)
- {
- if (doneCnt == 0)
- {
- Thread.yield();
- }
- else
- {
- out.write(buf, 0, doneCnt);
- }
- }
-
- out.flush();
- }
- finally
- {
- try
- {
- in.close();
- }
- catch (IOException e)
- {
- }
-
- try
- {
- out.close();
- }
- catch (IOException e)
- {
- }
- }
- }
- else
- { // smaller files, use channels
- FileInputStream fis = new FileInputStream(src);
- FileOutputStream fos = new FileOutputStream(dst);
- FileChannel in = fis.getChannel(), out = fos.getChannel();
-
- try
- {
- long offs = 0, doneCnt = 0, copyCnt = Math.min(65536, fileSize);
- do
- {
- doneCnt = in.transferTo(offs, copyCnt, out);
- offs += doneCnt;
- fileSize -= doneCnt;
- }
-
- while (fileSize > 0);
- }
- finally
- { // cleanup
- try
- {
- in.close();
- }
- catch (IOException e)
- {
- }
-
- try
- {
- out.close();
- }
- catch (IOException e)
- {
- }
-
- try
- {
- fis.close();
- }
- catch (IOException e)
- {
- }
-
- try
- {
- fos.close();
- }
- catch (IOException ex)
- {
- }
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.ImplementationError; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.channels.FileChannel; + +/** + * @author Eike Stepper + */ +public final class NIOUtil +{ + private NIOUtil() + { + } + + /** + * TODO Look at {@link #copy(File, File, boolean)} + */ + public static void copyFile(File source, File target) + { + // http://www.javalobby.org/java/forums/t17036.html + // http://java.sun.com/developer/JDCTechTips/2002/tt0507.html#tip1 + FileChannel sourceChannel = null; + FileChannel targetChannel = null; + + try + { + if (!target.getParentFile().exists()) + { + target.getParentFile().mkdirs(); + } + + if (!target.exists()) + { + target.createNewFile(); + } + + sourceChannel = new FileInputStream(source).getChannel(); + targetChannel = new FileOutputStream(target).getChannel(); + + long size = sourceChannel.size(); + long transfered = sourceChannel.transferTo(0, size, targetChannel); + if (transfered != size) + { + throw new ImplementationError("Seems as if a loop must be implemented here"); //$NON-NLS-1$ + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + IOUtil.closeSilent(sourceChannel); + IOUtil.closeSilent(targetChannel); + } + } + + /** + * Copy source file to destination. If destination is a path then source file name is appended. If destination file + * exists then: overwrite=true - destination file is replaced; overwite=false - exception is thrown. + * + * @param src + * source file + * @param dst + * destination file or path + * @param overwrite + * overwrite destination file + * @exception IOException + * I/O problem + */ + @SuppressWarnings("unused") + private static void copy(final File src, File dst, final boolean overwrite) throws IOException + { + if (!src.isFile() || !src.exists()) + { + throw new IllegalArgumentException("Source file '" + src.getAbsolutePath() + "' not found!"); //$NON-NLS-1$ //$NON-NLS-2$ + } + + if (dst.exists()) + { + if (dst.isDirectory()) + { + // name + dst = new File(dst, src.getName()); + } + else if (dst.isFile()) + { + if (!overwrite) + { + throw new IllegalArgumentException("Destination file '" + dst.getAbsolutePath() + "' already exists!"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + else + { + throw new IllegalArgumentException("Invalid destination object '" + dst.getAbsolutePath() + "'!"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + File dstParent = dst.getParentFile(); + if (!dstParent.exists()) + { + if (!dstParent.mkdirs()) + { + throw new IOException("Failed to create directory " + dstParent.getAbsolutePath()); //$NON-NLS-1$ + } + } + + long fileSize = src.length(); + if (fileSize > 20971520l) + { // for larger files (20Mb) use streams + FileInputStream in = new FileInputStream(src); + FileOutputStream out = new FileOutputStream(dst); + try + { + int doneCnt = -1, bufSize = 32768; + byte buf[] = new byte[bufSize]; + while ((doneCnt = in.read(buf, 0, bufSize)) >= 0) + { + if (doneCnt == 0) + { + Thread.yield(); + } + else + { + out.write(buf, 0, doneCnt); + } + } + + out.flush(); + } + finally + { + try + { + in.close(); + } + catch (IOException e) + { + } + + try + { + out.close(); + } + catch (IOException e) + { + } + } + } + else + { // smaller files, use channels + FileInputStream fis = new FileInputStream(src); + FileOutputStream fos = new FileOutputStream(dst); + FileChannel in = fis.getChannel(), out = fos.getChannel(); + + try + { + long offs = 0, doneCnt = 0, copyCnt = Math.min(65536, fileSize); + do + { + doneCnt = in.transferTo(offs, copyCnt, out); + offs += doneCnt; + fileSize -= doneCnt; + } + + while (fileSize > 0); + } + finally + { // cleanup + try + { + in.close(); + } + catch (IOException e) + { + } + + try + { + out.close(); + } + catch (IOException e) + { + } + + try + { + fis.close(); + } + catch (IOException e) + { + } + + try + { + fos.close(); + } + catch (IOException ex) + { + } + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java index 661d147503..85de906902 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/SortedFileMap.java @@ -1,231 +1,231 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.Closeable;
-import java.io.File;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-
-/**
- * @author Eike Stepper
- */
-public abstract class SortedFileMap<K extends Comparable<K>, V> implements Closeable
-{
- private File file;
-
- private RandomAccessFile randomAccessFile;
-
- private ExtendedDataInput input;
-
- private ExtendedDataOutput output;
-
- private long entrySize;
-
- private long entryCount;
-
- /**
- * @see RandomAccessFile#RandomAccessFile(File, String)
- */
- public SortedFileMap(File file, String mode)
- {
- try
- {
- this.file = file;
- randomAccessFile = new RandomAccessFile(file, mode);
- input = new DataInputExtender(randomAccessFile);
- output = new DataOutputExtender(randomAccessFile);
- entrySize = getKeySize() + getValueSize();
- entryCount = randomAccessFile.length() / entrySize;
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public void close() throws IOException
- {
- IOUtil.close(randomAccessFile);
- }
-
- public File getFile()
- {
- return file;
- }
-
- public RandomAccessFile getRandomAccessFile()
- {
- return randomAccessFile;
- }
-
- public long getEntryCount()
- {
- return entryCount;
- }
-
- public int getEntrySize()
- {
- return (int)entrySize;
- }
-
- public long getPosition(long index)
- {
- return index * entrySize;
- }
-
- public long getValuePosition(long index)
- {
- return getPosition(index) + getKeySize();
- }
-
- public K getMaxKey()
- {
- if (entryCount == 0)
- {
- return null;
- }
-
- return getKey(entryCount - 1);
- }
-
- public K getKey(long index)
- {
- try
- {
- long pos = getPosition(index);
- randomAccessFile.seek(pos);
- return readKey(input);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public V getValue(long index)
- {
- try
- {
- long pos = getValuePosition(index);
- randomAccessFile.seek(pos);
- return readValue(input);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public V get(K key)
- {
- try
- {
- long index = search(key);
- if (index < 0)
- {
- return null;
- }
-
- return readValue(input);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- public V put(K key, V value)
- {
- try
- {
- long index = search(key);
- if (index >= 0)
- {
- long pos = getValuePosition(index);
- randomAccessFile.seek(pos);
- V oldValue = readValue(input);
- randomAccessFile.seek(pos);
- writeValue(output, value);
- return oldValue;
- }
-
- index = -index - 1;
- for (long i = entryCount; i > index; --i)
- {
- randomAccessFile.seek(getPosition(i - 1));
- K k = readKey(input);
- randomAccessFile.seek(getValuePosition(i - 1));
- V v = readValue(input);
-
- randomAccessFile.seek(getPosition(i));
- writeKey(output, k);
- randomAccessFile.seek(getValuePosition(i));
- writeValue(output, v);
- }
-
- ++entryCount;
- randomAccessFile.seek(getPosition(index));
- writeKey(output, key);
- randomAccessFile.seek(getValuePosition(index));
- writeValue(output, value);
- return null;
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- /**
- * @return The index of the entry with the given key if the key exists, <code>-(insertionIndex + 1)</code> otherwise.
- */
- protected long search(K key) throws IOException
- {
- long low = 0;
- long high = entryCount - 1;
-
- while (low <= high)
- {
- long mid = low + high >> 1;
- randomAccessFile.seek(getPosition(mid));
- Comparable<K> midVal = readKey(input);
- int cmp = midVal.compareTo(key);
-
- if (cmp < 0)
- {
- low = mid + 1;
- }
- else if (cmp > 0)
- {
- high = mid - 1;
- }
- else
- {
- return mid; // key found
- }
- }
-
- return -(low + 1); // key not found.
- }
-
- public abstract int getKeySize();
-
- protected abstract K readKey(ExtendedDataInput in) throws IOException;
-
- protected abstract void writeKey(ExtendedDataOutput out, K key) throws IOException;
-
- public abstract int getValueSize();
-
- protected abstract V readValue(ExtendedDataInput in) throws IOException;
-
- protected abstract void writeValue(ExtendedDataOutput out, V value) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; + +/** + * @author Eike Stepper + */ +public abstract class SortedFileMap<K extends Comparable<K>, V> implements Closeable +{ + private File file; + + private RandomAccessFile randomAccessFile; + + private ExtendedDataInput input; + + private ExtendedDataOutput output; + + private long entrySize; + + private long entryCount; + + /** + * @see RandomAccessFile#RandomAccessFile(File, String) + */ + public SortedFileMap(File file, String mode) + { + try + { + this.file = file; + randomAccessFile = new RandomAccessFile(file, mode); + input = new DataInputExtender(randomAccessFile); + output = new DataOutputExtender(randomAccessFile); + entrySize = getKeySize() + getValueSize(); + entryCount = randomAccessFile.length() / entrySize; + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public void close() throws IOException + { + IOUtil.close(randomAccessFile); + } + + public File getFile() + { + return file; + } + + public RandomAccessFile getRandomAccessFile() + { + return randomAccessFile; + } + + public long getEntryCount() + { + return entryCount; + } + + public int getEntrySize() + { + return (int)entrySize; + } + + public long getPosition(long index) + { + return index * entrySize; + } + + public long getValuePosition(long index) + { + return getPosition(index) + getKeySize(); + } + + public K getMaxKey() + { + if (entryCount == 0) + { + return null; + } + + return getKey(entryCount - 1); + } + + public K getKey(long index) + { + try + { + long pos = getPosition(index); + randomAccessFile.seek(pos); + return readKey(input); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public V getValue(long index) + { + try + { + long pos = getValuePosition(index); + randomAccessFile.seek(pos); + return readValue(input); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public V get(K key) + { + try + { + long index = search(key); + if (index < 0) + { + return null; + } + + return readValue(input); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + public V put(K key, V value) + { + try + { + long index = search(key); + if (index >= 0) + { + long pos = getValuePosition(index); + randomAccessFile.seek(pos); + V oldValue = readValue(input); + randomAccessFile.seek(pos); + writeValue(output, value); + return oldValue; + } + + index = -index - 1; + for (long i = entryCount; i > index; --i) + { + randomAccessFile.seek(getPosition(i - 1)); + K k = readKey(input); + randomAccessFile.seek(getValuePosition(i - 1)); + V v = readValue(input); + + randomAccessFile.seek(getPosition(i)); + writeKey(output, k); + randomAccessFile.seek(getValuePosition(i)); + writeValue(output, v); + } + + ++entryCount; + randomAccessFile.seek(getPosition(index)); + writeKey(output, key); + randomAccessFile.seek(getValuePosition(index)); + writeValue(output, value); + return null; + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + /** + * @return The index of the entry with the given key if the key exists, <code>-(insertionIndex + 1)</code> otherwise. + */ + protected long search(K key) throws IOException + { + long low = 0; + long high = entryCount - 1; + + while (low <= high) + { + long mid = low + high >> 1; + randomAccessFile.seek(getPosition(mid)); + Comparable<K> midVal = readKey(input); + int cmp = midVal.compareTo(key); + + if (cmp < 0) + { + low = mid + 1; + } + else if (cmp > 0) + { + high = mid - 1; + } + else + { + return mid; // key found + } + } + + return -(low + 1); // key not found. + } + + public abstract int getKeySize(); + + protected abstract K readKey(ExtendedDataInput in) throws IOException; + + protected abstract void writeKey(ExtendedDataOutput out, K key) throws IOException; + + public abstract int getValueSize(); + + protected abstract V readValue(ExtendedDataInput in) throws IOException; + + protected abstract void writeValue(ExtendedDataOutput out, V value) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java index 857b1aabbf..adf31c18ac 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StreamWrapperChain.java @@ -1,58 +1,58 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public class StreamWrapperChain extends DelegatingStreamWrapper
-{
- private IStreamWrapper head;
-
- public StreamWrapperChain(IStreamWrapper head, IStreamWrapper delegate)
- {
- super(delegate);
- this.head = head;
- }
-
- public IStreamWrapper getHead()
- {
- return head;
- }
-
- @Override
- protected InputStream doWrapInputStream(InputStream in) throws IOException
- {
- return head.wrapInputStream(in);
- }
-
- @Override
- protected OutputStream doWrapOutputStream(OutputStream out) throws IOException
- {
- return head.wrapOutputStream(out);
- }
-
- @Override
- protected void doFinishInputStream(InputStream in) throws IOException
- {
- head.finishInputStream(in);
- }
-
- @Override
- protected void doFinishOutputStream(OutputStream out) throws IOException
- {
- head.finishOutputStream(out);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public class StreamWrapperChain extends DelegatingStreamWrapper +{ + private IStreamWrapper head; + + public StreamWrapperChain(IStreamWrapper head, IStreamWrapper delegate) + { + super(delegate); + this.head = head; + } + + public IStreamWrapper getHead() + { + return head; + } + + @Override + protected InputStream doWrapInputStream(InputStream in) throws IOException + { + return head.wrapInputStream(in); + } + + @Override + protected OutputStream doWrapOutputStream(OutputStream out) throws IOException + { + return head.wrapOutputStream(out); + } + + @Override + protected void doFinishInputStream(InputStream in) throws IOException + { + head.finishInputStream(in); + } + + @Override + protected void doFinishOutputStream(OutputStream out) throws IOException + { + head.finishOutputStream(out); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java index f6ede4f264..5ff9b4f286 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringCompressor.java @@ -1,456 +1,456 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.CheckUtil;
-
-import java.io.IOException;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class StringCompressor implements StringIO
-{
- /**
- * @since 3.0
- */
- public static boolean BYPASS = false;
-
- private static final int NULL_ID = 0;
-
- private static final int INFO_FOLLOWS = Integer.MIN_VALUE;
-
- private static final byte NOTHING_FOLLOWS = 1;
-
- private static final byte STRING_FOLLOWS = 2;
-
- private static final byte ACK_FOLLOWS = 3;
-
- private static final boolean DEBUG = false;
-
- private static final byte DEBUG_STRING = -1;
-
- private static final byte DEBUG_INT = -2;
-
- private static final byte DEBUG_BYTE = -3;
-
- private boolean client;
-
- private int lastID;
-
- private Map<String, ID> stringToID = new HashMap<String, ID>();
-
- private Map<Integer, String> idToString = new HashMap<Integer, String>();
-
- private List<Integer> pendingAcknowledgements = new ArrayList<Integer>();
-
- /**
- * Creates a StringCompressor instance.
- *
- * @param client
- * Must be different on both sides of the stream.
- */
- public StringCompressor(boolean client)
- {
- this.client = client;
- }
-
- public boolean isClient()
- {
- return client;
- }
-
- public void write(ExtendedDataOutput out, String string) throws IOException
- {
- if (DEBUG)
- {
- trace("BEGIN", string);
- }
-
- if (string == null)
- {
- writeInt(out, NULL_ID);
- return;
- }
-
- ID id;
- List<Integer> acknowledgements = null;
- boolean stringFollows = false;
- synchronized (this)
- {
- id = stringToID.get(string);
- if (id == null)
- {
- lastID += client ? 1 : -1;
- id = new ID(lastID);
-
- stringToID.put(string, id);
- idToString.put(id.getValue(), string);
- stringFollows = true;
- }
- else if (!id.isAcknowledged())
- {
- stringFollows = true;
- }
-
- if (!pendingAcknowledgements.isEmpty())
- {
- acknowledgements = pendingAcknowledgements;
- pendingAcknowledgements = new ArrayList<Integer>();
- }
- }
-
- if (stringFollows || acknowledgements != null)
- {
- writeInt(out, INFO_FOLLOWS);
- writeInt(out, id.getValue());
-
- if (stringFollows)
- {
- writeByte(out, STRING_FOLLOWS);
- writeString(out, string);
- }
-
- if (acknowledgements != null)
- {
- for (int ack : acknowledgements)
- {
- writeByte(out, ACK_FOLLOWS);
- writeInt(out, ack);
- }
- }
-
- writeByte(out, NOTHING_FOLLOWS);
- }
- else
- {
- writeInt(out, id.getValue());
- }
- }
-
- public String read(ExtendedDataInput in) throws IOException
- {
- if (DEBUG)
- {
- trace("BEGIN", "?");
- }
-
- int id = readInt(in);
- if (id == NULL_ID)
- {
- return null;
- }
-
- String string = null;
- List<Integer> acks = null;
- if (id == INFO_FOLLOWS)
- {
- id = readInt(in);
-
- boolean moreInfos = true;
- while (moreInfos)
- {
- byte info = readByte(in);
- switch (info)
- {
- case NOTHING_FOLLOWS:
- moreInfos = false;
- break;
-
- case STRING_FOLLOWS:
- string = readString(in);
- break;
-
- case ACK_FOLLOWS:
- if (acks == null)
- {
- acks = new ArrayList<Integer>();
- }
-
- acks.add(readInt(in));
- break;
-
- default:
- throw new IOException("Invalid info: " + info); //$NON-NLS-1$
- }
- }
- }
-
- synchronized (this)
- {
- acknowledge(acks);
- if (string != null)
- {
- stringToID.put(string, new ID(id));
- idToString.put(id, string);
- pendingAcknowledgements.add(id);
- }
- else
- {
- string = idToString.get(id);
- if (string == null)
- {
- throw new IOException("String ID unknown: " + id); //$NON-NLS-1$
- }
- }
- }
-
- return string;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("StringCompressor[client={0}]", client); //$NON-NLS-1$
- }
-
- private void acknowledge(List<Integer> acks)
- {
- if (acks != null)
- {
- for (int value : acks)
- {
- String string = idToString.get(value);
- if (string != null)
- {
- ID id = stringToID.get(string);
- if (id != null)
- {
- id.setAcknowledged();
- }
- }
- }
- }
- }
-
- private void writeByte(ExtendedDataOutput out, byte value) throws IOException
- {
- if (DEBUG)
- {
- trace("writeByte", value);
- out.writeByte(DEBUG_BYTE);
- }
-
- out.writeByte(value);
- }
-
- private void writeInt(ExtendedDataOutput out, int value) throws IOException
- {
- if (DEBUG)
- {
- trace("writeInt", value);
- out.writeByte(DEBUG_INT);
- }
-
- out.writeInt(value);
- }
-
- /**
- * @since 3.0
- */
- protected void writeString(ExtendedDataOutput out, String value) throws IOException
- {
- if (DEBUG)
- {
- trace("writeString", value);
- out.writeByte(DEBUG_STRING);
- }
-
- out.writeString(value);
- }
-
- private byte readByte(ExtendedDataInput in) throws IOException
- {
- if (DEBUG)
- {
- byte type = in.readByte();
- if (DEBUG_BYTE != type)
- {
- throw new IOException("Not a byte value (type=" + type + ")"); //$NON-NLS-1$
- }
- }
-
- byte value = in.readByte();
- if (DEBUG)
- {
- trace("readByte", value);
- }
-
- return value;
- }
-
- private int readInt(ExtendedDataInput in) throws IOException
- {
- if (DEBUG)
- {
- byte type = in.readByte();
- if (DEBUG_INT != type)
- {
- throw new IOException("Not an integer value (type=" + type + ")"); //$NON-NLS-1$
- }
- }
-
- int value = in.readInt();
- if (DEBUG)
- {
- trace("readInt", value);
- }
-
- return value;
- }
-
- /**
- * @since 3.0
- */
- protected String readString(ExtendedDataInput in) throws IOException
- {
- if (DEBUG)
- {
- byte type = in.readByte();
- if (DEBUG_STRING != type)
- {
- throw new IOException("Not a string value (type=" + type + ")"); //$NON-NLS-1$
- }
- }
-
- String value = in.readString();
- if (DEBUG)
- {
- trace("readString", value);
- }
-
- return value;
- }
-
- private void trace(String prefix, Object value)
- {
- if (value instanceof Byte)
- {
- byte opcode = (Byte)value;
- switch (opcode)
- {
- case NOTHING_FOLLOWS:
- value = "NOTHING_FOLLOWS";
- break;
-
- case STRING_FOLLOWS:
- value = "STRING_FOLLOWS";
- break;
-
- case ACK_FOLLOWS:
- value = "STRING_FOLLOWS";
- break;
- }
- }
-
- if (value instanceof Integer)
- {
- int opcode = (Integer)value;
- if (opcode == INFO_FOLLOWS)
- {
- value = "INFO_FOLLOWS";
- }
- }
-
- String msg = "[" + Thread.currentThread().getName() + "] " + prefix + ": " + value;
- if (!client)
- {
- msg = " " + msg;
- }
-
- IOUtil.OUT().println(msg);
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class ID
- {
- private int value;
-
- private boolean acknowledged;
-
- public ID(int value)
- {
- CheckUtil.checkArg(value != INFO_FOLLOWS, "value");
- this.value = value;
- }
-
- public int getValue()
- {
- return value;
- }
-
- public boolean isAcknowledged()
- {
- return acknowledged;
- }
-
- public void setAcknowledged()
- {
- acknowledged = true;
- }
- }
-
- /**
- * @author Eike Stepper
- * @since 3.0
- */
- public static class Counting extends StringCompressor
- {
- private long stringsRead;
-
- private long stringsWritten;
-
- public Counting(boolean client)
- {
- super(client);
- }
-
- public long getStringsRead()
- {
- return stringsRead;
- }
-
- public long getStringsWritten()
- {
- return stringsWritten;
- }
-
- @Override
- protected String readString(ExtendedDataInput in) throws IOException
- {
- synchronized (this)
- {
- ++stringsRead;
- }
-
- return super.readString(in);
- }
-
- @Override
- protected void writeString(ExtendedDataOutput out, String value) throws IOException
- {
- synchronized (this)
- {
- ++stringsWritten;
- }
-
- super.writeString(out, value);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.CheckUtil; + +import java.io.IOException; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class StringCompressor implements StringIO +{ + /** + * @since 3.0 + */ + public static boolean BYPASS = false; + + private static final int NULL_ID = 0; + + private static final int INFO_FOLLOWS = Integer.MIN_VALUE; + + private static final byte NOTHING_FOLLOWS = 1; + + private static final byte STRING_FOLLOWS = 2; + + private static final byte ACK_FOLLOWS = 3; + + private static final boolean DEBUG = false; + + private static final byte DEBUG_STRING = -1; + + private static final byte DEBUG_INT = -2; + + private static final byte DEBUG_BYTE = -3; + + private boolean client; + + private int lastID; + + private Map<String, ID> stringToID = new HashMap<String, ID>(); + + private Map<Integer, String> idToString = new HashMap<Integer, String>(); + + private List<Integer> pendingAcknowledgements = new ArrayList<Integer>(); + + /** + * Creates a StringCompressor instance. + * + * @param client + * Must be different on both sides of the stream. + */ + public StringCompressor(boolean client) + { + this.client = client; + } + + public boolean isClient() + { + return client; + } + + public void write(ExtendedDataOutput out, String string) throws IOException + { + if (DEBUG) + { + trace("BEGIN", string); + } + + if (string == null) + { + writeInt(out, NULL_ID); + return; + } + + ID id; + List<Integer> acknowledgements = null; + boolean stringFollows = false; + synchronized (this) + { + id = stringToID.get(string); + if (id == null) + { + lastID += client ? 1 : -1; + id = new ID(lastID); + + stringToID.put(string, id); + idToString.put(id.getValue(), string); + stringFollows = true; + } + else if (!id.isAcknowledged()) + { + stringFollows = true; + } + + if (!pendingAcknowledgements.isEmpty()) + { + acknowledgements = pendingAcknowledgements; + pendingAcknowledgements = new ArrayList<Integer>(); + } + } + + if (stringFollows || acknowledgements != null) + { + writeInt(out, INFO_FOLLOWS); + writeInt(out, id.getValue()); + + if (stringFollows) + { + writeByte(out, STRING_FOLLOWS); + writeString(out, string); + } + + if (acknowledgements != null) + { + for (int ack : acknowledgements) + { + writeByte(out, ACK_FOLLOWS); + writeInt(out, ack); + } + } + + writeByte(out, NOTHING_FOLLOWS); + } + else + { + writeInt(out, id.getValue()); + } + } + + public String read(ExtendedDataInput in) throws IOException + { + if (DEBUG) + { + trace("BEGIN", "?"); + } + + int id = readInt(in); + if (id == NULL_ID) + { + return null; + } + + String string = null; + List<Integer> acks = null; + if (id == INFO_FOLLOWS) + { + id = readInt(in); + + boolean moreInfos = true; + while (moreInfos) + { + byte info = readByte(in); + switch (info) + { + case NOTHING_FOLLOWS: + moreInfos = false; + break; + + case STRING_FOLLOWS: + string = readString(in); + break; + + case ACK_FOLLOWS: + if (acks == null) + { + acks = new ArrayList<Integer>(); + } + + acks.add(readInt(in)); + break; + + default: + throw new IOException("Invalid info: " + info); //$NON-NLS-1$ + } + } + } + + synchronized (this) + { + acknowledge(acks); + if (string != null) + { + stringToID.put(string, new ID(id)); + idToString.put(id, string); + pendingAcknowledgements.add(id); + } + else + { + string = idToString.get(id); + if (string == null) + { + throw new IOException("String ID unknown: " + id); //$NON-NLS-1$ + } + } + } + + return string; + } + + @Override + public String toString() + { + return MessageFormat.format("StringCompressor[client={0}]", client); //$NON-NLS-1$ + } + + private void acknowledge(List<Integer> acks) + { + if (acks != null) + { + for (int value : acks) + { + String string = idToString.get(value); + if (string != null) + { + ID id = stringToID.get(string); + if (id != null) + { + id.setAcknowledged(); + } + } + } + } + } + + private void writeByte(ExtendedDataOutput out, byte value) throws IOException + { + if (DEBUG) + { + trace("writeByte", value); + out.writeByte(DEBUG_BYTE); + } + + out.writeByte(value); + } + + private void writeInt(ExtendedDataOutput out, int value) throws IOException + { + if (DEBUG) + { + trace("writeInt", value); + out.writeByte(DEBUG_INT); + } + + out.writeInt(value); + } + + /** + * @since 3.0 + */ + protected void writeString(ExtendedDataOutput out, String value) throws IOException + { + if (DEBUG) + { + trace("writeString", value); + out.writeByte(DEBUG_STRING); + } + + out.writeString(value); + } + + private byte readByte(ExtendedDataInput in) throws IOException + { + if (DEBUG) + { + byte type = in.readByte(); + if (DEBUG_BYTE != type) + { + throw new IOException("Not a byte value (type=" + type + ")"); //$NON-NLS-1$ + } + } + + byte value = in.readByte(); + if (DEBUG) + { + trace("readByte", value); + } + + return value; + } + + private int readInt(ExtendedDataInput in) throws IOException + { + if (DEBUG) + { + byte type = in.readByte(); + if (DEBUG_INT != type) + { + throw new IOException("Not an integer value (type=" + type + ")"); //$NON-NLS-1$ + } + } + + int value = in.readInt(); + if (DEBUG) + { + trace("readInt", value); + } + + return value; + } + + /** + * @since 3.0 + */ + protected String readString(ExtendedDataInput in) throws IOException + { + if (DEBUG) + { + byte type = in.readByte(); + if (DEBUG_STRING != type) + { + throw new IOException("Not a string value (type=" + type + ")"); //$NON-NLS-1$ + } + } + + String value = in.readString(); + if (DEBUG) + { + trace("readString", value); + } + + return value; + } + + private void trace(String prefix, Object value) + { + if (value instanceof Byte) + { + byte opcode = (Byte)value; + switch (opcode) + { + case NOTHING_FOLLOWS: + value = "NOTHING_FOLLOWS"; + break; + + case STRING_FOLLOWS: + value = "STRING_FOLLOWS"; + break; + + case ACK_FOLLOWS: + value = "STRING_FOLLOWS"; + break; + } + } + + if (value instanceof Integer) + { + int opcode = (Integer)value; + if (opcode == INFO_FOLLOWS) + { + value = "INFO_FOLLOWS"; + } + } + + String msg = "[" + Thread.currentThread().getName() + "] " + prefix + ": " + value; + if (!client) + { + msg = " " + msg; + } + + IOUtil.OUT().println(msg); + } + + /** + * @author Eike Stepper + */ + private static final class ID + { + private int value; + + private boolean acknowledged; + + public ID(int value) + { + CheckUtil.checkArg(value != INFO_FOLLOWS, "value"); + this.value = value; + } + + public int getValue() + { + return value; + } + + public boolean isAcknowledged() + { + return acknowledged; + } + + public void setAcknowledged() + { + acknowledged = true; + } + } + + /** + * @author Eike Stepper + * @since 3.0 + */ + public static class Counting extends StringCompressor + { + private long stringsRead; + + private long stringsWritten; + + public Counting(boolean client) + { + super(client); + } + + public long getStringsRead() + { + return stringsRead; + } + + public long getStringsWritten() + { + return stringsWritten; + } + + @Override + protected String readString(ExtendedDataInput in) throws IOException + { + synchronized (this) + { + ++stringsRead; + } + + return super.readString(in); + } + + @Override + protected void writeString(ExtendedDataOutput out, String value) throws IOException + { + synchronized (this) + { + ++stringsWritten; + } + + super.writeString(out, value); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java index e522b2532b..bdb26c3ac4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/StringIO.java @@ -1,43 +1,43 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface StringIO
-{
- public static final StringIO DIRECT = new StringIO()
- {
- public void write(ExtendedDataOutput out, String string) throws IOException
- {
- out.writeString(string);
- }
-
- public String read(ExtendedDataInput in) throws IOException
- {
- return in.readString();
- }
-
- @Override
- public String toString()
- {
- return "DIRECT"; //$NON-NLS-1$
- }
- };
-
- public void write(ExtendedDataOutput out, String string) throws IOException;
-
- public String read(ExtendedDataInput in) throws IOException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface StringIO +{ + public static final StringIO DIRECT = new StringIO() + { + public void write(ExtendedDataOutput out, String string) throws IOException + { + out.writeString(string); + } + + public String read(ExtendedDataInput in) throws IOException + { + return in.readString(); + } + + @Override + public String toString() + { + return "DIRECT"; //$NON-NLS-1$ + } + }; + + public void write(ExtendedDataOutput out, String string) throws IOException; + + public String read(ExtendedDataInput in) throws IOException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java index 0d1934e69b..71a8474e00 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/TMPUtil.java @@ -1,177 +1,177 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.om.OMPlatform;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-/**
- * @author Eike Stepper
- */
-public final class TMPUtil
-{
- /**
- * @since 3.0
- */
- public static final String TEMP_FOLDER_PROPERTY = "org.eclipse.net4j.util.io.tmpdir";
-
- /**
- * @since 2.0
- */
- public static final String SYSTEM_TEMP_FOLDER = OMPlatform.INSTANCE.getProperty("java.io.tmpdir"); //$NON-NLS-1$
-
- private static File tempFolder;
-
- private TMPUtil()
- {
- }
-
- /**
- * @since 3.0
- */
- public synchronized static File getTempFolder()
- {
- if (tempFolder == null)
- {
- String path = OMPlatform.INSTANCE.getProperty(TEMP_FOLDER_PROPERTY);
- if (path == null)
- {
- path = getPathFromUserHome();
- if (path == null)
- {
- path = SYSTEM_TEMP_FOLDER;
- }
- }
-
- tempFolder = new File(path);
-
- if (!tempFolder.exists())
- {
- tempFolder.mkdirs();
- }
- }
-
- return tempFolder;
- }
-
- private static String getPathFromUserHome()
- {
- File home = new File(OMPlatform.INSTANCE.getProperty("user.home"));
- File file = new File(home, TEMP_FOLDER_PROPERTY);
- if (file.exists() && file.isFile())
- {
- InputStream in = null;
-
- try
- {
- in = new FileInputStream(file);
-
- Properties properties = new Properties();
- properties.load(in);
-
- return properties.getProperty("path");
- }
- catch (Exception ignore)
- {
- }
- finally
- {
- IOUtil.closeSilent(in);
- }
- }
-
- return null;
- }
-
- /**
- * @since 3.0
- */
- public static void setTempFolder(String tempFolder)
- {
- TMPUtil.tempFolder = new File(tempFolder);
- }
-
- public static File createTempFolder() throws IORuntimeException
- {
- return createTempFolder("tmp"); //$NON-NLS-1$
- }
-
- public static File createTempFolder(String prefix) throws IORuntimeException
- {
- return createTempFolder(prefix, ""); //$NON-NLS-1$
- }
-
- public static File createTempFolder(String prefix, String suffix) throws IORuntimeException
- {
- return createTempFolder(prefix, suffix, getTempFolder());
- }
-
- public static File createTempFolder(String prefix, String suffix, File directory) throws IORuntimeException
- {
- try
- {
- File tmp = File.createTempFile(prefix, suffix, directory);
- String tmpPath = tmp.getAbsolutePath();
- tmp.delete();
- tmp = new File(tmpPath);
- tmp.mkdirs();
- return tmp;
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-
- /**
- * @since 3.1
- */
- public static File createTempFile() throws IORuntimeException
- {
- return createTempFile("tmp"); //$NON-NLS-1$
- }
-
- /**
- * @since 3.1
- */
- public static File createTempFile(String prefix) throws IORuntimeException
- {
- return createTempFile(prefix, ""); //$NON-NLS-1$
- }
-
- /**
- * @since 3.1
- */
- public static File createTempFile(String prefix, String suffix) throws IORuntimeException
- {
- return createTempFile(prefix, suffix, getTempFolder());
- }
-
- /**
- * @since 3.1
- */
- public static File createTempFile(String prefix, String suffix, File directory) throws IORuntimeException
- {
- try
- {
- return File.createTempFile(prefix, suffix, directory);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.om.OMPlatform; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * @author Eike Stepper + */ +public final class TMPUtil +{ + /** + * @since 3.0 + */ + public static final String TEMP_FOLDER_PROPERTY = "org.eclipse.net4j.util.io.tmpdir"; + + /** + * @since 2.0 + */ + public static final String SYSTEM_TEMP_FOLDER = OMPlatform.INSTANCE.getProperty("java.io.tmpdir"); //$NON-NLS-1$ + + private static File tempFolder; + + private TMPUtil() + { + } + + /** + * @since 3.0 + */ + public synchronized static File getTempFolder() + { + if (tempFolder == null) + { + String path = OMPlatform.INSTANCE.getProperty(TEMP_FOLDER_PROPERTY); + if (path == null) + { + path = getPathFromUserHome(); + if (path == null) + { + path = SYSTEM_TEMP_FOLDER; + } + } + + tempFolder = new File(path); + + if (!tempFolder.exists()) + { + tempFolder.mkdirs(); + } + } + + return tempFolder; + } + + private static String getPathFromUserHome() + { + File home = new File(OMPlatform.INSTANCE.getProperty("user.home")); + File file = new File(home, TEMP_FOLDER_PROPERTY); + if (file.exists() && file.isFile()) + { + InputStream in = null; + + try + { + in = new FileInputStream(file); + + Properties properties = new Properties(); + properties.load(in); + + return properties.getProperty("path"); + } + catch (Exception ignore) + { + } + finally + { + IOUtil.closeSilent(in); + } + } + + return null; + } + + /** + * @since 3.0 + */ + public static void setTempFolder(String tempFolder) + { + TMPUtil.tempFolder = new File(tempFolder); + } + + public static File createTempFolder() throws IORuntimeException + { + return createTempFolder("tmp"); //$NON-NLS-1$ + } + + public static File createTempFolder(String prefix) throws IORuntimeException + { + return createTempFolder(prefix, ""); //$NON-NLS-1$ + } + + public static File createTempFolder(String prefix, String suffix) throws IORuntimeException + { + return createTempFolder(prefix, suffix, getTempFolder()); + } + + public static File createTempFolder(String prefix, String suffix, File directory) throws IORuntimeException + { + try + { + File tmp = File.createTempFile(prefix, suffix, directory); + String tmpPath = tmp.getAbsolutePath(); + tmp.delete(); + tmp = new File(tmpPath); + tmp.mkdirs(); + return tmp; + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } + + /** + * @since 3.1 + */ + public static File createTempFile() throws IORuntimeException + { + return createTempFile("tmp"); //$NON-NLS-1$ + } + + /** + * @since 3.1 + */ + public static File createTempFile(String prefix) throws IORuntimeException + { + return createTempFile(prefix, ""); //$NON-NLS-1$ + } + + /** + * @since 3.1 + */ + public static File createTempFile(String prefix, String suffix) throws IORuntimeException + { + return createTempFile(prefix, suffix, getTempFolder()); + } + + /** + * @since 3.1 + */ + public static File createTempFile(String prefix, String suffix, File directory) throws IORuntimeException + { + try + { + return File.createTempFile(prefix, suffix, directory); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java index 4a8d9a48b2..778e480180 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XMLOutput.java @@ -1,317 +1,317 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import org.eclipse.net4j.util.HexUtil;
-import org.eclipse.net4j.util.WrappedException;
-
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.AttributesImpl;
-
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.sax.SAXTransformerFactory;
-import javax.xml.transform.sax.TransformerHandler;
-import javax.xml.transform.stream.StreamResult;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.Writer;
-import java.util.LinkedList;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- */
-public class XMLOutput
-{
- private static final AttributesImpl NO_ATTRIBUTES = new AttributesImpl();
-
- private TransformerHandler xmlHandler;
-
- private char[] newLine;
-
- private char[] indentation;
-
- private LinkedList<Element> stack = new LinkedList<Element>();
-
- private Element element;
-
- public XMLOutput(OutputStream out) throws TransformerConfigurationException, SAXException
- {
- setNewLine("\n");
- setIndentation(" ");
- SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
-
- xmlHandler = factory.newTransformerHandler();
-
- Transformer transformer = xmlHandler.getTransformer();
- transformer.setOutputProperty(OutputKeys.METHOD, "xml");
- transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
- transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
-
- xmlHandler.setResult(new StreamResult(out));
- xmlHandler.startDocument();
- }
-
- public void setNewLine(String newLine)
- {
- this.newLine = newLine.toCharArray();
- }
-
- public void setIndentation(String indentation)
- {
- this.indentation = indentation.toCharArray();
- }
-
- public XMLOutput element(String name) throws SAXException
- {
- flush();
- element = new Element(name);
- return this;
- }
-
- public XMLOutput attribute(String name, Object value) throws SAXException
- {
- if (value != null)
- {
- return attributeOrNull(name, value);
- }
-
- return this;
- }
-
- public XMLOutput attributeOrNull(String name, Object value) throws SAXException
- {
- checkElement();
- element.addAttribute(name, value);
- return this;
- }
-
- public Writer characters() throws SAXException
- {
- checkElement();
- newLine();
- element.start();
- xmlHandler.startCDATA();
-
- return new Writer()
- {
- @Override
- public void write(char[] cbuf, int off, int len) throws IOException
- {
- try
- {
- xmlHandler.characters(cbuf, off, len);
- }
- catch (SAXException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- @Override
- public void flush() throws IOException
- {
- // Do nothing
- }
-
- @Override
- public void close() throws IOException
- {
- try
- {
- xmlHandler.endCDATA();
- element.end();
- }
- catch (SAXException ex)
- {
- throw WrappedException.wrap(ex);
- }
- finally
- {
- element = null;
- }
- }
- };
- }
-
- public OutputStream bytes() throws SAXException
- {
- checkElement();
- newLine();
- element.start();
- xmlHandler.startCDATA();
-
- return new OutputStream()
- {
- @Override
- public void write(byte[] b, int off, int len) throws IOException
- {
- try
- {
- char[] cbuf = HexUtil.bytesToHex(b, off, len).toCharArray();
- xmlHandler.characters(cbuf, 0, cbuf.length);
- }
- catch (SAXException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- @Override
- public void write(int i) throws IOException
- {
- byte b = (byte)((i & 0xff) + Byte.MIN_VALUE);
- byte[] bs = { b };
- write(bs, 0, 1);
- }
-
- @Override
- public void close() throws IOException
- {
- try
- {
- xmlHandler.endCDATA();
- element.end();
- }
- catch (SAXException ex)
- {
- throw WrappedException.wrap(ex);
- }
- finally
- {
- element = null;
- }
- }
- };
- }
-
- public XMLOutput push() throws SAXException
- {
- newLine();
- element.start();
-
- stack.add(element);
- element = null;
- return this;
- }
-
- public XMLOutput pop() throws SAXException
- {
- flush();
- Element element = stack.removeLast();
-
- if (element.hasChildren())
- {
- newLine();
- }
-
- element.end();
- return this;
- }
-
- public void done() throws SAXException
- {
- while (!stack.isEmpty())
- {
- pop();
- }
-
- xmlHandler.endDocument();
- }
-
- private void flush() throws SAXException
- {
- if (element != null)
- {
- newLine();
- element.start();
- element.end();
- element = null;
- }
- }
-
- private void newLine() throws SAXException
- {
- xmlHandler.ignorableWhitespace(newLine, 0, newLine.length);
- for (int i = 0; i < stack.size(); i++)
- {
- xmlHandler.ignorableWhitespace(indentation, 0, indentation.length);
- }
- }
-
- private void checkElement()
- {
- if (element == null)
- {
- throw new IllegalStateException("No element");
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private final class Element
- {
- private String name;
-
- private AttributesImpl attributes;
-
- private boolean children;
-
- public Element(String name)
- {
- this.name = name;
- }
-
- public boolean hasChildren()
- {
- return children;
- }
-
- public void addChild()
- {
- children = true;
- }
-
- public void addAttribute(String name, Object value)
- {
- if (attributes == null)
- {
- attributes = new AttributesImpl();
- }
-
- if (value == null)
- {
- value = "";
- }
-
- attributes.addAttribute("", "", name, "", value.toString());
- }
-
- public void start() throws SAXException
- {
- if (!stack.isEmpty())
- {
- stack.getLast().addChild();
- }
-
- xmlHandler.startElement("", "", name, attributes == null ? NO_ATTRIBUTES : attributes);
- }
-
- public void end() throws SAXException
- {
- xmlHandler.endElement("", "", name);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import org.eclipse.net4j.util.HexUtil; +import org.eclipse.net4j.util.WrappedException; + +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamResult; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.LinkedList; + +/** + * @author Eike Stepper + * @since 3.1 + */ +public class XMLOutput +{ + private static final AttributesImpl NO_ATTRIBUTES = new AttributesImpl(); + + private TransformerHandler xmlHandler; + + private char[] newLine; + + private char[] indentation; + + private LinkedList<Element> stack = new LinkedList<Element>(); + + private Element element; + + public XMLOutput(OutputStream out) throws TransformerConfigurationException, SAXException + { + setNewLine("\n"); + setIndentation(" "); + SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); + + xmlHandler = factory.newTransformerHandler(); + + Transformer transformer = xmlHandler.getTransformer(); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + + xmlHandler.setResult(new StreamResult(out)); + xmlHandler.startDocument(); + } + + public void setNewLine(String newLine) + { + this.newLine = newLine.toCharArray(); + } + + public void setIndentation(String indentation) + { + this.indentation = indentation.toCharArray(); + } + + public XMLOutput element(String name) throws SAXException + { + flush(); + element = new Element(name); + return this; + } + + public XMLOutput attribute(String name, Object value) throws SAXException + { + if (value != null) + { + return attributeOrNull(name, value); + } + + return this; + } + + public XMLOutput attributeOrNull(String name, Object value) throws SAXException + { + checkElement(); + element.addAttribute(name, value); + return this; + } + + public Writer characters() throws SAXException + { + checkElement(); + newLine(); + element.start(); + xmlHandler.startCDATA(); + + return new Writer() + { + @Override + public void write(char[] cbuf, int off, int len) throws IOException + { + try + { + xmlHandler.characters(cbuf, off, len); + } + catch (SAXException ex) + { + throw WrappedException.wrap(ex); + } + } + + @Override + public void flush() throws IOException + { + // Do nothing + } + + @Override + public void close() throws IOException + { + try + { + xmlHandler.endCDATA(); + element.end(); + } + catch (SAXException ex) + { + throw WrappedException.wrap(ex); + } + finally + { + element = null; + } + } + }; + } + + public OutputStream bytes() throws SAXException + { + checkElement(); + newLine(); + element.start(); + xmlHandler.startCDATA(); + + return new OutputStream() + { + @Override + public void write(byte[] b, int off, int len) throws IOException + { + try + { + char[] cbuf = HexUtil.bytesToHex(b, off, len).toCharArray(); + xmlHandler.characters(cbuf, 0, cbuf.length); + } + catch (SAXException ex) + { + throw WrappedException.wrap(ex); + } + } + + @Override + public void write(int i) throws IOException + { + byte b = (byte)((i & 0xff) + Byte.MIN_VALUE); + byte[] bs = { b }; + write(bs, 0, 1); + } + + @Override + public void close() throws IOException + { + try + { + xmlHandler.endCDATA(); + element.end(); + } + catch (SAXException ex) + { + throw WrappedException.wrap(ex); + } + finally + { + element = null; + } + } + }; + } + + public XMLOutput push() throws SAXException + { + newLine(); + element.start(); + + stack.add(element); + element = null; + return this; + } + + public XMLOutput pop() throws SAXException + { + flush(); + Element element = stack.removeLast(); + + if (element.hasChildren()) + { + newLine(); + } + + element.end(); + return this; + } + + public void done() throws SAXException + { + while (!stack.isEmpty()) + { + pop(); + } + + xmlHandler.endDocument(); + } + + private void flush() throws SAXException + { + if (element != null) + { + newLine(); + element.start(); + element.end(); + element = null; + } + } + + private void newLine() throws SAXException + { + xmlHandler.ignorableWhitespace(newLine, 0, newLine.length); + for (int i = 0; i < stack.size(); i++) + { + xmlHandler.ignorableWhitespace(indentation, 0, indentation.length); + } + } + + private void checkElement() + { + if (element == null) + { + throw new IllegalStateException("No element"); + } + } + + /** + * @author Eike Stepper + */ + private final class Element + { + private String name; + + private AttributesImpl attributes; + + private boolean children; + + public Element(String name) + { + this.name = name; + } + + public boolean hasChildren() + { + return children; + } + + public void addChild() + { + children = true; + } + + public void addAttribute(String name, Object value) + { + if (attributes == null) + { + attributes = new AttributesImpl(); + } + + if (value == null) + { + value = ""; + } + + attributes.addAttribute("", "", name, "", value.toString()); + } + + public void start() throws SAXException + { + if (!stack.isEmpty()) + { + stack.getLast().addChild(); + } + + xmlHandler.startElement("", "", name, attributes == null ? NO_ATTRIBUTES : attributes); + } + + public void end() throws SAXException + { + xmlHandler.endElement("", "", name); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java index cecd5cb3aa..6d43f95d57 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORInputStream.java @@ -1,55 +1,55 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * @author Eike Stepper
- */
-public class XORInputStream extends DelegatingInputStream
-{
- private int[] key;
-
- private int index;
-
- public XORInputStream(InputStream in, int... key)
- {
- super(in);
- this.key = key;
- }
-
- public int[] getKey()
- {
- return key;
- }
-
- @Override
- public int read() throws IOException
- {
- int b = super.read();
- if (b != -1)
- {
- if (key != null && key.length != 0)
- {
- if (index == key.length)
- {
- index = 0;
- }
-
- b = b & 0xFF ^ key[index++] & 0xFF;
- }
- }
-
- return b;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * @author Eike Stepper + */ +public class XORInputStream extends DelegatingInputStream +{ + private int[] key; + + private int index; + + public XORInputStream(InputStream in, int... key) + { + super(in); + this.key = key; + } + + public int[] getKey() + { + return key; + } + + @Override + public int read() throws IOException + { + int b = super.read(); + if (b != -1) + { + if (key != null && key.length != 0) + { + if (index == key.length) + { + index = 0; + } + + b = b & 0xFF ^ key[index++] & 0xFF; + } + } + + return b; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java index e95d166e95..5f8eed40c4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XOROutputStream.java @@ -1,51 +1,51 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public class XOROutputStream extends DelegatingOutputStream
-{
- private int[] key;
-
- private int index;
-
- public XOROutputStream(OutputStream out, int... key)
- {
- super(out);
- this.key = key;
- }
-
- public int[] getKey()
- {
- return key;
- }
-
- @Override
- public void write(int b) throws IOException
- {
- if (key != null && key.length != 0)
- {
- if (index == key.length)
- {
- index = 0;
- }
-
- b = b & 0xFF ^ key[index++] & 0xFF;
- }
-
- super.write(b);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public class XOROutputStream extends DelegatingOutputStream +{ + private int[] key; + + private int index; + + public XOROutputStream(OutputStream out, int... key) + { + super(out); + this.key = key; + } + + public int[] getKey() + { + return key; + } + + @Override + public void write(int b) throws IOException + { + if (key != null && key.length != 0) + { + if (index == key.length) + { + index = 0; + } + + b = b & 0xFF ^ key[index++] & 0xFF; + } + + super.write(b); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java index 293b4d6ca4..7edd8239da 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/XORStreamWrapper.java @@ -1,61 +1,61 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @author Eike Stepper
- */
-public class XORStreamWrapper implements IStreamWrapper
-{
- private int[] key;
-
- public XORStreamWrapper(int[] key)
- {
- this.key = key;
- }
-
- public int[] getKey()
- {
- return key;
- }
-
- public XORInputStream wrapInputStream(InputStream in) throws IOException
- {
- if (in instanceof XORInputStream)
- {
- return (XORInputStream)in;
- }
-
- return new XORInputStream(in, key);
- }
-
- public XOROutputStream wrapOutputStream(OutputStream out) throws IOException
- {
- if (out instanceof XOROutputStream)
- {
- return (XOROutputStream)out;
- }
-
- return new XOROutputStream(out, key);
- }
-
- public void finishInputStream(InputStream in) throws IOException
- {
- }
-
- public void finishOutputStream(OutputStream out) throws IOException
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * @author Eike Stepper + */ +public class XORStreamWrapper implements IStreamWrapper +{ + private int[] key; + + public XORStreamWrapper(int[] key) + { + this.key = key; + } + + public int[] getKey() + { + return key; + } + + public XORInputStream wrapInputStream(InputStream in) throws IOException + { + if (in instanceof XORInputStream) + { + return (XORInputStream)in; + } + + return new XORInputStream(in, key); + } + + public XOROutputStream wrapOutputStream(OutputStream out) throws IOException + { + if (out instanceof XOROutputStream) + { + return (XOROutputStream)out; + } + + return new XOROutputStream(out, key); + } + + public void finishInputStream(InputStream in) throws IOException + { + } + + public void finishOutputStream(OutputStream out) throws IOException + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java index 89f22103d2..2e00d02f25 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/ZIPUtil.java @@ -1,408 +1,408 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.io;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Iterator;
-import java.util.List;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-import java.util.zip.ZipOutputStream;
-
-/**
- * @author Eike Stepper
- */
-public final class ZIPUtil
-{
- public static final int DEFALULT_BUFFER_SIZE = 4096;
-
- private static final int ORDER_KEEP = -1;
-
- private static final int ORDER_SWAP = 1;
-
- private ZIPUtil()
- {
- }
-
- public static void zip(ZipEntryHandler handler, File zipFile) throws IORuntimeException
- {
- final byte[] buffer = new byte[DEFALULT_BUFFER_SIZE];
- final EntryContext context = new EntryContext();
-
- FileOutputStream fos = IOUtil.openOutputStream(zipFile);
- ZipOutputStream zos = null;
- InputStream input = null;
- ZipEntry entry = null;
-
- try
- {
- zos = new ZipOutputStream(new BufferedOutputStream(fos, DEFALULT_BUFFER_SIZE));
- for (;;)
- {
- handler.handleEntry(context);
- if (context.isEmpty())
- {
- break;
- }
-
- try
- {
- String name = context.getName().replace(File.separatorChar, '/');
- entry = new ZipEntry(name);
- zos.putNextEntry(entry);
-
- if (!context.isDirectory())
- {
- input = context.getInputStream();
- if (input == null)
- {
- throw new IllegalStateException("Input is null for zip entry " + name); //$NON-NLS-1$
- }
-
- IOUtil.copy(input, zos, buffer);
- }
- }
- finally
- {
- IOUtil.closeSilent(input);
- if (entry != null)
- {
- zos.closeEntry();
- }
-
- context.reset();
- }
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- IOUtil.closeSilent(zos);
- IOUtil.closeSilent(fos);
- }
- }
-
- public static void zip(File sourceFolder, boolean excludeRoot, File zipFile)
- {
- zip(new FileSystemZipHandler(sourceFolder, excludeRoot), zipFile);
- }
-
- public static void unzip(File zipFile, UnzipHandler handler) throws IORuntimeException
- {
- FileInputStream fis = IOUtil.openInputStream(zipFile);
- ZipInputStream zis = null;
-
- try
- {
- zis = new ZipInputStream(new BufferedInputStream(fis, DEFALULT_BUFFER_SIZE));
-
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null)
- {
- if (entry.isDirectory())
- {
- handler.unzipDirectory(entry.getName());
- }
- else
- {
- // TODO Provide delegating InputStream that ignores close()
- handler.unzipFile(entry.getName(), zis);
- }
- }
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- IOUtil.closeSilent(zis);
- IOUtil.closeSilent(fis);
- }
- }
-
- public static void unzip(File zipFile, File targetFolder) throws IORuntimeException
- {
- unzip(zipFile, new FileSystemUnzipHandler(targetFolder, DEFALULT_BUFFER_SIZE));
- }
-
- /**
- * @author Eike Stepper
- */
- public interface ZipEntryHandler
- {
- public void handleEntry(EntryContext context) throws IOException;
- }
-
- /**
- * @author Eike Stepper
- */
- public interface UnzipHandler
- {
- public void unzipDirectory(String name) throws IOException;
-
- public void unzipFile(String name, InputStream zipStream) throws IOException;
- }
-
- /**
- * @author Eike Stepper
- */
- public static final class EntryContext
- {
- private static final String EMPTY = new String();
-
- private String name = EMPTY;
-
- private InputStream inputStream;
-
- private boolean directory;
-
- EntryContext()
- {
- }
-
- void reset()
- {
- name = null;
- inputStream = null;
- }
-
- boolean isEmpty()
- {
- return name == null;
- }
-
- boolean isDirectory()
- {
- return directory;
- }
-
- String getName()
- {
- return name;
- }
-
- InputStream getInputStream()
- {
- return inputStream;
- }
-
- public void setName(String name, boolean directory)
- {
- this.name = name + (directory ? "/" : ""); //$NON-NLS-1$ //$NON-NLS-2$
- this.directory = directory;
- }
-
- public void setInputStream(InputStream inputStream)
- {
- this.inputStream = inputStream;
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static final class FileSystemZipHandler implements ZipEntryHandler
- {
- private int sourceFolderLength;
-
- private transient Iterator<File> files;
-
- public FileSystemZipHandler(File sourceFolder, boolean excludeRoot)
- {
- File root = excludeRoot ? sourceFolder : sourceFolder.getParentFile();
- sourceFolderLength = root.getAbsolutePath().length();
- if (excludeRoot)
- {
- ++sourceFolderLength;
- }
-
- final int baseLength = sourceFolder.getAbsolutePath().length();
- List<File> list = IOUtil.listBreadthFirst(sourceFolder);
- Collections.sort(list, new Comparator<File>()
- {
- public int compare(File f1, File f2)
- {
- String path1 = getPath(f1, baseLength);
- String path2 = getPath(f2, baseLength);
- if (path1.length() == 0)
- {
- return ORDER_KEEP;
- }
-
- if (path2.length() == 0)
- {
- return ORDER_SWAP;
- }
-
- if (f1.isDirectory())
- {
- if (f2.isDirectory())
- {
- // f1=dir, f2=dir
- if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
- {
- return ORDER_KEEP;
- }
-
- if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
- {
- return ORDER_SWAP;
- }
-
- return path1.compareTo(path2);
- }
-
- // f1=dir, f2=file
- if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
- {
- return ORDER_KEEP;
- }
-
- if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
- {
- return ORDER_SWAP;
- }
-
- return ORDER_KEEP;
- }
-
- if (f2.isDirectory())
- {
- // f1=file, f2=dir
- if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$
- {
- return ORDER_SWAP;
- }
-
- if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
- {
- return ORDER_KEEP;
- }
-
- return ORDER_SWAP;
- }
-
- // f1=file, f2=file
- if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
- {
- return ORDER_KEEP;
- }
-
- if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$
- {
- return ORDER_SWAP;
- }
-
- return path1.compareTo(path2);
- }
-
- private String getPath(File file, int baseLength)
- {
- String absolutePath = file.getAbsolutePath();
- String substring = absolutePath.substring(baseLength);
- String replace = substring.replace(File.separatorChar, '/');
- return replace;
- }
- });
-
- files = list.iterator();
- if (excludeRoot)
- {
- files.next();
- }
- }
-
- public void handleEntry(EntryContext context) throws IOException
- {
- if (files.hasNext())
- {
- File file = files.next();
- String name = getName(file);
- if (name.length() != 0)
- {
- context.setName(name, file.isDirectory());
-
- if (file.isFile())
- {
- context.setInputStream(IOUtil.openInputStream(file));
- }
- }
- }
- }
-
- protected String getName(File file)
- {
- return file.getAbsolutePath().substring(sourceFolderLength);
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static final class FileSystemUnzipHandler implements UnzipHandler
- {
- private File targetFolder;
-
- private transient byte[] buffer;
-
- public FileSystemUnzipHandler(File targetFolder, int bufferSize)
- {
- this.targetFolder = targetFolder;
- buffer = new byte[bufferSize];
- }
-
- public File getTargetFolder()
- {
- return targetFolder;
- }
-
- public void unzipDirectory(String name)
- {
- File directory = new File(targetFolder, name);
- if (!directory.exists())
- {
- directory.mkdirs();
- }
- }
-
- public void unzipFile(String name, InputStream zipStream)
- {
- File targetFile = new File(targetFolder, name);
- if (!targetFile.getParentFile().exists())
- {
- targetFile.getParentFile().mkdirs();
- }
-
- FileOutputStream out = IOUtil.openOutputStream(targetFile);
-
- try
- {
- IOUtil.copy(zipStream, out, buffer);
- }
- finally
- {
- IOUtil.closeSilent(out);
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.io; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +/** + * @author Eike Stepper + */ +public final class ZIPUtil +{ + public static final int DEFALULT_BUFFER_SIZE = 4096; + + private static final int ORDER_KEEP = -1; + + private static final int ORDER_SWAP = 1; + + private ZIPUtil() + { + } + + public static void zip(ZipEntryHandler handler, File zipFile) throws IORuntimeException + { + final byte[] buffer = new byte[DEFALULT_BUFFER_SIZE]; + final EntryContext context = new EntryContext(); + + FileOutputStream fos = IOUtil.openOutputStream(zipFile); + ZipOutputStream zos = null; + InputStream input = null; + ZipEntry entry = null; + + try + { + zos = new ZipOutputStream(new BufferedOutputStream(fos, DEFALULT_BUFFER_SIZE)); + for (;;) + { + handler.handleEntry(context); + if (context.isEmpty()) + { + break; + } + + try + { + String name = context.getName().replace(File.separatorChar, '/'); + entry = new ZipEntry(name); + zos.putNextEntry(entry); + + if (!context.isDirectory()) + { + input = context.getInputStream(); + if (input == null) + { + throw new IllegalStateException("Input is null for zip entry " + name); //$NON-NLS-1$ + } + + IOUtil.copy(input, zos, buffer); + } + } + finally + { + IOUtil.closeSilent(input); + if (entry != null) + { + zos.closeEntry(); + } + + context.reset(); + } + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + IOUtil.closeSilent(zos); + IOUtil.closeSilent(fos); + } + } + + public static void zip(File sourceFolder, boolean excludeRoot, File zipFile) + { + zip(new FileSystemZipHandler(sourceFolder, excludeRoot), zipFile); + } + + public static void unzip(File zipFile, UnzipHandler handler) throws IORuntimeException + { + FileInputStream fis = IOUtil.openInputStream(zipFile); + ZipInputStream zis = null; + + try + { + zis = new ZipInputStream(new BufferedInputStream(fis, DEFALULT_BUFFER_SIZE)); + + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) + { + if (entry.isDirectory()) + { + handler.unzipDirectory(entry.getName()); + } + else + { + // TODO Provide delegating InputStream that ignores close() + handler.unzipFile(entry.getName(), zis); + } + } + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + IOUtil.closeSilent(zis); + IOUtil.closeSilent(fis); + } + } + + public static void unzip(File zipFile, File targetFolder) throws IORuntimeException + { + unzip(zipFile, new FileSystemUnzipHandler(targetFolder, DEFALULT_BUFFER_SIZE)); + } + + /** + * @author Eike Stepper + */ + public interface ZipEntryHandler + { + public void handleEntry(EntryContext context) throws IOException; + } + + /** + * @author Eike Stepper + */ + public interface UnzipHandler + { + public void unzipDirectory(String name) throws IOException; + + public void unzipFile(String name, InputStream zipStream) throws IOException; + } + + /** + * @author Eike Stepper + */ + public static final class EntryContext + { + private static final String EMPTY = new String(); + + private String name = EMPTY; + + private InputStream inputStream; + + private boolean directory; + + EntryContext() + { + } + + void reset() + { + name = null; + inputStream = null; + } + + boolean isEmpty() + { + return name == null; + } + + boolean isDirectory() + { + return directory; + } + + String getName() + { + return name; + } + + InputStream getInputStream() + { + return inputStream; + } + + public void setName(String name, boolean directory) + { + this.name = name + (directory ? "/" : ""); //$NON-NLS-1$ //$NON-NLS-2$ + this.directory = directory; + } + + public void setInputStream(InputStream inputStream) + { + this.inputStream = inputStream; + } + } + + /** + * @author Eike Stepper + */ + public static final class FileSystemZipHandler implements ZipEntryHandler + { + private int sourceFolderLength; + + private transient Iterator<File> files; + + public FileSystemZipHandler(File sourceFolder, boolean excludeRoot) + { + File root = excludeRoot ? sourceFolder : sourceFolder.getParentFile(); + sourceFolderLength = root.getAbsolutePath().length(); + if (excludeRoot) + { + ++sourceFolderLength; + } + + final int baseLength = sourceFolder.getAbsolutePath().length(); + List<File> list = IOUtil.listBreadthFirst(sourceFolder); + Collections.sort(list, new Comparator<File>() + { + public int compare(File f1, File f2) + { + String path1 = getPath(f1, baseLength); + String path2 = getPath(f2, baseLength); + if (path1.length() == 0) + { + return ORDER_KEEP; + } + + if (path2.length() == 0) + { + return ORDER_SWAP; + } + + if (f1.isDirectory()) + { + if (f2.isDirectory()) + { + // f1=dir, f2=dir + if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ + { + return ORDER_KEEP; + } + + if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ + { + return ORDER_SWAP; + } + + return path1.compareTo(path2); + } + + // f1=dir, f2=file + if (path1.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ + { + return ORDER_KEEP; + } + + if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ + { + return ORDER_SWAP; + } + + return ORDER_KEEP; + } + + if (f2.isDirectory()) + { + // f1=file, f2=dir + if (path2.equalsIgnoreCase("/META-INF")) //$NON-NLS-1$ + { + return ORDER_SWAP; + } + + if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ + { + return ORDER_KEEP; + } + + return ORDER_SWAP; + } + + // f1=file, f2=file + if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ + { + return ORDER_KEEP; + } + + if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF")) //$NON-NLS-1$ + { + return ORDER_SWAP; + } + + return path1.compareTo(path2); + } + + private String getPath(File file, int baseLength) + { + String absolutePath = file.getAbsolutePath(); + String substring = absolutePath.substring(baseLength); + String replace = substring.replace(File.separatorChar, '/'); + return replace; + } + }); + + files = list.iterator(); + if (excludeRoot) + { + files.next(); + } + } + + public void handleEntry(EntryContext context) throws IOException + { + if (files.hasNext()) + { + File file = files.next(); + String name = getName(file); + if (name.length() != 0) + { + context.setName(name, file.isDirectory()); + + if (file.isFile()) + { + context.setInputStream(IOUtil.openInputStream(file)); + } + } + } + } + + protected String getName(File file) + { + return file.getAbsolutePath().substring(sourceFolderLength); + } + } + + /** + * @author Eike Stepper + */ + public static final class FileSystemUnzipHandler implements UnzipHandler + { + private File targetFolder; + + private transient byte[] buffer; + + public FileSystemUnzipHandler(File targetFolder, int bufferSize) + { + this.targetFolder = targetFolder; + buffer = new byte[bufferSize]; + } + + public File getTargetFolder() + { + return targetFolder; + } + + public void unzipDirectory(String name) + { + File directory = new File(targetFolder, name); + if (!directory.exists()) + { + directory.mkdirs(); + } + } + + public void unzipFile(String name, InputStream zipStream) + { + File targetFile = new File(targetFolder, name); + if (!targetFile.getParentFile().exists()) + { + targetFile.getParentFile().mkdirs(); + } + + FileOutputStream out = IOUtil.openOutputStream(targetFile); + + try + { + IOUtil.copy(zipStream, out, buffer); + } + finally + { + IOUtil.closeSilent(out); + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java index 44fa3a1ed5..2fd34b12a5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/io/package-info.java @@ -1,17 +1,17 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for I/O.
- * @apiviz.exclude .*
- */
-package org.eclipse.net4j.util.io;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for I/O. + * @apiviz.exclude .* + */ +package org.eclipse.net4j.util.io; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java index f43ca8ca27..80b47c85da 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/ILifecycleEvent.java @@ -1,43 +1,43 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.lifecycle;
-
-import org.eclipse.net4j.util.event.IEvent;
-
-/**
- * An {@link IEvent event} fired from an entity with a {@link ILifecycle lifecycle} when its lifecycle {@link Kind
- * state} has changed.
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement Thi import org.eclipse.net4j.util.event.IEvent; import org.eclipse.net4j.util.event.IEvent; import
- * org.eclipse.net4j.util.event.IEvent; s interface is not intended to be implemented by clients.
- * @apiviz.has {@link org.eclipse.net4j.util.lifecycle.ILifecycleEvent.Kind}
- */
-public interface ILifecycleEvent extends IEvent
-{
- /**
- * @since 3.0
- */
- public ILifecycle getSource();
-
- public Kind getKind();
-
- /**
- * Enumerates the possible {@link ILifecycle#getLifecycleState() lifecycle state} changes of an entity.
- *
- * @author Eike Stepper
- */
- public enum Kind
- {
- ABOUT_TO_ACTIVATE, ACTIVATED, ABOUT_TO_DEACTIVATE, DEACTIVATED
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.lifecycle; + +import org.eclipse.net4j.util.event.IEvent; + +/** + * An {@link IEvent event} fired from an entity with a {@link ILifecycle lifecycle} when its lifecycle {@link Kind + * state} has changed. + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement Thi import org.eclipse.net4j.util.event.IEvent; import org.eclipse.net4j.util.event.IEvent; import + * org.eclipse.net4j.util.event.IEvent; s interface is not intended to be implemented by clients. + * @apiviz.has {@link org.eclipse.net4j.util.lifecycle.ILifecycleEvent.Kind} + */ +public interface ILifecycleEvent extends IEvent +{ + /** + * @since 3.0 + */ + public ILifecycle getSource(); + + public Kind getKind(); + + /** + * Enumerates the possible {@link ILifecycle#getLifecycleState() lifecycle state} changes of an entity. + * + * @author Eike Stepper + */ + public enum Kind + { + ABOUT_TO_ACTIVATE, ACTIVATED, ABOUT_TO_DEACTIVATE, DEACTIVATED + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java index ab46f83e61..8d3f783455 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEvent.java @@ -1,47 +1,47 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.lifecycle;
-
-import org.eclipse.net4j.util.event.Event;
-
-/**
- * A default implementation of a lifecycle {@link ILifecycleEvent event}.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class LifecycleEvent extends Event implements ILifecycleEvent
-{
- private static final long serialVersionUID = 1L;
-
- private Kind kind;
-
- public LifecycleEvent(Lifecycle lifecycle, Kind kind)
- {
- super(lifecycle);
- this.kind = kind;
- }
-
- /**
- * @since 3.0
- */
- @Override
- public ILifecycle getSource()
- {
- return (ILifecycle)super.getSource();
- }
-
- public Kind getKind()
- {
- return kind;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.lifecycle; + +import org.eclipse.net4j.util.event.Event; + +/** + * A default implementation of a lifecycle {@link ILifecycleEvent event}. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class LifecycleEvent extends Event implements ILifecycleEvent +{ + private static final long serialVersionUID = 1L; + + private Kind kind; + + public LifecycleEvent(Lifecycle lifecycle, Kind kind) + { + super(lifecycle); + this.kind = kind; + } + + /** + * @since 3.0 + */ + @Override + public ILifecycle getSource() + { + return (ILifecycle)super.getSource(); + } + + public Kind getKind() + { + return kind; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java index ff7765879d..9b02333348 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleEventAdapter.java @@ -1,80 +1,80 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.lifecycle;
-
-import org.eclipse.net4j.util.event.IEvent;
-import org.eclipse.net4j.util.event.IListener;
-
-/**
- * A {@link IListener listener} that dispatches lifecycle {@link ILifecycleEvent events} to methods that can be
- * overridden by extenders.
- *
- * @author Eike Stepper
- * @apiviz.exclude
- */
-public class LifecycleEventAdapter implements IListener
-{
- public LifecycleEventAdapter()
- {
- }
-
- public final void notifyEvent(IEvent event)
- {
- if (event instanceof ILifecycleEvent)
- {
- ILifecycleEvent e = (ILifecycleEvent)event;
- notifyLifecycleEvent(e);
- }
- else
- {
- notifyOtherEvent(event);
- }
- }
-
- protected void notifyLifecycleEvent(ILifecycleEvent event)
- {
- switch (event.getKind())
- {
- case ABOUT_TO_ACTIVATE:
- onAboutToActivate(event.getSource());
- break;
- case ACTIVATED:
- onActivated(event.getSource());
- break;
- case ABOUT_TO_DEACTIVATE:
- onAboutToDeactivate(event.getSource());
- break;
- case DEACTIVATED:
- onDeactivated(event.getSource());
- break;
- }
- }
-
- protected void notifyOtherEvent(IEvent event)
- {
- }
-
- protected void onAboutToActivate(ILifecycle lifecycle)
- {
- }
-
- protected void onActivated(ILifecycle lifecycle)
- {
- }
-
- protected void onAboutToDeactivate(ILifecycle lifecycle)
- {
- }
-
- protected void onDeactivated(ILifecycle lifecycle)
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.lifecycle; + +import org.eclipse.net4j.util.event.IEvent; +import org.eclipse.net4j.util.event.IListener; + +/** + * A {@link IListener listener} that dispatches lifecycle {@link ILifecycleEvent events} to methods that can be + * overridden by extenders. + * + * @author Eike Stepper + * @apiviz.exclude + */ +public class LifecycleEventAdapter implements IListener +{ + public LifecycleEventAdapter() + { + } + + public final void notifyEvent(IEvent event) + { + if (event instanceof ILifecycleEvent) + { + ILifecycleEvent e = (ILifecycleEvent)event; + notifyLifecycleEvent(e); + } + else + { + notifyOtherEvent(event); + } + } + + protected void notifyLifecycleEvent(ILifecycleEvent event) + { + switch (event.getKind()) + { + case ABOUT_TO_ACTIVATE: + onAboutToActivate(event.getSource()); + break; + case ACTIVATED: + onActivated(event.getSource()); + break; + case ABOUT_TO_DEACTIVATE: + onAboutToDeactivate(event.getSource()); + break; + case DEACTIVATED: + onDeactivated(event.getSource()); + break; + } + } + + protected void notifyOtherEvent(IEvent event) + { + } + + protected void onAboutToActivate(ILifecycle lifecycle) + { + } + + protected void onActivated(ILifecycle lifecycle) + { + } + + protected void onAboutToDeactivate(ILifecycle lifecycle) + { + } + + protected void onDeactivated(ILifecycle lifecycle) + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java index bc2a715c3f..ec94815da9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleException.java @@ -1,42 +1,42 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.lifecycle;
-
-/**
- * An unchecked wrapper exception for checked exceptions being thrown from {@link Lifecycle#doActivate()}.
- *
- * @author Eike Stepper
- * @noextend This class is not intended to be subclassed by clients.
- * @apiviz.exclude
- */
-public class LifecycleException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public LifecycleException()
- {
- }
-
- public LifecycleException(String message)
- {
- super(message);
- }
-
- public LifecycleException(Throwable cause)
- {
- super(cause);
- }
-
- public LifecycleException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.lifecycle; + +/** + * An unchecked wrapper exception for checked exceptions being thrown from {@link Lifecycle#doActivate()}. + * + * @author Eike Stepper + * @noextend This class is not intended to be subclassed by clients. + * @apiviz.exclude + */ +public class LifecycleException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public LifecycleException() + { + } + + public LifecycleException(String message) + { + super(message); + } + + public LifecycleException(Throwable cause) + { + super(cause); + } + + public LifecycleException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java index af0cbaa958..45ae687c70 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/LifecycleState.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.lifecycle;
-
-/**
- * Enumerates the possible lifecycle states of an entity with a {@link ILifecycle lifecycle}.
- *
- * @author Eike Stepper
- * @since 3.0
- */
-public enum LifecycleState
-{
- ACTIVATING, ACTIVE, DEACTIVATING, INACTIVE
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.lifecycle; + +/** + * Enumerates the possible lifecycle states of an entity with a {@link ILifecycle lifecycle}. + * + * @author Eike Stepper + * @since 3.0 + */ +public enum LifecycleState +{ + ACTIVATING, ACTIVE, DEACTIVATING, INACTIVE +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java index 069a8d2401..254076a2b1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/lifecycle/package-info.java @@ -1,19 +1,19 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for components with a simple lifecycle.
- * Interfaces that describe the behaviour of objects with respect to their lifecycle.
- * A utility class to interact with such objects and an abstract class that can be
- * used to implement such objects are provided as well.
- */
-package org.eclipse.net4j.util.lifecycle;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for components with a simple lifecycle. + * Interfaces that describe the behaviour of objects with respect to their lifecycle. + * A utility class to interact with such objects and an abstract class that can be + * used to implement such objects are provided as well. + */ +package org.eclipse.net4j.util.lifecycle; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java index be35816666..2c332473f6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/LegacyUtil.java @@ -1,67 +1,67 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om;
-
-import org.eclipse.net4j.internal.util.om.LegacyBundle;
-
-/**
- * Various static helper methods for dealing with {@link OMBundle bundles} if OSGi {@link OMPlatform#isOSGiRunning() is
- * not running}.
- *
- * @author Eike Stepper
- */
-public final class LegacyUtil
-{
- private static final String[] UNINITIALIZED = {};
-
- private static String[] commandLineArgs = UNINITIALIZED;
-
- private LegacyUtil()
- {
- }
-
- /**
- * @since 3.2
- */
- public static String[] getCommandLineArgs() throws IllegalStateException
- {
- if (commandLineArgs == UNINITIALIZED)
- {
- throw new IllegalStateException("Command line argumentshave not been set");
- }
-
- return commandLineArgs;
- }
-
- /**
- * @since 3.2
- */
- public static void setCommandLineArgs(String[] commandLineArgs)
- {
- LegacyUtil.commandLineArgs = commandLineArgs;
- }
-
- public static void startBundles(OMBundle[] bundles) throws Exception
- {
- for (int i = 0; i < bundles.length; i++)
- {
- ((LegacyBundle)bundles[i]).start();
- }
- }
-
- public static void stopBundles(OMBundle[] bundles) throws Exception
- {
- for (int i = bundles.length - 1; i >= 0; i--)
- {
- ((LegacyBundle)bundles[i]).stop();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om; + +import org.eclipse.net4j.internal.util.om.LegacyBundle; + +/** + * Various static helper methods for dealing with {@link OMBundle bundles} if OSGi {@link OMPlatform#isOSGiRunning() is + * not running}. + * + * @author Eike Stepper + */ +public final class LegacyUtil +{ + private static final String[] UNINITIALIZED = {}; + + private static String[] commandLineArgs = UNINITIALIZED; + + private LegacyUtil() + { + } + + /** + * @since 3.2 + */ + public static String[] getCommandLineArgs() throws IllegalStateException + { + if (commandLineArgs == UNINITIALIZED) + { + throw new IllegalStateException("Command line argumentshave not been set"); + } + + return commandLineArgs; + } + + /** + * @since 3.2 + */ + public static void setCommandLineArgs(String[] commandLineArgs) + { + LegacyUtil.commandLineArgs = commandLineArgs; + } + + public static void startBundles(OMBundle[] bundles) throws Exception + { + for (int i = 0; i < bundles.length; i++) + { + ((LegacyBundle)bundles[i]).start(); + } + } + + public static void stopBundles(OMBundle[] bundles) throws Exception + { + for (int i = bundles.length - 1; i >= 0; i--) + { + ((LegacyBundle)bundles[i]).stop(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java index ac42062f21..f19d1e1cd9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMBundle.java @@ -1,177 +1,177 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om;
-
-import org.eclipse.net4j.util.om.log.OMLogger;
-import org.eclipse.net4j.util.om.pref.OMPreferences;
-import org.eclipse.net4j.util.om.trace.OMTracer;
-
-import org.eclipse.osgi.service.debug.DebugOptions;
-
-import org.osgi.framework.Bundle;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Iterator;
-import java.util.Properties;
-import java.util.ResourceBundle;
-
-/**
- * Represents a {@link Bundle bundle}, whether OSGi {@link OMPlatform#isOSGiRunning() is running} or not.
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- * @apiviz.landmark
- * @apiviz.has {@link org.eclipse.net4j.util.om.pref.OMPreferences} oneway - - preferences
- * @apiviz.has {@link org.eclipse.net4j.util.om.log.OMLogger} oneway - - logger
- * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTracer} - - tracers
- * @apiviz.has {@link OMBundle.DebugSupport}
- * @apiviz.has {@link OMBundle.TranslationSupport}
- * @apiviz.has {@link java.util.Properties} oneway - - config
- */
-public interface OMBundle
-{
- public OMPlatform getPlatform();
-
- public String getBundleID();
-
- public URL getBaseURL();
-
- /**
- * @since 3.2
- */
- public Iterator<Class<?>> getClasses();
-
- public OMTracer tracer(String name);
-
- public OMLogger logger();
-
- public OMPreferences preferences();
-
- public File getConfigFile();
-
- public Properties getConfigProperties();
-
- public String getStateLocation();
-
- public InputStream getInputStream(String path) throws IOException;
-
- public DebugSupport getDebugSupport();
-
- public TranslationSupport getTranslationSupport();
-
- /**
- * @deprecated For internal use only.
- */
- @Deprecated
- public void setBundleContext(Object bundleContext);
-
- /**
- * A facility for accessing OSGi {@link DebugOptions debug options}, whether OSGi {@link OMPlatform#isOSGiRunning() is
- * running} or not.
- *
- * @author Eike Stepper
- */
- public interface DebugSupport
- {
- public boolean isDebugging();
-
- public void setDebugging(boolean debugging);
-
- public String getDebugOption(String option);
-
- public void setDebugOption(String option, String value);
-
- public String getDebugOption(String option, String defaultValue);
-
- public boolean getDebugOption(String option, boolean defaultValue);
-
- public void setDebugOption(String option, boolean value);
-
- public int getDebugOption(String option, int defaultValue);
-
- public void setDebugOption(String option, int value);
- }
-
- /**
- * A facility for accessing {@link ResourceBundle resource bundles}.
- *
- * @author Eike Stepper
- */
- public interface TranslationSupport
- {
- /**
- * Indicates whether strings should be translated by default.
- *
- * @return <code>true</code> if strings should be translated by default; <code>false</code> otherwise.
- */
- public boolean shouldTranslate();
-
- /**
- * Sets whether strings should be translated by default.
- *
- * @param shouldTranslate
- * whether strings should be translated by default.
- */
- public void setShouldTranslate(boolean shouldTranslate);
-
- /**
- * Returns the string resource associated with the key.
- *
- * @param key
- * the key of the string resource.
- * @return the string resource associated with the key.
- */
- String getString(String key);
-
- /**
- * Returns the string resource associated with the key.
- *
- * @param key
- * the key of the string resource.
- * @param translate
- * whether the result is to be translated to the current locale.
- * @return the string resource associated with the key.
- */
- String getString(String key, boolean translate);
-
- /**
- * Returns a string resource associated with the key, and performs substitutions.
- *
- * @param key
- * the key of the string.
- * @param args
- * the message substitutions.
- * @return a string resource associated with the key.
- * @see #getString(String)
- * @see java.text.MessageFormat#format(String, Object...)
- */
- String getString(String key, Object... args);
-
- /**
- * Returns a string resource associated with the key, and performs substitutions.
- *
- * @param key
- * the key of the string.
- * @param translate
- * whether the result is to be translated to the current locale.
- * @param args
- * the message substitutions.
- * @return a string resource associated with the key.
- * @see #getString(String)
- * @see java.text.MessageFormat#format(String, Object[])
- */
- String getString(String key, boolean translate, Object... args);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om; + +import org.eclipse.net4j.util.om.log.OMLogger; +import org.eclipse.net4j.util.om.pref.OMPreferences; +import org.eclipse.net4j.util.om.trace.OMTracer; + +import org.eclipse.osgi.service.debug.DebugOptions; + +import org.osgi.framework.Bundle; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Iterator; +import java.util.Properties; +import java.util.ResourceBundle; + +/** + * Represents a {@link Bundle bundle}, whether OSGi {@link OMPlatform#isOSGiRunning() is running} or not. + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + * @apiviz.landmark + * @apiviz.has {@link org.eclipse.net4j.util.om.pref.OMPreferences} oneway - - preferences + * @apiviz.has {@link org.eclipse.net4j.util.om.log.OMLogger} oneway - - logger + * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTracer} - - tracers + * @apiviz.has {@link OMBundle.DebugSupport} + * @apiviz.has {@link OMBundle.TranslationSupport} + * @apiviz.has {@link java.util.Properties} oneway - - config + */ +public interface OMBundle +{ + public OMPlatform getPlatform(); + + public String getBundleID(); + + public URL getBaseURL(); + + /** + * @since 3.2 + */ + public Iterator<Class<?>> getClasses(); + + public OMTracer tracer(String name); + + public OMLogger logger(); + + public OMPreferences preferences(); + + public File getConfigFile(); + + public Properties getConfigProperties(); + + public String getStateLocation(); + + public InputStream getInputStream(String path) throws IOException; + + public DebugSupport getDebugSupport(); + + public TranslationSupport getTranslationSupport(); + + /** + * @deprecated For internal use only. + */ + @Deprecated + public void setBundleContext(Object bundleContext); + + /** + * A facility for accessing OSGi {@link DebugOptions debug options}, whether OSGi {@link OMPlatform#isOSGiRunning() is + * running} or not. + * + * @author Eike Stepper + */ + public interface DebugSupport + { + public boolean isDebugging(); + + public void setDebugging(boolean debugging); + + public String getDebugOption(String option); + + public void setDebugOption(String option, String value); + + public String getDebugOption(String option, String defaultValue); + + public boolean getDebugOption(String option, boolean defaultValue); + + public void setDebugOption(String option, boolean value); + + public int getDebugOption(String option, int defaultValue); + + public void setDebugOption(String option, int value); + } + + /** + * A facility for accessing {@link ResourceBundle resource bundles}. + * + * @author Eike Stepper + */ + public interface TranslationSupport + { + /** + * Indicates whether strings should be translated by default. + * + * @return <code>true</code> if strings should be translated by default; <code>false</code> otherwise. + */ + public boolean shouldTranslate(); + + /** + * Sets whether strings should be translated by default. + * + * @param shouldTranslate + * whether strings should be translated by default. + */ + public void setShouldTranslate(boolean shouldTranslate); + + /** + * Returns the string resource associated with the key. + * + * @param key + * the key of the string resource. + * @return the string resource associated with the key. + */ + String getString(String key); + + /** + * Returns the string resource associated with the key. + * + * @param key + * the key of the string resource. + * @param translate + * whether the result is to be translated to the current locale. + * @return the string resource associated with the key. + */ + String getString(String key, boolean translate); + + /** + * Returns a string resource associated with the key, and performs substitutions. + * + * @param key + * the key of the string. + * @param args + * the message substitutions. + * @return a string resource associated with the key. + * @see #getString(String) + * @see java.text.MessageFormat#format(String, Object...) + */ + String getString(String key, Object... args); + + /** + * Returns a string resource associated with the key, and performs substitutions. + * + * @param key + * the key of the string. + * @param translate + * whether the result is to be translated to the current locale. + * @param args + * the message substitutions. + * @return a string resource associated with the key. + * @see #getString(String) + * @see java.text.MessageFormat#format(String, Object[]) + */ + String getString(String key, boolean translate, Object... args); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java index c353b4ea37..d5b2ab3830 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OMPlatform.java @@ -1,92 +1,92 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractPlatform;
-import org.eclipse.net4j.util.om.log.OMLogFilter;
-import org.eclipse.net4j.util.om.log.OMLogHandler;
-import org.eclipse.net4j.util.om.trace.OMTraceHandler;
-
-import java.io.File;
-import java.util.Properties;
-
-/**
- * Represents the platform that {@link OMBundle bundles} are deployed into, whether OSGi {@link #isOSGiRunning() is
- * running} or not.
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- * @apiviz.landmark
- * @apiviz.has {@link OMBundle} bundles platform
- * @apiviz.owns {@link org.eclipse.net4j.util.om.log.OMLogHandler} - - logHandlers
- * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTraceHandler} - - traceHandlers
- * @apiviz.has {@link java.io.File} oneway - - stateFolder
- */
-public interface OMPlatform
-{
- // @Singleton
- public static final OMPlatform INSTANCE = AbstractPlatform.createPlatform();
-
- public OMBundle bundle(String bundleID, Class<?> accessor);
-
- public boolean isOSGiRunning();
-
- /**
- * @since 2.0
- */
- public boolean isExtensionRegistryAvailable();
-
- public boolean isDebugging();
-
- public void setDebugging(boolean debugging);
-
- /**
- * @since 3.2
- */
- public void addLogFilter(OMLogFilter logFilter);
-
- /**
- * @since 3.2
- */
- public void removeLogFilter(OMLogFilter logFilter);
-
- public void addLogHandler(OMLogHandler logHandler);
-
- public void removeLogHandler(OMLogHandler logHandler);
-
- public void addTraceHandler(OMTraceHandler traceHandler);
-
- public void removeTraceHandler(OMTraceHandler traceHandler);
-
- public File getStateFolder();
-
- public File getConfigFolder();
-
- public File getConfigFile(String name);
-
- public Properties getConfigProperties(String name);
-
- /**
- * @since 3.0
- */
- public String getProperty(String key);
-
- /**
- * @since 3.0
- */
- public String getProperty(String key, String defaultValue);
-
- /**
- * @since 3.2
- */
- public String[] getCommandLineArgs() throws IllegalStateException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om; + +import org.eclipse.net4j.internal.util.bundle.AbstractPlatform; +import org.eclipse.net4j.util.om.log.OMLogFilter; +import org.eclipse.net4j.util.om.log.OMLogHandler; +import org.eclipse.net4j.util.om.trace.OMTraceHandler; + +import java.io.File; +import java.util.Properties; + +/** + * Represents the platform that {@link OMBundle bundles} are deployed into, whether OSGi {@link #isOSGiRunning() is + * running} or not. + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + * @apiviz.landmark + * @apiviz.has {@link OMBundle} bundles platform + * @apiviz.owns {@link org.eclipse.net4j.util.om.log.OMLogHandler} - - logHandlers + * @apiviz.owns {@link org.eclipse.net4j.util.om.trace.OMTraceHandler} - - traceHandlers + * @apiviz.has {@link java.io.File} oneway - - stateFolder + */ +public interface OMPlatform +{ + // @Singleton + public static final OMPlatform INSTANCE = AbstractPlatform.createPlatform(); + + public OMBundle bundle(String bundleID, Class<?> accessor); + + public boolean isOSGiRunning(); + + /** + * @since 2.0 + */ + public boolean isExtensionRegistryAvailable(); + + public boolean isDebugging(); + + public void setDebugging(boolean debugging); + + /** + * @since 3.2 + */ + public void addLogFilter(OMLogFilter logFilter); + + /** + * @since 3.2 + */ + public void removeLogFilter(OMLogFilter logFilter); + + public void addLogHandler(OMLogHandler logHandler); + + public void removeLogHandler(OMLogHandler logHandler); + + public void addTraceHandler(OMTraceHandler traceHandler); + + public void removeTraceHandler(OMTraceHandler traceHandler); + + public File getStateFolder(); + + public File getConfigFolder(); + + public File getConfigFile(String name); + + public Properties getConfigProperties(String name); + + /** + * @since 3.0 + */ + public String getProperty(String key); + + /** + * @since 3.0 + */ + public String getProperty(String key, String defaultValue); + + /** + * @since 3.2 + */ + public String[] getCommandLineArgs() throws IllegalStateException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java index 93f0031cba..074adf7f14 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiActivator.java @@ -1,320 +1,320 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.AbstractBundle;
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.internal.util.om.OSGiBundle;
-import org.eclipse.net4j.util.io.IOUtil;
-
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-
-/**
- * A default implementation of an OSGi {@link BundleActivator bundle activator} for OM {@link OMBundle bundles}.
- *
- * @author Eike Stepper
- */
-public abstract class OSGiActivator implements BundleActivator
-{
- private OMBundle omBundle;
-
- /**
- * @since 2.0
- */
- protected BundleContext bundleContext;
-
- public OSGiActivator(OMBundle omBundle)
- {
- this.omBundle = omBundle;
- }
-
- public final OMBundle getOMBundle()
- {
- return omBundle;
- }
-
- public final void start(BundleContext context) throws Exception
- {
- bundleContext = context;
- OSGiActivator.traceStart(context);
- if (omBundle == null)
- {
- throw new IllegalStateException("bundle == null"); //$NON-NLS-1$
- }
-
- try
- {
- setBundleContext(context);
- ((AbstractBundle)omBundle).start();
- doStart();
- }
- catch (Error error)
- {
- omBundle.logger().error(error);
- throw error;
- }
- catch (Exception ex)
- {
- omBundle.logger().error(ex);
- throw ex;
- }
- }
-
- public final void stop(BundleContext context) throws Exception
- {
- OSGiActivator.traceStop(context);
- if (omBundle == null)
- {
- throw new IllegalStateException("bundle == null"); //$NON-NLS-1$
- }
-
- try
- {
- doStop();
- ((AbstractBundle)omBundle).stop();
- setBundleContext(null);
- }
- catch (Error error)
- {
- omBundle.logger().error(error);
- throw error;
- }
- catch (Exception ex)
- {
- omBundle.logger().error(ex);
- throw ex;
- }
- }
-
- @Override
- public final boolean equals(Object obj)
- {
- return super.equals(obj);
- }
-
- @Override
- public final int hashCode()
- {
- return super.hashCode();
- }
-
- @Override
- public final String toString()
- {
- return super.toString();
- }
-
- @Override
- protected final Object clone() throws CloneNotSupportedException
- {
- return super.clone();
- }
-
- @Override
- protected final void finalize() throws Throwable
- {
- super.finalize();
- }
-
- /**
- * @since 2.0
- */
- protected void doStart() throws Exception
- {
- }
-
- /**
- * @since 2.0
- */
- protected void doStop() throws Exception
- {
- }
-
- @SuppressWarnings("deprecation")
- private void setBundleContext(BundleContext context)
- {
- omBundle.setBundleContext(context);
- }
-
- /**
- * @since 2.0
- */
- public static void traceStart(BundleContext context)
- {
- try
- {
- if (OM.TRACER.isEnabled())
- {
- OM.TRACER.format("Starting bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$
- }
- }
- catch (RuntimeException ignore)
- {
- }
- }
-
- /**
- * @since 2.0
- */
- public static void traceStop(BundleContext context)
- {
- try
- {
- if (OM.TRACER.isEnabled())
- {
- OM.TRACER.format("Stopping bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$
- }
- }
- catch (RuntimeException ignore)
- {
- }
- }
-
- /**
- * Saves and loads {@link OMBundle bundle} state.
- *
- * @author Eike Stepper
- * @since 3.1
- */
- public static abstract class StateHandler
- {
- private OSGiBundle bundle;
-
- public StateHandler(OMBundle bundle)
- {
- this.bundle = (OSGiBundle)bundle;
- }
-
- public final void start() throws Exception
- {
- Object state = null;
- File stateFile = getStateFile();
- if (stateFile.exists())
- {
- FileInputStream fis = null;
-
- try
- {
- fis = new FileInputStream(stateFile);
- ObjectInputStream ois = new ObjectInputStream(fis)
- {
- @Override
- protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException
- {
- String className = desc.getName();
- return bundle.getAccessor().getClassLoader().loadClass(className);
- }
- };
-
- state = ois.readObject();
- IOUtil.close(ois);
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- IOUtil.close(fis);
- fis = null;
- stateFile.delete();
- }
- finally
- {
- IOUtil.close(fis);
- }
- }
-
- startWithState(state);
- }
-
- public final void stop() throws Exception
- {
- FileOutputStream fos = null;
-
- try
- {
- Object state = stopWithState();
-
- File stateFile = getStateFile();
- fos = new FileOutputStream(stateFile);
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(state);
- IOUtil.close(oos);
- }
- finally
- {
- IOUtil.close(fos);
- }
- }
-
- private File getStateFile()
- {
- return new File(bundle.getStateLocation(), "state.bin");
- }
-
- protected abstract void startWithState(Object state) throws Exception;
-
- protected abstract Object stopWithState() throws Exception;
- }
-
- /**
- * An OSGi {@link OSGiActivator activator} that stores {@link StateHandler bundle state} between sessions.
- *
- * @author Eike Stepper
- * @since 3.1
- * @apiviz.has {@link OSGiActivator.StateHandler} oneway - - stateHandler
- */
- public static abstract class WithState extends OSGiActivator
- {
- private StateHandler handler = new StateHandler(getOMBundle())
- {
- @Override
- protected void startWithState(Object state) throws Exception
- {
- doStartWithState(state);
- }
-
- @Override
- protected Object stopWithState() throws Exception
- {
- return doStopWithState();
- }
- };
-
- public WithState(OMBundle bundle)
- {
- super(bundle);
- }
-
- @Override
- protected final void doStart() throws Exception
- {
- handler.start();
- }
-
- @Override
- protected final void doStop() throws Exception
- {
- handler.stop();
- }
-
- protected abstract void doStartWithState(Object state) throws Exception;
-
- protected abstract Object doStopWithState() throws Exception;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om; + +import org.eclipse.net4j.internal.util.bundle.AbstractBundle; +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.internal.util.om.OSGiBundle; +import org.eclipse.net4j.util.io.IOUtil; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.ObjectStreamClass; + +/** + * A default implementation of an OSGi {@link BundleActivator bundle activator} for OM {@link OMBundle bundles}. + * + * @author Eike Stepper + */ +public abstract class OSGiActivator implements BundleActivator +{ + private OMBundle omBundle; + + /** + * @since 2.0 + */ + protected BundleContext bundleContext; + + public OSGiActivator(OMBundle omBundle) + { + this.omBundle = omBundle; + } + + public final OMBundle getOMBundle() + { + return omBundle; + } + + public final void start(BundleContext context) throws Exception + { + bundleContext = context; + OSGiActivator.traceStart(context); + if (omBundle == null) + { + throw new IllegalStateException("bundle == null"); //$NON-NLS-1$ + } + + try + { + setBundleContext(context); + ((AbstractBundle)omBundle).start(); + doStart(); + } + catch (Error error) + { + omBundle.logger().error(error); + throw error; + } + catch (Exception ex) + { + omBundle.logger().error(ex); + throw ex; + } + } + + public final void stop(BundleContext context) throws Exception + { + OSGiActivator.traceStop(context); + if (omBundle == null) + { + throw new IllegalStateException("bundle == null"); //$NON-NLS-1$ + } + + try + { + doStop(); + ((AbstractBundle)omBundle).stop(); + setBundleContext(null); + } + catch (Error error) + { + omBundle.logger().error(error); + throw error; + } + catch (Exception ex) + { + omBundle.logger().error(ex); + throw ex; + } + } + + @Override + public final boolean equals(Object obj) + { + return super.equals(obj); + } + + @Override + public final int hashCode() + { + return super.hashCode(); + } + + @Override + public final String toString() + { + return super.toString(); + } + + @Override + protected final Object clone() throws CloneNotSupportedException + { + return super.clone(); + } + + @Override + protected final void finalize() throws Throwable + { + super.finalize(); + } + + /** + * @since 2.0 + */ + protected void doStart() throws Exception + { + } + + /** + * @since 2.0 + */ + protected void doStop() throws Exception + { + } + + @SuppressWarnings("deprecation") + private void setBundleContext(BundleContext context) + { + omBundle.setBundleContext(context); + } + + /** + * @since 2.0 + */ + public static void traceStart(BundleContext context) + { + try + { + if (OM.TRACER.isEnabled()) + { + OM.TRACER.format("Starting bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$ + } + } + catch (RuntimeException ignore) + { + } + } + + /** + * @since 2.0 + */ + public static void traceStop(BundleContext context) + { + try + { + if (OM.TRACER.isEnabled()) + { + OM.TRACER.format("Stopping bundle {0}", context.getBundle().getSymbolicName()); //$NON-NLS-1$ + } + } + catch (RuntimeException ignore) + { + } + } + + /** + * Saves and loads {@link OMBundle bundle} state. + * + * @author Eike Stepper + * @since 3.1 + */ + public static abstract class StateHandler + { + private OSGiBundle bundle; + + public StateHandler(OMBundle bundle) + { + this.bundle = (OSGiBundle)bundle; + } + + public final void start() throws Exception + { + Object state = null; + File stateFile = getStateFile(); + if (stateFile.exists()) + { + FileInputStream fis = null; + + try + { + fis = new FileInputStream(stateFile); + ObjectInputStream ois = new ObjectInputStream(fis) + { + @Override + protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException + { + String className = desc.getName(); + return bundle.getAccessor().getClassLoader().loadClass(className); + } + }; + + state = ois.readObject(); + IOUtil.close(ois); + } + catch (Exception ex) + { + OM.LOG.error(ex); + IOUtil.close(fis); + fis = null; + stateFile.delete(); + } + finally + { + IOUtil.close(fis); + } + } + + startWithState(state); + } + + public final void stop() throws Exception + { + FileOutputStream fos = null; + + try + { + Object state = stopWithState(); + + File stateFile = getStateFile(); + fos = new FileOutputStream(stateFile); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(state); + IOUtil.close(oos); + } + finally + { + IOUtil.close(fos); + } + } + + private File getStateFile() + { + return new File(bundle.getStateLocation(), "state.bin"); + } + + protected abstract void startWithState(Object state) throws Exception; + + protected abstract Object stopWithState() throws Exception; + } + + /** + * An OSGi {@link OSGiActivator activator} that stores {@link StateHandler bundle state} between sessions. + * + * @author Eike Stepper + * @since 3.1 + * @apiviz.has {@link OSGiActivator.StateHandler} oneway - - stateHandler + */ + public static abstract class WithState extends OSGiActivator + { + private StateHandler handler = new StateHandler(getOMBundle()) + { + @Override + protected void startWithState(Object state) throws Exception + { + doStartWithState(state); + } + + @Override + protected Object stopWithState() throws Exception + { + return doStopWithState(); + } + }; + + public WithState(OMBundle bundle) + { + super(bundle); + } + + @Override + protected final void doStart() throws Exception + { + handler.start(); + } + + @Override + protected final void doStop() throws Exception + { + handler.stop(); + } + + protected abstract void doStartWithState(Object state) throws Exception; + + protected abstract Object doStopWithState() throws Exception; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java index 87f2808ac3..832808a30d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/OSGiApplication.java @@ -1,147 +1,147 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import org.eclipse.equinox.app.IApplication;
-import org.eclipse.equinox.app.IApplicationContext;
-
-import java.util.concurrent.CountDownLatch;
-
-/**
- * A default implementation of an OSGi {@link IApplication application}.
- *
- * @author Eike Stepper
- */
-public class OSGiApplication implements IApplication
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OSGiApplication.class);
-
- private String applicationID;
-
- private IApplicationContext context;
-
- private CountDownLatch stopLatch;
-
- public OSGiApplication(String applicationID)
- {
- this.applicationID = applicationID;
- }
-
- public String getApplicationID()
- {
- return applicationID;
- }
-
- public IApplicationContext getApplicationContext()
- {
- return context;
- }
-
- public boolean isRunning()
- {
- return stopLatch != null;
- }
-
- public final Object start(IApplicationContext context) throws Exception
- {
- this.context = context;
- traceStart(applicationID);
-
- try
- {
- doStart();
- }
- catch (Error error)
- {
- OM.LOG.error(error);
- throw error;
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- throw ex;
- }
-
- if (context != null)
- {
- context.applicationRunning();
- }
-
- stopLatch = new CountDownLatch(1);
- stopLatch.await();
- stopLatch = null;
- return EXIT_OK;
- }
-
- public final void stop()
- {
- traceStop(applicationID);
-
- try
- {
- doStop();
- }
- catch (Error error)
- {
- OM.LOG.error(error);
- throw error;
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- }
-
- context = null;
- if (stopLatch != null)
- {
- stopLatch.countDown();
- }
- }
-
- protected void doStart() throws Exception
- {
- }
-
- protected void doStop() throws Exception
- {
- }
-
- public static void traceStart(String applicationID)
- {
- try
- {
- if (TRACER.isEnabled())
- {
- TRACER.format("Starting application {0}", applicationID); //$NON-NLS-1$
- }
- }
- catch (RuntimeException ignore)
- {
- }
- }
-
- public static void traceStop(String applicationID)
- {
- try
- {
- if (TRACER.isEnabled())
- {
- TRACER.format("Stopping application {0}", applicationID); //$NON-NLS-1$
- }
- }
- catch (RuntimeException ignore)
- {
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import org.eclipse.equinox.app.IApplication; +import org.eclipse.equinox.app.IApplicationContext; + +import java.util.concurrent.CountDownLatch; + +/** + * A default implementation of an OSGi {@link IApplication application}. + * + * @author Eike Stepper + */ +public class OSGiApplication implements IApplication +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_OM, OSGiApplication.class); + + private String applicationID; + + private IApplicationContext context; + + private CountDownLatch stopLatch; + + public OSGiApplication(String applicationID) + { + this.applicationID = applicationID; + } + + public String getApplicationID() + { + return applicationID; + } + + public IApplicationContext getApplicationContext() + { + return context; + } + + public boolean isRunning() + { + return stopLatch != null; + } + + public final Object start(IApplicationContext context) throws Exception + { + this.context = context; + traceStart(applicationID); + + try + { + doStart(); + } + catch (Error error) + { + OM.LOG.error(error); + throw error; + } + catch (Exception ex) + { + OM.LOG.error(ex); + throw ex; + } + + if (context != null) + { + context.applicationRunning(); + } + + stopLatch = new CountDownLatch(1); + stopLatch.await(); + stopLatch = null; + return EXIT_OK; + } + + public final void stop() + { + traceStop(applicationID); + + try + { + doStop(); + } + catch (Error error) + { + OM.LOG.error(error); + throw error; + } + catch (Exception ex) + { + OM.LOG.error(ex); + } + + context = null; + if (stopLatch != null) + { + stopLatch.countDown(); + } + } + + protected void doStart() throws Exception + { + } + + protected void doStop() throws Exception + { + } + + public static void traceStart(String applicationID) + { + try + { + if (TRACER.isEnabled()) + { + TRACER.format("Starting application {0}", applicationID); //$NON-NLS-1$ + } + } + catch (RuntimeException ignore) + { + } + } + + public static void traceStop(String applicationID) + { + try + { + if (TRACER.isEnabled()) + { + TRACER.format("Stopping application {0}", applicationID); //$NON-NLS-1$ + } + } + catch (RuntimeException ignore) + { + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java index e13650fc23..811a5d9601 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/log/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for platform-independent logging.
- */
-package org.eclipse.net4j.util.om.log;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for platform-independent logging. + */ +package org.eclipse.net4j.util.om.log; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java index 3bef60ad82..579e4b54ac 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/AbstractMonitor.java @@ -1,207 +1,207 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class AbstractMonitor implements OMMonitor
-{
- private static final long NOT_BEGUN = -1;
-
- private double totalWork = NOT_BEGUN;
-
- private double work;
-
- public AbstractMonitor()
- {
- }
-
- public boolean hasBegun() throws MonitorCanceledException
- {
- checkCanceled();
- return totalWork != NOT_BEGUN;
- }
-
- public OMMonitor begin(double totalWork) throws MonitorCanceledException
- {
- checkCanceled();
- this.totalWork = totalWork;
- return this;
- }
-
- public OMMonitor begin() throws MonitorCanceledException
- {
- return begin(ONE);
- }
-
- public void worked(double work) throws MonitorCanceledException
- {
- checkBegun();
- this.work += work;
- }
-
- public void worked() throws MonitorCanceledException
- {
- worked(ONE);
- }
-
- public OMMonitor fork(double work)
- {
- checkBegun();
- return createNestedMonitor(work);
- }
-
- public OMMonitor fork()
- {
- return fork(ONE);
- }
-
- public Async forkAsync(double work)
- {
- checkBegun();
- AsyncTimerTask asyncTimerTask = createAsyncTimerTask(work);
- if (asyncTimerTask == null)
- {
- throw new NullPointerException("No async timer task has been created");
- }
-
- long period = getAsyncSchedulePeriod();
- scheduleAtFixedRate(asyncTimerTask, period, period);
- return asyncTimerTask;
- }
-
- public Async forkAsync()
- {
- return forkAsync(ONE);
- }
-
- public void done()
- {
- if (!isCanceled())
- {
- double rest = totalWork - work;
- if (rest > 0)
- {
- worked(rest);
- }
- }
- }
-
- public double getTotalWork()
- {
- return totalWork;
- }
-
- public double getWork()
- {
- return work;
- }
-
- public double getWorkPercent()
- {
- return percent(work, totalWork);
- }
-
- protected OMMonitor createNestedMonitor(double work)
- {
- return new NestedMonitor(this, work);
- }
-
- protected AsyncTimerTask createAsyncTimerTask(double work)
- {
- return new AsyncTimerTask(this, work, DEFAULT_TIME_FACTOR);
- }
-
- protected abstract long getAsyncSchedulePeriod();
-
- protected abstract Timer getTimer();
-
- /**
- * @since 3.0
- */
- protected abstract void scheduleAtFixedRate(TimerTask task, long delay, long period);
-
- private void checkBegun() throws MonitorCanceledException
- {
- if (!hasBegun())
- {
- throw new IllegalStateException("begin() has not been called"); //$NON-NLS-1$
- }
- }
-
- /**
- * @since 3.1
- */
- protected static double percent(double part, double whole)
- {
- return Math.min(part * HUNDRED / whole, HUNDRED);
- }
-
- /**
- * @author Eike Stepper
- */
- public static class AsyncTimerTask extends TimerTask implements Async
- {
- private OMMonitor monitor;
-
- private boolean canceled;
-
- public AsyncTimerTask(AbstractMonitor parent, double parentWork, double timeFactor)
- {
- monitor = parent.fork(parentWork);
- monitor.begin();
- }
-
- @Override
- public void run()
- {
- try
- {
- if (!canceled)
- {
- double work = 1 - monitor.getWork();
- monitor.worked(work / TEN);
- }
- }
- catch (Exception ex)
- {
- OM.LOG.error("AsyncTimerTask failed", ex);
- }
- }
-
- public void stop()
- {
- try
- {
- monitor.done();
- cancel();
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- }
- }
-
- @Override
- public boolean cancel()
- {
- canceled = true;
- return super.cancel();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +import org.eclipse.net4j.internal.util.bundle.OM; + +import java.util.Timer; +import java.util.TimerTask; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class AbstractMonitor implements OMMonitor +{ + private static final long NOT_BEGUN = -1; + + private double totalWork = NOT_BEGUN; + + private double work; + + public AbstractMonitor() + { + } + + public boolean hasBegun() throws MonitorCanceledException + { + checkCanceled(); + return totalWork != NOT_BEGUN; + } + + public OMMonitor begin(double totalWork) throws MonitorCanceledException + { + checkCanceled(); + this.totalWork = totalWork; + return this; + } + + public OMMonitor begin() throws MonitorCanceledException + { + return begin(ONE); + } + + public void worked(double work) throws MonitorCanceledException + { + checkBegun(); + this.work += work; + } + + public void worked() throws MonitorCanceledException + { + worked(ONE); + } + + public OMMonitor fork(double work) + { + checkBegun(); + return createNestedMonitor(work); + } + + public OMMonitor fork() + { + return fork(ONE); + } + + public Async forkAsync(double work) + { + checkBegun(); + AsyncTimerTask asyncTimerTask = createAsyncTimerTask(work); + if (asyncTimerTask == null) + { + throw new NullPointerException("No async timer task has been created"); + } + + long period = getAsyncSchedulePeriod(); + scheduleAtFixedRate(asyncTimerTask, period, period); + return asyncTimerTask; + } + + public Async forkAsync() + { + return forkAsync(ONE); + } + + public void done() + { + if (!isCanceled()) + { + double rest = totalWork - work; + if (rest > 0) + { + worked(rest); + } + } + } + + public double getTotalWork() + { + return totalWork; + } + + public double getWork() + { + return work; + } + + public double getWorkPercent() + { + return percent(work, totalWork); + } + + protected OMMonitor createNestedMonitor(double work) + { + return new NestedMonitor(this, work); + } + + protected AsyncTimerTask createAsyncTimerTask(double work) + { + return new AsyncTimerTask(this, work, DEFAULT_TIME_FACTOR); + } + + protected abstract long getAsyncSchedulePeriod(); + + protected abstract Timer getTimer(); + + /** + * @since 3.0 + */ + protected abstract void scheduleAtFixedRate(TimerTask task, long delay, long period); + + private void checkBegun() throws MonitorCanceledException + { + if (!hasBegun()) + { + throw new IllegalStateException("begin() has not been called"); //$NON-NLS-1$ + } + } + + /** + * @since 3.1 + */ + protected static double percent(double part, double whole) + { + return Math.min(part * HUNDRED / whole, HUNDRED); + } + + /** + * @author Eike Stepper + */ + public static class AsyncTimerTask extends TimerTask implements Async + { + private OMMonitor monitor; + + private boolean canceled; + + public AsyncTimerTask(AbstractMonitor parent, double parentWork, double timeFactor) + { + monitor = parent.fork(parentWork); + monitor.begin(); + } + + @Override + public void run() + { + try + { + if (!canceled) + { + double work = 1 - monitor.getWork(); + monitor.worked(work / TEN); + } + } + catch (Exception ex) + { + OM.LOG.error("AsyncTimerTask failed", ex); + } + } + + public void stop() + { + try + { + monitor.done(); + cancel(); + } + catch (Exception ex) + { + OM.LOG.error(ex); + } + } + + @Override + public boolean cancel() + { + canceled = true; + return super.cancel(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java index a39766e75c..76e55e4490 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/DelegatingMonitor.java @@ -1,105 +1,105 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class DelegatingMonitor implements OMMonitor
-{
- private OMMonitor delegate;
-
- public DelegatingMonitor(OMMonitor delegate)
- {
- this.delegate = delegate;
- }
-
- public OMMonitor getDelegate()
- {
- return delegate;
- }
-
- public boolean hasBegun() throws MonitorCanceledException
- {
- return delegate.hasBegun();
- }
-
- public OMMonitor begin() throws MonitorCanceledException
- {
- return delegate.begin();
- }
-
- public OMMonitor begin(double totalWork) throws MonitorCanceledException
- {
- return delegate.begin(totalWork);
- }
-
- public void checkCanceled() throws MonitorCanceledException
- {
- delegate.checkCanceled();
- }
-
- public void done()
- {
- delegate.done();
- }
-
- public OMMonitor fork()
- {
- return delegate.fork();
- }
-
- public OMMonitor fork(double work)
- {
- return delegate.fork(work);
- }
-
- public Async forkAsync()
- {
- return delegate.forkAsync();
- }
-
- public Async forkAsync(double work)
- {
- return delegate.forkAsync(work);
- }
-
- public double getTotalWork()
- {
- return delegate.getTotalWork();
- }
-
- public double getWork()
- {
- return delegate.getWork();
- }
-
- public double getWorkPercent()
- {
- return delegate.getWorkPercent();
- }
-
- public boolean isCanceled()
- {
- return delegate.isCanceled();
- }
-
- public void worked() throws MonitorCanceledException
- {
- delegate.worked();
- }
-
- public void worked(double work) throws MonitorCanceledException
- {
- delegate.worked(work);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class DelegatingMonitor implements OMMonitor +{ + private OMMonitor delegate; + + public DelegatingMonitor(OMMonitor delegate) + { + this.delegate = delegate; + } + + public OMMonitor getDelegate() + { + return delegate; + } + + public boolean hasBegun() throws MonitorCanceledException + { + return delegate.hasBegun(); + } + + public OMMonitor begin() throws MonitorCanceledException + { + return delegate.begin(); + } + + public OMMonitor begin(double totalWork) throws MonitorCanceledException + { + return delegate.begin(totalWork); + } + + public void checkCanceled() throws MonitorCanceledException + { + delegate.checkCanceled(); + } + + public void done() + { + delegate.done(); + } + + public OMMonitor fork() + { + return delegate.fork(); + } + + public OMMonitor fork(double work) + { + return delegate.fork(work); + } + + public Async forkAsync() + { + return delegate.forkAsync(); + } + + public Async forkAsync(double work) + { + return delegate.forkAsync(work); + } + + public double getTotalWork() + { + return delegate.getTotalWork(); + } + + public double getWork() + { + return delegate.getWork(); + } + + public double getWorkPercent() + { + return delegate.getWorkPercent(); + } + + public boolean isCanceled() + { + return delegate.isCanceled(); + } + + public void worked() throws MonitorCanceledException + { + delegate.worked(); + } + + public void worked(double work) throws MonitorCanceledException + { + delegate.worked(work); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java index 65764b9c4f..dfc6a9ea42 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/EclipseMonitor.java @@ -1,182 +1,182 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-import org.eclipse.net4j.util.StringUtil;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.SubProgressMonitor;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class EclipseMonitor extends Monitor
-{
- private IProgressMonitor progressMonitor;
-
- private String taskName;
-
- public EclipseMonitor(IProgressMonitor progressMonitor, String taskName)
- {
- this.progressMonitor = progressMonitor;
- this.taskName = taskName;
- }
-
- public EclipseMonitor(IProgressMonitor progressMonitor)
- {
- this(progressMonitor, StringUtil.EMPTY);
- }
-
- public String getTaskName()
- {
- return taskName;
- }
-
- @Override
- public boolean isCanceled()
- {
- if (super.isCanceled())
- {
- return true;
- }
-
- return progressMonitor.isCanceled();
- }
-
- @Override
- public OMMonitor begin(double totalWork) throws MonitorCanceledException
- {
- super.begin(totalWork);
- int eclipseWork = totalWork > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)totalWork;
- progressMonitor.beginTask(taskName, eclipseWork);
- return this;
- }
-
- @Override
- public void worked(double work) throws MonitorCanceledException
- {
- super.worked(work);
- progressMonitor.internalWorked(work);
- }
-
- @Override
- public void done()
- {
- super.done();
- progressMonitor.done();
- }
-
- /**
- * A sub progress monitor that synchronizes all methods on the parent monitor instance.
- *
- * @author Eike Stepper
- * @since 3.0
- */
- public static class SynchronizedSubProgressMonitor extends SubProgressMonitor
- {
- public SynchronizedSubProgressMonitor(IProgressMonitor monitor, int ticks)
- {
- super(monitor, ticks);
- }
-
- @Override
- public void beginTask(String name, int totalWork)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.beginTask(name, totalWork);
- }
- }
-
- @Override
- public void clearBlocked()
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.clearBlocked();
- }
- }
-
- @Override
- public void done()
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.done();
- }
- }
-
- @Override
- public void internalWorked(double work)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.internalWorked(work);
- }
- }
-
- @Override
- public boolean isCanceled()
- {
- synchronized (getWrappedProgressMonitor())
- {
- return super.isCanceled();
- }
- }
-
- @Override
- public void setBlocked(IStatus reason)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.setBlocked(reason);
- }
- }
-
- @Override
- public void setCanceled(boolean b)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.setCanceled(b);
- }
- }
-
- @Override
- public void setTaskName(String name)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.setTaskName(name);
- }
- }
-
- @Override
- public void subTask(String name)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.subTask(name);
- }
- }
-
- @Override
- public void worked(int work)
- {
- synchronized (getWrappedProgressMonitor())
- {
- super.worked(work);
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +import org.eclipse.net4j.util.StringUtil; + +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.SubProgressMonitor; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class EclipseMonitor extends Monitor +{ + private IProgressMonitor progressMonitor; + + private String taskName; + + public EclipseMonitor(IProgressMonitor progressMonitor, String taskName) + { + this.progressMonitor = progressMonitor; + this.taskName = taskName; + } + + public EclipseMonitor(IProgressMonitor progressMonitor) + { + this(progressMonitor, StringUtil.EMPTY); + } + + public String getTaskName() + { + return taskName; + } + + @Override + public boolean isCanceled() + { + if (super.isCanceled()) + { + return true; + } + + return progressMonitor.isCanceled(); + } + + @Override + public OMMonitor begin(double totalWork) throws MonitorCanceledException + { + super.begin(totalWork); + int eclipseWork = totalWork > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)totalWork; + progressMonitor.beginTask(taskName, eclipseWork); + return this; + } + + @Override + public void worked(double work) throws MonitorCanceledException + { + super.worked(work); + progressMonitor.internalWorked(work); + } + + @Override + public void done() + { + super.done(); + progressMonitor.done(); + } + + /** + * A sub progress monitor that synchronizes all methods on the parent monitor instance. + * + * @author Eike Stepper + * @since 3.0 + */ + public static class SynchronizedSubProgressMonitor extends SubProgressMonitor + { + public SynchronizedSubProgressMonitor(IProgressMonitor monitor, int ticks) + { + super(monitor, ticks); + } + + @Override + public void beginTask(String name, int totalWork) + { + synchronized (getWrappedProgressMonitor()) + { + super.beginTask(name, totalWork); + } + } + + @Override + public void clearBlocked() + { + synchronized (getWrappedProgressMonitor()) + { + super.clearBlocked(); + } + } + + @Override + public void done() + { + synchronized (getWrappedProgressMonitor()) + { + super.done(); + } + } + + @Override + public void internalWorked(double work) + { + synchronized (getWrappedProgressMonitor()) + { + super.internalWorked(work); + } + } + + @Override + public boolean isCanceled() + { + synchronized (getWrappedProgressMonitor()) + { + return super.isCanceled(); + } + } + + @Override + public void setBlocked(IStatus reason) + { + synchronized (getWrappedProgressMonitor()) + { + super.setBlocked(reason); + } + } + + @Override + public void setCanceled(boolean b) + { + synchronized (getWrappedProgressMonitor()) + { + super.setCanceled(b); + } + } + + @Override + public void setTaskName(String name) + { + synchronized (getWrappedProgressMonitor()) + { + super.setTaskName(name); + } + } + + @Override + public void subTask(String name) + { + synchronized (getWrappedProgressMonitor()) + { + super.subTask(name); + } + } + + @Override + public void worked(int work) + { + synchronized (getWrappedProgressMonitor()) + { + super.worked(work); + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java index 3ce10053a2..9028b849b1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/Monitor.java @@ -1,97 +1,97 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class Monitor extends AbstractMonitor
-{
- public static final long DEFAULT_ASYNC_SCHEDULE_PERIOD = 1000;
-
- private static Timer TIMER;
-
- private boolean canceled;
-
- private RuntimeException cancelException;
-
- public Monitor()
- {
- }
-
- public void cancel()
- {
- cancel(null);
- }
-
- public void cancel(RuntimeException cancelException)
- {
- this.cancelException = cancelException;
- canceled = true;
- }
-
- public boolean isCanceled()
- {
- return canceled;
- }
-
- public void checkCanceled() throws MonitorCanceledException
- {
- if (cancelException != null)
- {
- throw new MonitorCanceledException(cancelException);
- }
-
- if (canceled)
- {
- throw new MonitorCanceledException();
- }
- }
-
- @Override
- protected long getAsyncSchedulePeriod()
- {
- return DEFAULT_ASYNC_SCHEDULE_PERIOD;
- }
-
- @Override
- protected Timer getTimer()
- {
- synchronized (Monitor.class)
- {
- if (TIMER == null)
- {
- TIMER = new Timer("monitor-timer", true); //$NON-NLS-1$
- }
-
- return TIMER;
- }
- }
-
- @Override
- protected void scheduleAtFixedRate(TimerTask task, long delay, long period)
- {
- try
- {
- getTimer().scheduleAtFixedRate(task, delay, period);
- }
- catch (Exception ex)
- {
- OM.LOG.error(ex);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +import org.eclipse.net4j.internal.util.bundle.OM; + +import java.util.Timer; +import java.util.TimerTask; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class Monitor extends AbstractMonitor +{ + public static final long DEFAULT_ASYNC_SCHEDULE_PERIOD = 1000; + + private static Timer TIMER; + + private boolean canceled; + + private RuntimeException cancelException; + + public Monitor() + { + } + + public void cancel() + { + cancel(null); + } + + public void cancel(RuntimeException cancelException) + { + this.cancelException = cancelException; + canceled = true; + } + + public boolean isCanceled() + { + return canceled; + } + + public void checkCanceled() throws MonitorCanceledException + { + if (cancelException != null) + { + throw new MonitorCanceledException(cancelException); + } + + if (canceled) + { + throw new MonitorCanceledException(); + } + } + + @Override + protected long getAsyncSchedulePeriod() + { + return DEFAULT_ASYNC_SCHEDULE_PERIOD; + } + + @Override + protected Timer getTimer() + { + synchronized (Monitor.class) + { + if (TIMER == null) + { + TIMER = new Timer("monitor-timer", true); //$NON-NLS-1$ + } + + return TIMER; + } + } + + @Override + protected void scheduleAtFixedRate(TimerTask task, long delay, long period) + { + try + { + getTimer().scheduleAtFixedRate(task, delay, period); + } + catch (Exception ex) + { + OM.LOG.error(ex); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java index 567cdd1b6e..cba64c5a8e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/MonitorCanceledException.java @@ -1,40 +1,40 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- * @noextend This interface is not intended to be extended by clients.
- */
-public class MonitorCanceledException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public MonitorCanceledException()
- {
- }
-
- public MonitorCanceledException(String message)
- {
- super(message);
- }
-
- public MonitorCanceledException(Throwable cause)
- {
- super(cause);
- }
-
- public MonitorCanceledException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +/** + * @author Eike Stepper + * @since 2.0 + * @noextend This interface is not intended to be extended by clients. + */ +public class MonitorCanceledException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public MonitorCanceledException() + { + } + + public MonitorCanceledException(String message) + { + super(message); + } + + public MonitorCanceledException(Throwable cause) + { + super(cause); + } + + public MonitorCanceledException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java index 1cfa5e4c27..198f212da3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/NestedMonitor.java @@ -1,107 +1,107 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-import java.util.Timer;
-import java.util.TimerTask;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class NestedMonitor extends AbstractMonitor
-{
- private AbstractMonitor parent;
-
- private double parentWork;
-
- private double sentToParent;
-
- private double scale;
-
- private boolean usedUp;
-
- public NestedMonitor(AbstractMonitor parent, double parentWork)
- {
- this.parent = parent;
- this.parentWork = parentWork > ZERO ? parentWork : ZERO;
- }
-
- public AbstractMonitor getParent()
- {
- return parent;
- }
-
- public double getParentWork()
- {
- return parentWork;
- }
-
- public boolean isCanceled()
- {
- return parent.isCanceled();
- }
-
- public void checkCanceled() throws MonitorCanceledException
- {
- parent.checkCanceled();
- }
-
- @Override
- public OMMonitor begin(double totalWork) throws MonitorCanceledException
- {
- super.begin(totalWork);
- scale = totalWork > ZERO ? parentWork / totalWork : ZERO;
- return this;
- }
-
- @Override
- public void worked(double work) throws MonitorCanceledException
- {
- if (!usedUp)
- {
- super.worked(work);
- double realWork = work > ZERO ? scale * work : ZERO;
- parent.worked(realWork);
- sentToParent += realWork;
- if (sentToParent >= parentWork)
- {
- usedUp = true;
- }
- }
- }
-
- @Override
- public void done()
- {
- super.done();
- sentToParent = ZERO;
- usedUp = true;
- }
-
- @Override
- protected long getAsyncSchedulePeriod()
- {
- return parent.getAsyncSchedulePeriod();
- }
-
- @Override
- protected void scheduleAtFixedRate(TimerTask task, long delay, long period)
- {
- parent.scheduleAtFixedRate(task, delay, period);
- }
-
- @Override
- protected Timer getTimer()
- {
- return parent.getTimer();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +import java.util.Timer; +import java.util.TimerTask; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class NestedMonitor extends AbstractMonitor +{ + private AbstractMonitor parent; + + private double parentWork; + + private double sentToParent; + + private double scale; + + private boolean usedUp; + + public NestedMonitor(AbstractMonitor parent, double parentWork) + { + this.parent = parent; + this.parentWork = parentWork > ZERO ? parentWork : ZERO; + } + + public AbstractMonitor getParent() + { + return parent; + } + + public double getParentWork() + { + return parentWork; + } + + public boolean isCanceled() + { + return parent.isCanceled(); + } + + public void checkCanceled() throws MonitorCanceledException + { + parent.checkCanceled(); + } + + @Override + public OMMonitor begin(double totalWork) throws MonitorCanceledException + { + super.begin(totalWork); + scale = totalWork > ZERO ? parentWork / totalWork : ZERO; + return this; + } + + @Override + public void worked(double work) throws MonitorCanceledException + { + if (!usedUp) + { + super.worked(work); + double realWork = work > ZERO ? scale * work : ZERO; + parent.worked(realWork); + sentToParent += realWork; + if (sentToParent >= parentWork) + { + usedUp = true; + } + } + } + + @Override + public void done() + { + super.done(); + sentToParent = ZERO; + usedUp = true; + } + + @Override + protected long getAsyncSchedulePeriod() + { + return parent.getAsyncSchedulePeriod(); + } + + @Override + protected void scheduleAtFixedRate(TimerTask task, long delay, long period) + { + parent.scheduleAtFixedRate(task, delay, period); + } + + @Override + protected Timer getTimer() + { + return parent.getTimer(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java index 5888b5834a..36532cf125 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitor.java @@ -1,106 +1,106 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface OMMonitor extends OMMonitorProgress
-{
- /**
- * @since 2.0
- */
- public static final int THOUSAND = 1000;
-
- /**
- * @since 2.0
- */
- public static final double DEFAULT_TIME_FACTOR = THOUSAND;
-
- /**
- * @since 2.0
- */
- public boolean isCanceled();
-
- /**
- * @since 2.0
- */
- public void checkCanceled() throws MonitorCanceledException;
-
- /**
- * @since 2.0
- */
- public boolean hasBegun() throws MonitorCanceledException;
-
- /**
- * @since 2.0
- */
- public OMMonitor begin(double totalWork) throws MonitorCanceledException;
-
- /**
- * Same as calling <code>begin(ONE)</code>.
- *
- * @since 2.0
- */
- public OMMonitor begin() throws MonitorCanceledException;
-
- /**
- * @since 2.0
- */
- public void worked(double work) throws MonitorCanceledException;
-
- /**
- * Same as calling <code>worked(ONE)</code>.
- *
- * @since 2.0
- */
- public void worked() throws MonitorCanceledException;
-
- /**
- * @since 2.0
- */
- public OMMonitor fork(double work);
-
- /**
- * Same as calling <code>fork(ONE)</code>.
- *
- * @since 2.0
- */
- public OMMonitor fork();
-
- /**
- * @since 2.0
- */
- public Async forkAsync(double work);
-
- /**
- * Same as calling <code>forkAsync(ONE)</code>.
- *
- * @since 2.0
- */
- public Async forkAsync();
-
- /**
- * @since 2.0
- */
- public void done();
-
- /**
- * @author Eike Stepper
- * @since 2.0
- */
- public interface Async
- {
- public void stop();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface OMMonitor extends OMMonitorProgress +{ + /** + * @since 2.0 + */ + public static final int THOUSAND = 1000; + + /** + * @since 2.0 + */ + public static final double DEFAULT_TIME_FACTOR = THOUSAND; + + /** + * @since 2.0 + */ + public boolean isCanceled(); + + /** + * @since 2.0 + */ + public void checkCanceled() throws MonitorCanceledException; + + /** + * @since 2.0 + */ + public boolean hasBegun() throws MonitorCanceledException; + + /** + * @since 2.0 + */ + public OMMonitor begin(double totalWork) throws MonitorCanceledException; + + /** + * Same as calling <code>begin(ONE)</code>. + * + * @since 2.0 + */ + public OMMonitor begin() throws MonitorCanceledException; + + /** + * @since 2.0 + */ + public void worked(double work) throws MonitorCanceledException; + + /** + * Same as calling <code>worked(ONE)</code>. + * + * @since 2.0 + */ + public void worked() throws MonitorCanceledException; + + /** + * @since 2.0 + */ + public OMMonitor fork(double work); + + /** + * Same as calling <code>fork(ONE)</code>. + * + * @since 2.0 + */ + public OMMonitor fork(); + + /** + * @since 2.0 + */ + public Async forkAsync(double work); + + /** + * Same as calling <code>forkAsync(ONE)</code>. + * + * @since 2.0 + */ + public Async forkAsync(); + + /** + * @since 2.0 + */ + public void done(); + + /** + * @author Eike Stepper + * @since 2.0 + */ + public interface Async + { + public void stop(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java index a40ff347de..47f0118e73 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/OMMonitorProgress.java @@ -1,34 +1,34 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-/**
- * @author Eike Stepper
- * @since 3.1
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface OMMonitorProgress
-{
- public static final double ZERO = 0;
-
- public static final double ONE = 1;
-
- public static final double TEN = 10;
-
- public static final double HUNDRED = 100;
-
- public double getTotalWork();
-
- public double getWork();
-
- public double getWorkPercent();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +/** + * @author Eike Stepper + * @since 3.1 + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface OMMonitorProgress +{ + public static final double ZERO = 0; + + public static final double ONE = 1; + + public static final double TEN = 10; + + public static final double HUNDRED = 100; + + public double getTotalWork(); + + public double getWork(); + + public double getWorkPercent(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java index 63d4798f24..c2642ae569 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributable.java @@ -1,54 +1,54 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface ProgressDistributable<CONTEXT>
-{
- public int getLoopCount(CONTEXT context);
-
- public double getLoopWork(CONTEXT context);
-
- public void runLoop(int index, CONTEXT context, OMMonitor monitor) throws Exception;
-
- /**
- * @author Eike Stepper
- */
- public static abstract class Default<CONTEXT> implements ProgressDistributable<CONTEXT>
- {
- private int loopCount = 1;
-
- private double loopWork = OMMonitor.ONE;
-
- public Default()
- {
- }
-
- public Default(int loopCount, double loopWork)
- {
- this.loopCount = loopCount;
- this.loopWork = loopWork;
- }
-
- public int getLoopCount(CONTEXT context)
- {
- return loopCount;
- }
-
- public double getLoopWork(CONTEXT context)
- {
- return loopWork;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface ProgressDistributable<CONTEXT> +{ + public int getLoopCount(CONTEXT context); + + public double getLoopWork(CONTEXT context); + + public void runLoop(int index, CONTEXT context, OMMonitor monitor) throws Exception; + + /** + * @author Eike Stepper + */ + public static abstract class Default<CONTEXT> implements ProgressDistributable<CONTEXT> + { + private int loopCount = 1; + + private double loopWork = OMMonitor.ONE; + + public Default() + { + } + + public Default(int loopCount, double loopWork) + { + this.loopCount = loopCount; + this.loopWork = loopWork; + } + + public int getLoopCount(CONTEXT context) + { + return loopCount; + } + + public double getLoopWork(CONTEXT context) + { + return loopWork; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java index d7f3d1b7d3..8d7bbca213 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/ProgressDistributor.java @@ -1,173 +1,173 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.CheckUtil;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.om.trace.ContextTracer;
-
-import java.util.Arrays;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class ProgressDistributor
-{
- private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_MONITOR, ProgressDistributor.class);
-
- private double[] distribution;
-
- public ProgressDistributor()
- {
- }
-
- public final <CONTEXT> void run(ProgressDistributable<CONTEXT>[] distributables, CONTEXT context, OMMonitor monitor)
- throws RuntimeException, WrappedException
- {
- double[] distributionCopy;
- synchronized (this)
- {
- if (distribution == null)
- {
- distribution = new double[distributables.length];
- Arrays.fill(distribution, OMMonitor.ONE);
- }
- else
- {
- CheckUtil.checkArg(distribution.length == distributables.length, "distributables.length"); //$NON-NLS-1$
- }
-
- distributionCopy = new double[distribution.length];
- System.arraycopy(distribution, 0, distributionCopy, 0, distribution.length);
- }
-
- double total = OMMonitor.ZERO;
- for (int i = 0; i < distributionCopy.length; i++)
- {
- total += distributionCopy[i];
- }
-
- if (TRACER.isEnabled())
- {
- StringBuilder builder = new StringBuilder("Distribution: "); //$NON-NLS-1$
- for (int i = 0; i < distributionCopy.length; i++)
- {
- builder.append(distributionCopy[i] * OMMonitor.HUNDRED / total);
- builder.append("%, "); //$NON-NLS-1$
- }
-
- builder.append("("); //$NON-NLS-1$
- builder.append(this);
- builder.append(")"); //$NON-NLS-1$
- TRACER.trace(builder.toString());
- }
-
- monitor.begin(total);
-
- try
- {
- double[] times = new double[distributables.length];
- for (int i = 0; i < distributables.length; i++)
- {
- ProgressDistributable<CONTEXT> distributable = distributables[i];
- int count = distributable.getLoopCount(context);
- double work = distributable.getLoopWork(context);
-
- OMMonitor distributableMonitor = monitor.fork(distributionCopy[i]);
- distributableMonitor.begin(work * count);
-
- try
- {
- long start = System.currentTimeMillis();
- for (int loop = 0; loop < count; loop++)
- {
- try
- {
- distributable.runLoop(loop, context, distributableMonitor);
- }
- catch (Exception ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
-
- times[i] = (double)(System.currentTimeMillis() - start) / count;
- }
- finally
- {
- distributableMonitor.done();
- }
- }
-
- synchronized (this)
- {
- distribute(distribution, times);
- }
- }
- finally
- {
- monitor.done();
- }
- }
-
- protected abstract void distribute(double[] distribution, double[] times);
-
- public static <CONTEXT> ProgressDistributable<CONTEXT>[] array(ProgressDistributable<CONTEXT>... ops)
- {
- return ops;
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Arithmetic extends ProgressDistributor
- {
- private long count;
-
- private double[] times;
-
- public Arithmetic()
- {
- }
-
- @Override
- protected void distribute(double[] distribution, double[] times)
- {
- ++count;
- for (int i = 0; i < times.length; i++)
- {
- this.times[i] += times[i];
- distribution[i] = this.times[i] / count;
- }
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Geometric extends ProgressDistributor
- {
- public Geometric()
- {
- }
-
- @Override
- protected void distribute(double[] distribution, double[] times)
- {
- for (int i = 0; i < times.length; i++)
- {
- distribution[i] = (distribution[i] + times[i]) / 2;
- }
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.CheckUtil; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.om.trace.ContextTracer; + +import java.util.Arrays; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class ProgressDistributor +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_MONITOR, ProgressDistributor.class); + + private double[] distribution; + + public ProgressDistributor() + { + } + + public final <CONTEXT> void run(ProgressDistributable<CONTEXT>[] distributables, CONTEXT context, OMMonitor monitor) + throws RuntimeException, WrappedException + { + double[] distributionCopy; + synchronized (this) + { + if (distribution == null) + { + distribution = new double[distributables.length]; + Arrays.fill(distribution, OMMonitor.ONE); + } + else + { + CheckUtil.checkArg(distribution.length == distributables.length, "distributables.length"); //$NON-NLS-1$ + } + + distributionCopy = new double[distribution.length]; + System.arraycopy(distribution, 0, distributionCopy, 0, distribution.length); + } + + double total = OMMonitor.ZERO; + for (int i = 0; i < distributionCopy.length; i++) + { + total += distributionCopy[i]; + } + + if (TRACER.isEnabled()) + { + StringBuilder builder = new StringBuilder("Distribution: "); //$NON-NLS-1$ + for (int i = 0; i < distributionCopy.length; i++) + { + builder.append(distributionCopy[i] * OMMonitor.HUNDRED / total); + builder.append("%, "); //$NON-NLS-1$ + } + + builder.append("("); //$NON-NLS-1$ + builder.append(this); + builder.append(")"); //$NON-NLS-1$ + TRACER.trace(builder.toString()); + } + + monitor.begin(total); + + try + { + double[] times = new double[distributables.length]; + for (int i = 0; i < distributables.length; i++) + { + ProgressDistributable<CONTEXT> distributable = distributables[i]; + int count = distributable.getLoopCount(context); + double work = distributable.getLoopWork(context); + + OMMonitor distributableMonitor = monitor.fork(distributionCopy[i]); + distributableMonitor.begin(work * count); + + try + { + long start = System.currentTimeMillis(); + for (int loop = 0; loop < count; loop++) + { + try + { + distributable.runLoop(loop, context, distributableMonitor); + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + times[i] = (double)(System.currentTimeMillis() - start) / count; + } + finally + { + distributableMonitor.done(); + } + } + + synchronized (this) + { + distribute(distribution, times); + } + } + finally + { + monitor.done(); + } + } + + protected abstract void distribute(double[] distribution, double[] times); + + public static <CONTEXT> ProgressDistributable<CONTEXT>[] array(ProgressDistributable<CONTEXT>... ops) + { + return ops; + } + + /** + * @author Eike Stepper + */ + public static class Arithmetic extends ProgressDistributor + { + private long count; + + private double[] times; + + public Arithmetic() + { + } + + @Override + protected void distribute(double[] distribution, double[] times) + { + ++count; + for (int i = 0; i < times.length; i++) + { + this.times[i] += times[i]; + distribution[i] = this.times[i] / count; + } + } + } + + /** + * @author Eike Stepper + */ + public static class Geometric extends ProgressDistributor + { + public Geometric() + { + } + + @Override + protected void distribute(double[] distribution, double[] times) + { + for (int i = 0; i < times.length; i++) + { + distribution[i] = (distribution[i] + times[i]) / 2; + } + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java index 57277c9d09..f32eb8f474 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/TimeoutMonitor.java @@ -1,132 +1,132 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.monitor;
-
-import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException;
-import org.eclipse.net4j.util.concurrent.Timeouter;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class TimeoutMonitor extends Monitor
-{
- private long timeout;
-
- private transient Timeouter timeouter;
-
- public TimeoutMonitor(long timeout)
- {
- this.timeout = timeout;
- }
-
- public long getTimeout()
- {
- return timeout;
- }
-
- public void setTimeout(long timeout)
- {
- this.timeout = timeout;
- if (timeouter != null)
- {
- timeouter.setTimeout(timeout);
- }
- }
-
- public void touch()
- {
- if (timeouter != null)
- {
- timeouter.touch();
- }
- }
-
- @Override
- public OMMonitor begin(double totalWork)
- {
- timeouter = new Timeouter(getTimer(), timeout)
- {
- @Override
- protected void handleTimeout(long untouched)
- {
- TimeoutMonitor.this.handleTimeout(untouched);
- }
- };
-
- touch();
- super.begin(totalWork);
- return this;
- }
-
- @Override
- public void worked(double work)
- {
- touch();
- super.worked(work);
- }
-
- @Override
- public OMMonitor fork(double work)
- {
- touch();
- return super.fork(work);
- }
-
- @Override
- public Async forkAsync(double work)
- {
- touch();
- return super.forkAsync(work);
- }
-
- @Override
- public void done()
- {
- cancelTimeouter();
- super.done();
- }
-
- @Override
- public void cancel(RuntimeException cancelException)
- {
- cancelTimeouter();
- super.cancel(cancelException);
- }
-
- @Override
- public boolean isCanceled()
- {
- touch();
- return super.isCanceled();
- }
-
- @Override
- public void checkCanceled() throws MonitorCanceledException
- {
- touch();
- super.checkCanceled();
- }
-
- protected void handleTimeout(long untouched)
- {
- cancel(new TimeoutRuntimeException("Timeout after " + untouched + " millis"));
- }
-
- private void cancelTimeouter()
- {
- if (timeouter != null)
- {
- timeouter.dispose();
- timeouter = null;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.monitor; + +import org.eclipse.net4j.util.concurrent.TimeoutRuntimeException; +import org.eclipse.net4j.util.concurrent.Timeouter; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class TimeoutMonitor extends Monitor +{ + private long timeout; + + private transient Timeouter timeouter; + + public TimeoutMonitor(long timeout) + { + this.timeout = timeout; + } + + public long getTimeout() + { + return timeout; + } + + public void setTimeout(long timeout) + { + this.timeout = timeout; + if (timeouter != null) + { + timeouter.setTimeout(timeout); + } + } + + public void touch() + { + if (timeouter != null) + { + timeouter.touch(); + } + } + + @Override + public OMMonitor begin(double totalWork) + { + timeouter = new Timeouter(getTimer(), timeout) + { + @Override + protected void handleTimeout(long untouched) + { + TimeoutMonitor.this.handleTimeout(untouched); + } + }; + + touch(); + super.begin(totalWork); + return this; + } + + @Override + public void worked(double work) + { + touch(); + super.worked(work); + } + + @Override + public OMMonitor fork(double work) + { + touch(); + return super.fork(work); + } + + @Override + public Async forkAsync(double work) + { + touch(); + return super.forkAsync(work); + } + + @Override + public void done() + { + cancelTimeouter(); + super.done(); + } + + @Override + public void cancel(RuntimeException cancelException) + { + cancelTimeouter(); + super.cancel(cancelException); + } + + @Override + public boolean isCanceled() + { + touch(); + return super.isCanceled(); + } + + @Override + public void checkCanceled() throws MonitorCanceledException + { + touch(); + super.checkCanceled(); + } + + protected void handleTimeout(long untouched) + { + cancel(new TimeoutRuntimeException("Timeout after " + untouched + " millis")); + } + + private void cancelTimeouter() + { + if (timeouter != null) + { + timeouter.dispose(); + timeouter = null; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java index a6fe5056ad..7115de963c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/monitor/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for platform-independent progress monitoring.
- */
-package org.eclipse.net4j.util.om.monitor;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for platform-independent progress monitoring. + */ +package org.eclipse.net4j.util.om.monitor; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java index 58e3fd298e..d523955e02 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/package-info.java @@ -1,16 +1,16 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for platform-independent <i>operations and maintenance</i> (O&M).
- */
-package org.eclipse.net4j.util.om;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for platform-independent <i>operations and maintenance</i> (O&M). + */ +package org.eclipse.net4j.util.om; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java index 077df5dea0..616955b377 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreference.java @@ -1,43 +1,43 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.pref;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface OMPreference<T>
-{
- public OMPreferences getPreferences();
-
- public String getName();
-
- public Type getType();
-
- public T getDefaultValue();
-
- public T getValue();
-
- public T setValue(T value);
-
- public T unSet();
-
- public boolean isSet();
-
- /**
- * @author Eike Stepper
- */
- public enum Type
- {
- BOOLEAN, INTEGER, LONG, FLOAT, DOUBLE, STRING, ARRAY, BYTES
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.pref; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface OMPreference<T> +{ + public OMPreferences getPreferences(); + + public String getName(); + + public Type getType(); + + public T getDefaultValue(); + + public T getValue(); + + public T setValue(T value); + + public T unSet(); + + public boolean isSet(); + + /** + * @author Eike Stepper + */ + public enum Type + { + BOOLEAN, INTEGER, LONG, FLOAT, DOUBLE, STRING, ARRAY, BYTES + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java index b0aa754c51..82cf41a1e6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferences.java @@ -1,96 +1,96 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.pref;
-
-import org.eclipse.net4j.util.event.INotifier;
-import org.eclipse.net4j.util.om.OMBundle;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface OMPreferences extends INotifier
-{
- public static final boolean DEFAULT_BOOLEAN = false;
-
- public static final int DEFAULT_INTEGER = 0;
-
- public static final long DEFAULT_LONG = 0L;
-
- public static final float DEFAULT_FLOAT = 0.0f;
-
- public static final double DEFAULT_DOUBLE = 0.0d;
-
- public static final String DEFAULT_STRING = ""; //$NON-NLS-1$
-
- public static final String[] DEFAULT_ARRAY = {};
-
- public static final byte[] DEFAULT_BYTES = {};
-
- public OMBundle getBundle();
-
- public boolean isDirty();
-
- public void save();
-
- public OMPreference<Boolean> init(String name, boolean defaultValue);
-
- public OMPreference<Integer> init(String name, int defaultValue);
-
- public OMPreference<Long> init(String name, long defaultValue);
-
- public OMPreference<Float> init(String name, float defaultValue);
-
- public OMPreference<Double> init(String name, double defaultValue);
-
- public OMPreference<String> init(String name, String defaultValue);
-
- public OMPreference<String[]> init(String name, String[] defaultValue);
-
- public OMPreference<byte[]> init(String name, byte[] defaultValue);
-
- public OMPreference<Boolean> initBoolean(String name);
-
- public OMPreference<Integer> initInteger(String name);
-
- public OMPreference<Long> initLong(String name);
-
- public OMPreference<Float> initFloat(String name);
-
- public OMPreference<Double> initDouble(String name);
-
- public OMPreference<String> initString(String name);
-
- public OMPreference<String[]> initArray(String name);
-
- public OMPreference<byte[]> initBytes(String name);
-
- public boolean contains(String name);
-
- public OMPreference<?> get(String name);
-
- public OMPreference<Boolean> getBoolean(String name);
-
- public OMPreference<Integer> getInteger(String name);
-
- public OMPreference<Long> getLong(String name);
-
- public OMPreference<Float> getFloat(String name);
-
- public OMPreference<Double> getDouble(String name);
-
- public OMPreference<String> getString(String name);
-
- public OMPreference<String[]> getArray(String name);
-
- public OMPreference<byte[]> getBytes(String name);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.pref; + +import org.eclipse.net4j.util.event.INotifier; +import org.eclipse.net4j.util.om.OMBundle; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface OMPreferences extends INotifier +{ + public static final boolean DEFAULT_BOOLEAN = false; + + public static final int DEFAULT_INTEGER = 0; + + public static final long DEFAULT_LONG = 0L; + + public static final float DEFAULT_FLOAT = 0.0f; + + public static final double DEFAULT_DOUBLE = 0.0d; + + public static final String DEFAULT_STRING = ""; //$NON-NLS-1$ + + public static final String[] DEFAULT_ARRAY = {}; + + public static final byte[] DEFAULT_BYTES = {}; + + public OMBundle getBundle(); + + public boolean isDirty(); + + public void save(); + + public OMPreference<Boolean> init(String name, boolean defaultValue); + + public OMPreference<Integer> init(String name, int defaultValue); + + public OMPreference<Long> init(String name, long defaultValue); + + public OMPreference<Float> init(String name, float defaultValue); + + public OMPreference<Double> init(String name, double defaultValue); + + public OMPreference<String> init(String name, String defaultValue); + + public OMPreference<String[]> init(String name, String[] defaultValue); + + public OMPreference<byte[]> init(String name, byte[] defaultValue); + + public OMPreference<Boolean> initBoolean(String name); + + public OMPreference<Integer> initInteger(String name); + + public OMPreference<Long> initLong(String name); + + public OMPreference<Float> initFloat(String name); + + public OMPreference<Double> initDouble(String name); + + public OMPreference<String> initString(String name); + + public OMPreference<String[]> initArray(String name); + + public OMPreference<byte[]> initBytes(String name); + + public boolean contains(String name); + + public OMPreference<?> get(String name); + + public OMPreference<Boolean> getBoolean(String name); + + public OMPreference<Integer> getInteger(String name); + + public OMPreference<Long> getLong(String name); + + public OMPreference<Float> getFloat(String name); + + public OMPreference<Double> getDouble(String name); + + public OMPreference<String> getString(String name); + + public OMPreference<String[]> getArray(String name); + + public OMPreference<byte[]> getBytes(String name); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java index d603f914fa..853bed4357 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/OMPreferencesChangeEvent.java @@ -1,35 +1,35 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.om.pref;
-
-import org.eclipse.net4j.util.event.IEvent;
-
-/**
- * An {@link IEvent event} fired from a {@link OMPreferences preferences} object when a {@link OMPreference preference}
- * value has changed.
- *
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface OMPreferencesChangeEvent<T> extends IEvent
-{
- /**
- * @since 3.0
- */
- public OMPreferences getSource();
-
- public OMPreference<T> getPreference();
-
- public T getOldValue();
-
- public T getNewValue();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.om.pref; + +import org.eclipse.net4j.util.event.IEvent; + +/** + * An {@link IEvent event} fired from a {@link OMPreferences preferences} object when a {@link OMPreference preference} + * value has changed. + * + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface OMPreferencesChangeEvent<T> extends IEvent +{ + /** + * @since 3.0 + */ + public OMPreferences getSource(); + + public OMPreference<T> getPreference(); + + public T getOldValue(); + + public T getNewValue(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java index f2acb81b95..d1e6396353 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/pref/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for platform-independent preference management.
- */
-package org.eclipse.net4j.util.om.pref;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for platform-independent preference management. + */ +package org.eclipse.net4j.util.om.pref; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java index af29c7ba01..3c7fb1102e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/om/trace/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for platform-independent tracing.
- */
-package org.eclipse.net4j.util.om.trace;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for platform-independent tracing. + */ +package org.eclipse.net4j.util.om.trace; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java index ea862e8653..2552955731 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/IOptionsEvent.java @@ -1,25 +1,25 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Victor Roldan Betancort - initial API and implementation
- * Eike Stepper - maintenance
- */
-package org.eclipse.net4j.util.options;
-
-import org.eclipse.net4j.util.event.IEvent;
-
-/**
- * A generic {@link IEvent event} fired from an {@link IOptions options} object when an option has changed.
- *
- * @author Victor Roldan Betancort
- * @since 2.0
- */
-public interface IOptionsEvent extends IEvent
-{
- public IOptions getSource();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Victor Roldan Betancort - initial API and implementation + * Eike Stepper - maintenance + */ +package org.eclipse.net4j.util.options; + +import org.eclipse.net4j.util.event.IEvent; + +/** + * A generic {@link IEvent event} fired from an {@link IOptions options} object when an option has changed. + * + * @author Victor Roldan Betancort + * @since 2.0 + */ +public interface IOptionsEvent extends IEvent +{ + public IOptions getSource(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java index 38fe59907b..03cca8ad7a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/options/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for option containers that fire change events.
- */
-package org.eclipse.net4j.util.options;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for option containers that fire change events. + */ +package org.eclipse.net4j.util.options; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java index 729b0aac6c..3f11d71172 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Utility classes.
- */
-package org.eclipse.net4j.util;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Utility classes. + */ +package org.eclipse.net4j.util; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java index 324c70aed1..88358863b4 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/DefaultPropertyTester.java @@ -1,102 +1,102 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.properties;
-
-import org.eclipse.core.expressions.PropertyTester;
-
-import java.util.List;
-
-/**
- * Tests properties of receiver objects against expected values.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public class DefaultPropertyTester<RECEIVER> extends PropertyTester implements IProperties<RECEIVER>
-{
- private final String namespace;
-
- private final IProperties<RECEIVER> properties;
-
- public DefaultPropertyTester(String namespace, IProperties<RECEIVER> properties)
- {
- this.namespace = namespace;
- this.properties = properties;
- }
-
- public final String getNamespace()
- {
- return namespace;
- }
-
- public Class<RECEIVER> getReceiverType()
- {
- return properties.getReceiverType();
- }
-
- public Property<RECEIVER> getProperty(String name)
- {
- return properties.getProperty(name);
- }
-
- public List<Property<RECEIVER>> getProperties()
- {
- return properties.getProperties();
- }
-
- public void add(Property<RECEIVER> property)
- {
- properties.add(property);
- }
-
- public boolean test(Object receiver, String propertyName, Object[] args, Object expectedValue)
- {
- Property<RECEIVER> property = getProperty(propertyName);
- if (property == null)
- {
- return false;
- }
-
- @SuppressWarnings("unchecked")
- RECEIVER typed = (RECEIVER)receiver;
- return property.testValue(typed, args, expectedValue);
- }
-
- public void dumpContributionMarkup()
- {
- System.out.println(" <extension point=\"org.eclipse.core.expressions.propertyTesters\">");
- System.out.println(" <propertyTester");
- System.out.println(" id=\"" + getNamespace() + ".properties\"");
- System.out.println(" type=\"" + getReceiverType().getName() + "\"");
- System.out.println(" namespace=\"" + getNamespace() + "\"");
- System.out.print(" properties=\"");
-
- boolean first = true;
- for (Property<RECEIVER> property : getProperties())
- {
- if (first)
- {
- first = false;
- }
- else
- {
- System.out.print(",");
- }
-
- System.out.print(property.getName());
- }
-
- System.out.println("\"");
- System.out.println(" class=\"" + getClass().getName() + "\"/>");
- System.out.println(" </extension>");
-
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.properties; + +import org.eclipse.core.expressions.PropertyTester; + +import java.util.List; + +/** + * Tests properties of receiver objects against expected values. + * + * @author Eike Stepper + * @since 3.2 + */ +public class DefaultPropertyTester<RECEIVER> extends PropertyTester implements IProperties<RECEIVER> +{ + private final String namespace; + + private final IProperties<RECEIVER> properties; + + public DefaultPropertyTester(String namespace, IProperties<RECEIVER> properties) + { + this.namespace = namespace; + this.properties = properties; + } + + public final String getNamespace() + { + return namespace; + } + + public Class<RECEIVER> getReceiverType() + { + return properties.getReceiverType(); + } + + public Property<RECEIVER> getProperty(String name) + { + return properties.getProperty(name); + } + + public List<Property<RECEIVER>> getProperties() + { + return properties.getProperties(); + } + + public void add(Property<RECEIVER> property) + { + properties.add(property); + } + + public boolean test(Object receiver, String propertyName, Object[] args, Object expectedValue) + { + Property<RECEIVER> property = getProperty(propertyName); + if (property == null) + { + return false; + } + + @SuppressWarnings("unchecked") + RECEIVER typed = (RECEIVER)receiver; + return property.testValue(typed, args, expectedValue); + } + + public void dumpContributionMarkup() + { + System.out.println(" <extension point=\"org.eclipse.core.expressions.propertyTesters\">"); + System.out.println(" <propertyTester"); + System.out.println(" id=\"" + getNamespace() + ".properties\""); + System.out.println(" type=\"" + getReceiverType().getName() + "\""); + System.out.println(" namespace=\"" + getNamespace() + "\""); + System.out.print(" properties=\""); + + boolean first = true; + for (Property<RECEIVER> property : getProperties()) + { + if (first) + { + first = false; + } + else + { + System.out.print(","); + } + + System.out.print(property.getName()); + } + + System.out.println("\""); + System.out.println(" class=\"" + getClass().getName() + "\"/>"); + System.out.println(" </extension>"); + + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java index 15cba8cae6..a5ba97e8f2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IProperties.java @@ -1,26 +1,26 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.properties;
-
-/**
- * Contains a list of {@link Property properties}.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public interface IProperties<RECEIVER> extends IPropertyProvider<RECEIVER>
-{
- public Class<RECEIVER> getReceiverType();
-
- public Property<RECEIVER> getProperty(String name);
-
- public void add(Property<RECEIVER> property);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.properties; + +/** + * Contains a list of {@link Property properties}. + * + * @author Eike Stepper + * @since 3.2 + */ +public interface IProperties<RECEIVER> extends IPropertyProvider<RECEIVER> +{ + public Class<RECEIVER> getReceiverType(); + + public Property<RECEIVER> getProperty(String name); + + public void add(Property<RECEIVER> property); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java index 1edcb25bb1..43373bc1fe 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/IPropertyProvider.java @@ -1,24 +1,24 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.properties;
-
-import java.util.List;
-
-/**
- * Provides a list of {@link Property property descriptors}.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public interface IPropertyProvider<RECEIVER>
-{
- public List<Property<RECEIVER>> getProperties();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.properties; + +import java.util.List; + +/** + * Provides a list of {@link Property property descriptors}. + * + * @author Eike Stepper + * @since 3.2 + */ +public interface IPropertyProvider<RECEIVER> +{ + public List<Property<RECEIVER>> getProperties(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java index 677708ed0f..4ea497fc97 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Properties.java @@ -1,64 +1,64 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.properties;
-
-import org.eclipse.net4j.util.CheckUtil;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Contains a list of {@link Property properties}.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public class Properties<RECEIVER> implements IProperties<RECEIVER>
-{
- private final List<Property<RECEIVER>> properties = new ArrayList<Property<RECEIVER>>();
-
- private final Class<RECEIVER> receiverType;
-
- public Properties(Class<RECEIVER> receiverType)
- {
- this.receiverType = receiverType;
- }
-
- public final Class<RECEIVER> getReceiverType()
- {
- return receiverType;
- }
-
- public final void add(Property<RECEIVER> property)
- {
- CheckUtil.checkArg(property, "property");
- CheckUtil.checkArg(property.getName(), "property.getName()");
- properties.add(property);
- }
-
- public final List<Property<RECEIVER>> getProperties()
- {
- return properties;
- }
-
- public final Property<RECEIVER> getProperty(String name)
- {
- for (Property<RECEIVER> property : properties)
- {
- if (property.getName().equals(name))
- {
- return property;
- }
- }
-
- return null;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.properties; + +import org.eclipse.net4j.util.CheckUtil; + +import java.util.ArrayList; +import java.util.List; + +/** + * Contains a list of {@link Property properties}. + * + * @author Eike Stepper + * @since 3.2 + */ +public class Properties<RECEIVER> implements IProperties<RECEIVER> +{ + private final List<Property<RECEIVER>> properties = new ArrayList<Property<RECEIVER>>(); + + private final Class<RECEIVER> receiverType; + + public Properties(Class<RECEIVER> receiverType) + { + this.receiverType = receiverType; + } + + public final Class<RECEIVER> getReceiverType() + { + return receiverType; + } + + public final void add(Property<RECEIVER> property) + { + CheckUtil.checkArg(property, "property"); + CheckUtil.checkArg(property.getName(), "property.getName()"); + properties.add(property); + } + + public final List<Property<RECEIVER>> getProperties() + { + return properties; + } + + public final Property<RECEIVER> getProperty(String name) + { + for (Property<RECEIVER> property : properties) + { + if (property.getName().equals(name)) + { + return property; + } + } + + return null; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java index 39f667d7f1..a6c36e2f18 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/Property.java @@ -1,137 +1,137 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.properties;
-
-import org.eclipse.net4j.util.ObjectUtil;
-
-/**
- * Describes a property of a receiver object and extracts its value.
- *
- * @author Eike Stepper
- * @since 3.2
- */
-public abstract class Property<RECEIVER>
-{
- private final String name;
-
- private final String label;
-
- private final String description;
-
- private final String category;
-
- public Property(String name, String label, String description, String category)
- {
- this.name = name;
- this.label = label;
- this.description = description;
- this.category = category;
- }
-
- public Property(String name, String label, String description)
- {
- this(name, label, description, null);
- }
-
- public Property(String name)
- {
- this(name, null, null);
- }
-
- public final String getName()
- {
- return name;
- }
-
- public final String getLabel()
- {
- return label;
- }
-
- public final String getDescription()
- {
- return description;
- }
-
- public final String getCategory()
- {
- return category;
- }
-
- public boolean testValue(RECEIVER receiver, Object[] args, Object expectedValue)
- {
- Object value = getValue(receiver);
- return ObjectUtil.equals(value, expectedValue);
- }
-
- public final Object getValue(RECEIVER receiver)
- {
- Object value = eval(receiver);
- if (value == null)
- {
- return value;
- }
-
- Class<? extends Object> c = value.getClass();
- if (c == Boolean.class)
- {
- return value;
- }
-
- if (c == Boolean.class)
- {
- return value;
- }
-
- if (c == Character.class)
- {
- return value;
- }
-
- if (c == Byte.class)
- {
- return value;
- }
-
- if (c == Short.class)
- {
- return value;
- }
-
- if (c == Integer.class)
- {
- return value;
- }
-
- if (c == Long.class)
- {
- return value;
- }
-
- if (c == Float.class)
- {
- return value;
- }
-
- if (c == Double.class)
- {
- return value;
- }
-
- return value.toString();
- }
-
- /**
- * Returns the receiver's value for this property, either a {@link String} or a boxed primitive type. Return values of
- * all other types are converted with {@link #toString()} in {@link #eval(Object)}.
- */
- protected abstract Object eval(RECEIVER receiver);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.properties; + +import org.eclipse.net4j.util.ObjectUtil; + +/** + * Describes a property of a receiver object and extracts its value. + * + * @author Eike Stepper + * @since 3.2 + */ +public abstract class Property<RECEIVER> +{ + private final String name; + + private final String label; + + private final String description; + + private final String category; + + public Property(String name, String label, String description, String category) + { + this.name = name; + this.label = label; + this.description = description; + this.category = category; + } + + public Property(String name, String label, String description) + { + this(name, label, description, null); + } + + public Property(String name) + { + this(name, null, null); + } + + public final String getName() + { + return name; + } + + public final String getLabel() + { + return label; + } + + public final String getDescription() + { + return description; + } + + public final String getCategory() + { + return category; + } + + public boolean testValue(RECEIVER receiver, Object[] args, Object expectedValue) + { + Object value = getValue(receiver); + return ObjectUtil.equals(value, expectedValue); + } + + public final Object getValue(RECEIVER receiver) + { + Object value = eval(receiver); + if (value == null) + { + return value; + } + + Class<? extends Object> c = value.getClass(); + if (c == Boolean.class) + { + return value; + } + + if (c == Boolean.class) + { + return value; + } + + if (c == Character.class) + { + return value; + } + + if (c == Byte.class) + { + return value; + } + + if (c == Short.class) + { + return value; + } + + if (c == Integer.class) + { + return value; + } + + if (c == Long.class) + { + return value; + } + + if (c == Float.class) + { + return value; + } + + if (c == Double.class) + { + return value; + } + + return value.toString(); + } + + /** + * Returns the receiver's value for this property, either a {@link String} or a boxed primitive type. Return values of + * all other types are converted with {@link #toString()} in {@link #eval(Object)}. + */ + protected abstract Object eval(RECEIVER receiver); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java index 15397daa96..fe8c945ebf 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/properties/package-info.java @@ -1,18 +1,18 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework to describe and access properties of POJOs and to support Eclipse
- * {@link org.eclipse.core.expressions.PropertyTester property testers} and
- * <code>IPropertySources</code> in a uniform way.
- */
-package org.eclipse.net4j.util.properties;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework to describe and access properties of POJOs and to support Eclipse + * {@link org.eclipse.core.expressions.PropertyTester property testers} and + * <code>IPropertySources</code> in a uniform way. + */ +package org.eclipse.net4j.util.properties; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java index f5463d3891..7f5e0adbf8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedPhantomReference.java @@ -1,45 +1,45 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-import java.lang.ref.PhantomReference;
-import java.lang.ref.ReferenceQueue;
-import java.text.MessageFormat;
-
-/**
- * @author Eike Stepper
- */
-public class KeyedPhantomReference<K, T> extends PhantomReference<T> implements KeyedReference<K, T>
-{
- private K key;
-
- public KeyedPhantomReference(K key, T ref, ReferenceQueue<T> queue)
- {
- super(ref, queue);
- this.key = key;
- }
-
- public ReferenceType getType()
- {
- return ReferenceType.PHANTOM;
- }
-
- public K getKey()
- {
- return key;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("KeyedPhantomReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +import java.lang.ref.PhantomReference; +import java.lang.ref.ReferenceQueue; +import java.text.MessageFormat; + +/** + * @author Eike Stepper + */ +public class KeyedPhantomReference<K, T> extends PhantomReference<T> implements KeyedReference<K, T> +{ + private K key; + + public KeyedPhantomReference(K key, T ref, ReferenceQueue<T> queue) + { + super(ref, queue); + this.key = key; + } + + public ReferenceType getType() + { + return ReferenceType.PHANTOM; + } + + public K getKey() + { + return key; + } + + @Override + public String toString() + { + return MessageFormat.format("KeyedPhantomReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java index 457150957f..579977cdc2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedReference.java @@ -1,44 +1,44 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-import java.lang.ref.Reference;
-
-/**
- * @see Reference
- * @author Eike Stepper
- */
-public interface KeyedReference<K, T>
-{
- public ReferenceType getType();
-
- public K getKey();
-
- /**
- * @see Reference#get()
- */
- public T get();
-
- /**
- * @see Reference#clear()
- */
- public void clear();
-
- /**
- * @see Reference#isEnqueued()
- */
- public boolean isEnqueued();
-
- /**
- * @see Reference#enqueue()
- */
- public boolean enqueue();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +import java.lang.ref.Reference; + +/** + * @see Reference + * @author Eike Stepper + */ +public interface KeyedReference<K, T> +{ + public ReferenceType getType(); + + public K getKey(); + + /** + * @see Reference#get() + */ + public T get(); + + /** + * @see Reference#clear() + */ + public void clear(); + + /** + * @see Reference#isEnqueued() + */ + public boolean isEnqueued(); + + /** + * @see Reference#enqueue() + */ + public boolean enqueue(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java index c4b5c52798..19561c22dd 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedSoftReference.java @@ -1,51 +1,51 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.text.MessageFormat;
-
-/**
- * @author Eike Stepper
- */
-public class KeyedSoftReference<K, T> extends SoftReference<T> implements KeyedReference<K, T>
-{
- private K key;
-
- public KeyedSoftReference(K key, T ref)
- {
- super(ref);
- this.key = key;
- }
-
- public KeyedSoftReference(K key, T ref, ReferenceQueue<T> queue)
- {
- super(ref, queue);
- this.key = key;
- }
-
- public ReferenceType getType()
- {
- return ReferenceType.SOFT;
- }
-
- public K getKey()
- {
- return key;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("KeyedSoftReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.text.MessageFormat; + +/** + * @author Eike Stepper + */ +public class KeyedSoftReference<K, T> extends SoftReference<T> implements KeyedReference<K, T> +{ + private K key; + + public KeyedSoftReference(K key, T ref) + { + super(ref); + this.key = key; + } + + public KeyedSoftReference(K key, T ref, ReferenceQueue<T> queue) + { + super(ref, queue); + this.key = key; + } + + public ReferenceType getType() + { + return ReferenceType.SOFT; + } + + public K getKey() + { + return key; + } + + @Override + public String toString() + { + return MessageFormat.format("KeyedSoftReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java index 3455f5bace..1d3a6cba0f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedStrongReference.java @@ -1,65 +1,65 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-import java.text.MessageFormat;
-
-/**
- * @author Eike Stepper
- */
-public class KeyedStrongReference<K, T> implements KeyedReference<K, T>
-{
- private K key;
-
- private T ref;
-
- public KeyedStrongReference(K key, T ref)
- {
- this.key = key;
- this.ref = ref;
- }
-
- public ReferenceType getType()
- {
- return ReferenceType.STRONG;
- }
-
- public K getKey()
- {
- return key;
- }
-
- public T get()
- {
- return ref;
- }
-
- public void clear()
- {
- ref = null;
- }
-
- public boolean isEnqueued()
- {
- return false;
- }
-
- public boolean enqueue()
- {
- return false;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("KeyedStrongReference[{0} -> {1}]", key, ref); //$NON-NLS-1$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +import java.text.MessageFormat; + +/** + * @author Eike Stepper + */ +public class KeyedStrongReference<K, T> implements KeyedReference<K, T> +{ + private K key; + + private T ref; + + public KeyedStrongReference(K key, T ref) + { + this.key = key; + this.ref = ref; + } + + public ReferenceType getType() + { + return ReferenceType.STRONG; + } + + public K getKey() + { + return key; + } + + public T get() + { + return ref; + } + + public void clear() + { + ref = null; + } + + public boolean isEnqueued() + { + return false; + } + + public boolean enqueue() + { + return false; + } + + @Override + public String toString() + { + return MessageFormat.format("KeyedStrongReference[{0} -> {1}]", key, ref); //$NON-NLS-1$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java index e8c6e2bdb4..b8f3b48f55 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/KeyedWeakReference.java @@ -1,51 +1,51 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.WeakReference;
-import java.text.MessageFormat;
-
-/**
- * @author Eike Stepper
- */
-public class KeyedWeakReference<K, T> extends WeakReference<T> implements KeyedReference<K, T>
-{
- private K key;
-
- public KeyedWeakReference(K key, T ref)
- {
- super(ref);
- this.key = key;
- }
-
- public KeyedWeakReference(K key, T ref, ReferenceQueue<T> queue)
- {
- super(ref, queue);
- this.key = key;
- }
-
- public ReferenceType getType()
- {
- return ReferenceType.WEAK;
- }
-
- public K getKey()
- {
- return key;
- }
-
- @Override
- public String toString()
- {
- return MessageFormat.format("KeyedWeakReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.text.MessageFormat; + +/** + * @author Eike Stepper + */ +public class KeyedWeakReference<K, T> extends WeakReference<T> implements KeyedReference<K, T> +{ + private K key; + + public KeyedWeakReference(K key, T ref) + { + super(ref); + this.key = key; + } + + public KeyedWeakReference(K key, T ref, ReferenceQueue<T> queue) + { + super(ref, queue); + this.key = key; + } + + public ReferenceType getType() + { + return ReferenceType.WEAK; + } + + public K getKey() + { + return key; + } + + @Override + public String toString() + { + return MessageFormat.format("KeyedWeakReference[{0} -> {1}]", key, isEnqueued() ? "ENQUEUED" : get()); //$NON-NLS-1$ //$NON-NLS-2$ + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java index 9cc25c7397..6eab384d3a 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceQueueWorker.java @@ -1,101 +1,101 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- * Victor Roldan Betancort - Bug 311840 - OutOfMemory with fast population of revision cache
- */
-package org.eclipse.net4j.util.ref;
-
-import org.eclipse.net4j.util.concurrent.Worker;
-
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class ReferenceQueueWorker<T> extends Worker
-{
- /**
- * @since 3.0
- */
- public static final int DEFAULT_POLL_MILLIS = 1000 * 60; // One minute
-
- /**
- * @since 3.0
- */
- public static final int ALL_WORK_PER_POLL = -1;
-
- /**
- * @since 3.0
- */
- public static final int DEFAULT_MAX_WORK_PER_POLL = ALL_WORK_PER_POLL;
-
- private ReferenceQueue<T> queue = new ReferenceQueue<T>();
-
- private long pollMillis;
-
- private int maxWorkPerPoll;
-
- public ReferenceQueueWorker()
- {
- setPollMillis(DEFAULT_POLL_MILLIS);
- setMaxWorkPerPoll(DEFAULT_MAX_WORK_PER_POLL);
- }
-
- public long getPollMillis()
- {
- return pollMillis;
- }
-
- public void setPollMillis(long pollMillis)
- {
- this.pollMillis = pollMillis;
- }
-
- public int getMaxWorkPerPoll()
- {
- return maxWorkPerPoll;
- }
-
- public void setMaxWorkPerPoll(int maxWorkPerPoll)
- {
- this.maxWorkPerPoll = maxWorkPerPoll;
- }
-
- protected ReferenceQueue<T> getQueue()
- {
- return queue;
- }
-
- @Override
- protected final void work(WorkContext context) throws Exception
- {
- int count = maxWorkPerPoll;
- if (count == ALL_WORK_PER_POLL)
- {
- count = Integer.MAX_VALUE;
- }
-
- for (int i = 0; i < count; i++)
- {
- Reference<? extends T> reference = queue.poll();
- if (reference == null)
- {
- break;
- }
-
- work(reference);
- }
-
- context.nextWork(pollMillis);
- }
-
- protected abstract void work(Reference<? extends T> reference);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + * Victor Roldan Betancort - Bug 311840 - OutOfMemory with fast population of revision cache + */ +package org.eclipse.net4j.util.ref; + +import org.eclipse.net4j.util.concurrent.Worker; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class ReferenceQueueWorker<T> extends Worker +{ + /** + * @since 3.0 + */ + public static final int DEFAULT_POLL_MILLIS = 1000 * 60; // One minute + + /** + * @since 3.0 + */ + public static final int ALL_WORK_PER_POLL = -1; + + /** + * @since 3.0 + */ + public static final int DEFAULT_MAX_WORK_PER_POLL = ALL_WORK_PER_POLL; + + private ReferenceQueue<T> queue = new ReferenceQueue<T>(); + + private long pollMillis; + + private int maxWorkPerPoll; + + public ReferenceQueueWorker() + { + setPollMillis(DEFAULT_POLL_MILLIS); + setMaxWorkPerPoll(DEFAULT_MAX_WORK_PER_POLL); + } + + public long getPollMillis() + { + return pollMillis; + } + + public void setPollMillis(long pollMillis) + { + this.pollMillis = pollMillis; + } + + public int getMaxWorkPerPoll() + { + return maxWorkPerPoll; + } + + public void setMaxWorkPerPoll(int maxWorkPerPoll) + { + this.maxWorkPerPoll = maxWorkPerPoll; + } + + protected ReferenceQueue<T> getQueue() + { + return queue; + } + + @Override + protected final void work(WorkContext context) throws Exception + { + int count = maxWorkPerPoll; + if (count == ALL_WORK_PER_POLL) + { + count = Integer.MAX_VALUE; + } + + for (int i = 0; i < count; i++) + { + Reference<? extends T> reference = queue.poll(); + if (reference == null) + { + break; + } + + work(reference); + } + + context.nextWork(pollMillis); + } + + protected abstract void work(Reference<? extends T> reference); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java index cc364bbc33..2680d49950 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceType.java @@ -1,20 +1,20 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- */
-public enum ReferenceType
-{
- STRONG, SOFT, WEAK, PHANTOM;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + */ +public enum ReferenceType +{ + STRONG, SOFT, WEAK, PHANTOM; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java index c731a5e9f8..75bff38f4b 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/ReferenceValueMap.java @@ -1,503 +1,503 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.ref;
-
-import org.eclipse.net4j.util.collection.MapEntry;
-
-import java.lang.ref.ReferenceQueue;
-import java.util.AbstractMap;
-import java.util.AbstractSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * A {@link ConcurrentMap} implementation that uses {@link KeyedReference} instances ({@link KeyedStrongReference},
- * {@link KeyedSoftReference}, {@link KeyedWeakReference} or {@link KeyedPhantomReference}) as its values.
- * <p>
- * A <code>ReferenceValueMap</code> can be used to cache mappings until the <em>value</em> of the mapping is no longer
- * reachable from outside of the map
- * <p>
- * <b>Note:</b> This map is not synchronized. If it is to be used by multiple threads concurrently the user is
- * responsible for applying proper external synchronization!
- *
- * @author Eike Stepper
- */
-public abstract class ReferenceValueMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>
-{
- private ConcurrentMap<K, KeyedReference<K, V>> map;
-
- private ReferenceQueue<V> queue;
-
- private EntrySet entrySet;
-
- public ReferenceValueMap()
- {
- this(new ConcurrentHashMap<K, KeyedReference<K, V>>());
- }
-
- public ReferenceValueMap(ConcurrentMap<K, KeyedReference<K, V>> map)
- {
- if (!map.isEmpty())
- {
- throw new IllegalArgumentException("!map.isEmpty()"); //$NON-NLS-1$
- }
-
- this.map = map;
- queue = createQueue();
- }
-
- @Override
- public int size()
- {
- purgeQueue();
- return map.size();
- }
-
- @Override
- public boolean isEmpty()
- {
- purgeQueue();
- return map.isEmpty();
- }
-
- @Override
- public boolean containsKey(Object key)
- {
- KeyedReference<K, V> ref = map.get(key);
- if (ref != null)
- {
- if (ref.get() == null)
- {
- // ref.enqueue();
- return false;
- }
-
- return true;
- }
-
- return false;
- }
-
- @Override
- public boolean containsValue(Object value)
- {
- if (value == null)
- {
- throw new IllegalArgumentException("value == null"); //$NON-NLS-1$
- }
-
- for (KeyedReference<K, V> ref : map.values())
- {
- V v = ref.get();
- if (v == null)
- {
- // ref.enqueue();
- return false;
- }
-
- if (value.equals(v))
- {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public V get(Object key)
- {
- KeyedReference<K, V> ref = map.get(key);
- return dereference(ref);
- }
-
- @Override
- public V put(K key, V value)
- {
- try
- {
- KeyedReference<K, V> ref = createReference(key, value, queue);
- KeyedReference<K, V> oldRef = map.put(key, ref);
- return dereference(oldRef);
- }
- finally
- {
- purgeQueue();
- }
- }
-
- public V putIfAbsent(K key, V value)
- {
- try
- {
- KeyedReference<K, V> ref = createReference(key, value, queue);
- KeyedReference<K, V> oldRef = map.putIfAbsent(key, ref);
- return dereference(oldRef);
- }
- finally
- {
- purgeQueue();
- }
- }
-
- public V replace(K key, V value)
- {
- try
- {
- KeyedReference<K, V> ref = createReference(key, value, queue);
- KeyedReference<K, V> oldRef = map.replace(key, ref);
- return dereference(oldRef);
- }
- finally
- {
- purgeQueue();
- }
- }
-
- public boolean replace(K key, V oldValue, V newValue)
- {
- try
- {
- // TODO Consider a dummy KeyedReference class for oldRef
- KeyedReference<K, V> oldRef = createReference(key, oldValue, queue);
- KeyedReference<K, V> newRef = createReference(key, newValue, queue);
- return map.replace(key, oldRef, newRef);
- }
- finally
- {
- purgeQueue();
- }
- }
-
- @Override
- public V remove(Object key)
- {
- KeyedReference<K, V> ref = map.remove(key);
- return dereference(ref);
- }
-
- public boolean remove(Object key, Object value)
- {
- // TODO Consider a dummy KeyedReference class for value
- return map.remove(key, value);
- }
-
- @Override
- public void clear()
- {
- purgeQueue();
- map.clear();
- }
-
- @Override
- public Set<Map.Entry<K, V>> entrySet()
- {
- if (entrySet == null)
- {
- purgeQueue();
- entrySet = new EntrySet();
- }
-
- return entrySet;
- }
-
- protected ReferenceQueue<V> createQueue()
- {
- return new ReferenceQueue<V>();
- }
-
- @SuppressWarnings("unchecked")
- protected void purgeQueue()
- {
- if (queue != null)
- {
- KeyedReference<K, V> ref;
- while ((ref = (KeyedReference<K, V>)queue.poll()) != null)
- {
- // Slightly faster than map.get() + map.remove()
- K key = ref.getKey();
- map.remove(key, ref);
- purged(key);
- }
- }
- }
-
- protected void purged(K key)
- {
- }
-
- protected V dereference(KeyedReference<K, V> ref)
- {
- if (ref == null)
- {
- return null;
- }
-
- return ref.get();
- }
-
- protected abstract KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue);
-
- /**
- * @author Eike Stepper
- */
- public static class Strong<K, V> extends ReferenceValueMap<K, V>
- {
- public Strong()
- {
- }
-
- public Strong(ConcurrentMap<K, KeyedReference<K, V>> map)
- {
- super(map);
- }
-
- @Override
- protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue)
- {
- return new KeyedStrongReference<K, V>(key, value);
- }
-
- @Override
- protected ReferenceQueue<V> createQueue()
- {
- return null;
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Soft<K, V> extends ReferenceValueMap<K, V>
- {
- public Soft()
- {
- }
-
- public Soft(ConcurrentMap<K, KeyedReference<K, V>> map)
- {
- super(map);
- }
-
- @Override
- protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue)
- {
- return new KeyedSoftReference<K, V>(key, value, queue);
- }
- }
-
- /**
- * @author Eike Stepper
- */
- public static class Weak<K, V> extends ReferenceValueMap<K, V>
- {
- public Weak()
- {
- }
-
- public Weak(ConcurrentMap<K, KeyedReference<K, V>> map)
- {
- super(map);
- }
-
- @Override
- protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue)
- {
- return new KeyedWeakReference<K, V>(key, value, queue);
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private class EntrySet extends AbstractSet<Map.Entry<K, V>>
- {
- public EntrySet()
- {
- }
-
- @Override
- public int size()
- {
- return map.size();
- }
-
- @Override
- public boolean isEmpty()
- {
- return map.isEmpty();
- }
-
- @Override
- public boolean contains(Object object)
- {
- if (object == null)
- {
- throw new IllegalArgumentException("object == null"); //$NON-NLS-1$
- }
-
- if (object instanceof Map.Entry<?, ?>)
- {
- Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object;
- Object key = entry.getKey();
- Object value = entry.getValue();
- return key != null && value != null && value.equals(get(key));
- }
-
- return false;
- }
-
- @Override
- public Iterator<Map.Entry<K, V>> iterator()
- {
- return new EntrySetIterator();
- }
-
- @Override
- public Object[] toArray()
- {
- Object[] a = new Object[size()];
- int i = 0;
- for (Map.Entry<K, V> entry : this)
- {
- a[i++] = entry;
- }
-
- return a;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T[] toArray(T[] a)
- {
- if (a == null)
- {
- throw new IllegalArgumentException("array == null"); //$NON-NLS-1$
- }
-
- int size = size();
- if (a.length < size)
- {
- a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
- }
-
- int i = 0;
- for (Map.Entry<K, V> entry : this)
- {
- a[i++] = (T)entry;
- }
-
- if (a.length > size)
- {
- a[size] = null;
- }
-
- return a;
- }
-
- @Override
- public boolean remove(Object object)
- {
- if (object == null)
- {
- throw new IllegalArgumentException("object == null"); //$NON-NLS-1$
- }
-
- if (object instanceof Map.Entry<?, ?>)
- {
- Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object;
- return map.remove(entry.getKey(), entry.getValue());
- }
-
- return false;
- }
-
- @Override
- public void clear()
- {
- map.clear();
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private class EntrySetIterator implements Iterator<Map.Entry<K, V>>
- {
- private Iterator<Entry<K, KeyedReference<K, V>>> it = map.entrySet().iterator();
-
- private MapEntry<K, V> nextEntry;
-
- private K lastKey;
-
- public EntrySetIterator()
- {
- }
-
- public boolean hasNext()
- {
- if (nextEntry != null)
- {
- return true;
- }
-
- while (it.hasNext())
- {
- Entry<K, KeyedReference<K, V>> entry = it.next();
- lastKey = entry.getKey();
- V value = dereference(entry.getValue());
- if (value != null)
- {
- nextEntry = new MapEntry<K, V>(lastKey, value);
- return true;
- }
- }
-
- return false;
- }
-
- public Entry<K, V> next()
- {
- if (nextEntry == null)
- {
- if (!hasNext())
- {
- throw new NoSuchElementException();
- }
- }
-
- try
- {
- return nextEntry;
- }
- finally
- {
- nextEntry = null;
- }
- }
-
- public void remove()
- {
- if (lastKey == null)
- {
- throw new IllegalStateException("lastKey == null"); //$NON-NLS-1$
- }
-
- map.remove(lastKey);
- lastKey = null;
- nextEntry = null;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.ref; + +import org.eclipse.net4j.util.collection.MapEntry; + +import java.lang.ref.ReferenceQueue; +import java.util.AbstractMap; +import java.util.AbstractSet; +import java.util.Iterator; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * A {@link ConcurrentMap} implementation that uses {@link KeyedReference} instances ({@link KeyedStrongReference}, + * {@link KeyedSoftReference}, {@link KeyedWeakReference} or {@link KeyedPhantomReference}) as its values. + * <p> + * A <code>ReferenceValueMap</code> can be used to cache mappings until the <em>value</em> of the mapping is no longer + * reachable from outside of the map + * <p> + * <b>Note:</b> This map is not synchronized. If it is to be used by multiple threads concurrently the user is + * responsible for applying proper external synchronization! + * + * @author Eike Stepper + */ +public abstract class ReferenceValueMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> +{ + private ConcurrentMap<K, KeyedReference<K, V>> map; + + private ReferenceQueue<V> queue; + + private EntrySet entrySet; + + public ReferenceValueMap() + { + this(new ConcurrentHashMap<K, KeyedReference<K, V>>()); + } + + public ReferenceValueMap(ConcurrentMap<K, KeyedReference<K, V>> map) + { + if (!map.isEmpty()) + { + throw new IllegalArgumentException("!map.isEmpty()"); //$NON-NLS-1$ + } + + this.map = map; + queue = createQueue(); + } + + @Override + public int size() + { + purgeQueue(); + return map.size(); + } + + @Override + public boolean isEmpty() + { + purgeQueue(); + return map.isEmpty(); + } + + @Override + public boolean containsKey(Object key) + { + KeyedReference<K, V> ref = map.get(key); + if (ref != null) + { + if (ref.get() == null) + { + // ref.enqueue(); + return false; + } + + return true; + } + + return false; + } + + @Override + public boolean containsValue(Object value) + { + if (value == null) + { + throw new IllegalArgumentException("value == null"); //$NON-NLS-1$ + } + + for (KeyedReference<K, V> ref : map.values()) + { + V v = ref.get(); + if (v == null) + { + // ref.enqueue(); + return false; + } + + if (value.equals(v)) + { + return true; + } + } + + return false; + } + + @Override + public V get(Object key) + { + KeyedReference<K, V> ref = map.get(key); + return dereference(ref); + } + + @Override + public V put(K key, V value) + { + try + { + KeyedReference<K, V> ref = createReference(key, value, queue); + KeyedReference<K, V> oldRef = map.put(key, ref); + return dereference(oldRef); + } + finally + { + purgeQueue(); + } + } + + public V putIfAbsent(K key, V value) + { + try + { + KeyedReference<K, V> ref = createReference(key, value, queue); + KeyedReference<K, V> oldRef = map.putIfAbsent(key, ref); + return dereference(oldRef); + } + finally + { + purgeQueue(); + } + } + + public V replace(K key, V value) + { + try + { + KeyedReference<K, V> ref = createReference(key, value, queue); + KeyedReference<K, V> oldRef = map.replace(key, ref); + return dereference(oldRef); + } + finally + { + purgeQueue(); + } + } + + public boolean replace(K key, V oldValue, V newValue) + { + try + { + // TODO Consider a dummy KeyedReference class for oldRef + KeyedReference<K, V> oldRef = createReference(key, oldValue, queue); + KeyedReference<K, V> newRef = createReference(key, newValue, queue); + return map.replace(key, oldRef, newRef); + } + finally + { + purgeQueue(); + } + } + + @Override + public V remove(Object key) + { + KeyedReference<K, V> ref = map.remove(key); + return dereference(ref); + } + + public boolean remove(Object key, Object value) + { + // TODO Consider a dummy KeyedReference class for value + return map.remove(key, value); + } + + @Override + public void clear() + { + purgeQueue(); + map.clear(); + } + + @Override + public Set<Map.Entry<K, V>> entrySet() + { + if (entrySet == null) + { + purgeQueue(); + entrySet = new EntrySet(); + } + + return entrySet; + } + + protected ReferenceQueue<V> createQueue() + { + return new ReferenceQueue<V>(); + } + + @SuppressWarnings("unchecked") + protected void purgeQueue() + { + if (queue != null) + { + KeyedReference<K, V> ref; + while ((ref = (KeyedReference<K, V>)queue.poll()) != null) + { + // Slightly faster than map.get() + map.remove() + K key = ref.getKey(); + map.remove(key, ref); + purged(key); + } + } + } + + protected void purged(K key) + { + } + + protected V dereference(KeyedReference<K, V> ref) + { + if (ref == null) + { + return null; + } + + return ref.get(); + } + + protected abstract KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue); + + /** + * @author Eike Stepper + */ + public static class Strong<K, V> extends ReferenceValueMap<K, V> + { + public Strong() + { + } + + public Strong(ConcurrentMap<K, KeyedReference<K, V>> map) + { + super(map); + } + + @Override + protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue) + { + return new KeyedStrongReference<K, V>(key, value); + } + + @Override + protected ReferenceQueue<V> createQueue() + { + return null; + } + } + + /** + * @author Eike Stepper + */ + public static class Soft<K, V> extends ReferenceValueMap<K, V> + { + public Soft() + { + } + + public Soft(ConcurrentMap<K, KeyedReference<K, V>> map) + { + super(map); + } + + @Override + protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue) + { + return new KeyedSoftReference<K, V>(key, value, queue); + } + } + + /** + * @author Eike Stepper + */ + public static class Weak<K, V> extends ReferenceValueMap<K, V> + { + public Weak() + { + } + + public Weak(ConcurrentMap<K, KeyedReference<K, V>> map) + { + super(map); + } + + @Override + protected KeyedReference<K, V> createReference(K key, V value, ReferenceQueue<V> queue) + { + return new KeyedWeakReference<K, V>(key, value, queue); + } + } + + /** + * @author Eike Stepper + */ + private class EntrySet extends AbstractSet<Map.Entry<K, V>> + { + public EntrySet() + { + } + + @Override + public int size() + { + return map.size(); + } + + @Override + public boolean isEmpty() + { + return map.isEmpty(); + } + + @Override + public boolean contains(Object object) + { + if (object == null) + { + throw new IllegalArgumentException("object == null"); //$NON-NLS-1$ + } + + if (object instanceof Map.Entry<?, ?>) + { + Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object; + Object key = entry.getKey(); + Object value = entry.getValue(); + return key != null && value != null && value.equals(get(key)); + } + + return false; + } + + @Override + public Iterator<Map.Entry<K, V>> iterator() + { + return new EntrySetIterator(); + } + + @Override + public Object[] toArray() + { + Object[] a = new Object[size()]; + int i = 0; + for (Map.Entry<K, V> entry : this) + { + a[i++] = entry; + } + + return a; + } + + @SuppressWarnings("unchecked") + @Override + public <T> T[] toArray(T[] a) + { + if (a == null) + { + throw new IllegalArgumentException("array == null"); //$NON-NLS-1$ + } + + int size = size(); + if (a.length < size) + { + a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); + } + + int i = 0; + for (Map.Entry<K, V> entry : this) + { + a[i++] = (T)entry; + } + + if (a.length > size) + { + a[size] = null; + } + + return a; + } + + @Override + public boolean remove(Object object) + { + if (object == null) + { + throw new IllegalArgumentException("object == null"); //$NON-NLS-1$ + } + + if (object instanceof Map.Entry<?, ?>) + { + Map.Entry<?, ?> entry = (Map.Entry<?, ?>)object; + return map.remove(entry.getKey(), entry.getValue()); + } + + return false; + } + + @Override + public void clear() + { + map.clear(); + } + } + + /** + * @author Eike Stepper + */ + private class EntrySetIterator implements Iterator<Map.Entry<K, V>> + { + private Iterator<Entry<K, KeyedReference<K, V>>> it = map.entrySet().iterator(); + + private MapEntry<K, V> nextEntry; + + private K lastKey; + + public EntrySetIterator() + { + } + + public boolean hasNext() + { + if (nextEntry != null) + { + return true; + } + + while (it.hasNext()) + { + Entry<K, KeyedReference<K, V>> entry = it.next(); + lastKey = entry.getKey(); + V value = dereference(entry.getValue()); + if (value != null) + { + nextEntry = new MapEntry<K, V>(lastKey, value); + return true; + } + } + + return false; + } + + public Entry<K, V> next() + { + if (nextEntry == null) + { + if (!hasNext()) + { + throw new NoSuchElementException(); + } + } + + try + { + return nextEntry; + } + finally + { + nextEntry = null; + } + } + + public void remove() + { + if (lastKey == null) + { + throw new IllegalStateException("lastKey == null"); //$NON-NLS-1$ + } + + map.remove(lastKey); + lastKey = null; + nextEntry = null; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java index 57bb9fed38..596ea14566 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ref/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for memory-sensitive keyed references and value maps.
- */
-package org.eclipse.net4j.util.ref;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for memory-sensitive keyed references and value maps. + */ +package org.eclipse.net4j.util.ref; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java index c5863d4331..10e8442297 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/DelegatingRegistry.java @@ -1,149 +1,149 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Implementation note: AbstractDelegatingRegistry does not preserve the "modifyable view" contract of
- * {@link Map#entrySet()} as well as of {@link Map#keySet()}, i.e. they are disconnected sets and modifications applied
- * to them are not applied to their underlying AbstractDelegatingRegistry.
- * <p>
- *
- * @author Eike Stepper
- */
-public abstract class DelegatingRegistry<K, V> extends Registry<K, V>
-{
- private IRegistry<K, V> delegate;
-
- public DelegatingRegistry(IRegistry<K, V> delegate)
- {
- this.delegate = delegate;
- }
-
- public DelegatingRegistry(IRegistry<K, V> delegate, boolean autoCommit)
- {
- super(autoCommit);
- this.delegate = delegate;
- }
-
- @Override
- public V get(Object key)
- {
- V result = getMap().get(key);
- if (result == null && delegate != null)
- {
- result = delegate.get(key);
- }
-
- return result;
- }
-
- @Override
- public Set<Entry<K, V>> entrySet()
- {
- return mergedEntrySet();
- }
-
- @Override
- public Set<K> keySet()
- {
- return mergedKeySet();
- }
-
- @Override
- public Collection<V> values()
- {
- return mergedValues();
- }
-
- @Override
- protected V register(K key, V value)
- {
- V delegated = delegate != null ? delegate.get(key) : null;
- V old = getMap().put(key, value);
- if (old == null)
- {
- if (delegated != null)
- {
- // Unhidden delegated element now becomes hidden
- getTransaction().rememberDeregistered(key, delegated);
- }
-
- getTransaction().rememberRegistered(key, value);
- return delegated;
- }
-
- getTransaction().rememberDeregistered(key, old);
- getTransaction().rememberRegistered(key, value);
- return old;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- protected V deregister(Object key)
- {
- V delegated = delegate != null ? delegate.get(key) : null;
- V old = getMap().remove(key);
- if (old != null)
- {
- getTransaction().rememberDeregistered((K)key, old);
- if (delegated != null)
- {
- // Hidden delegated element now becomes unhidden
- getTransaction().rememberRegistered((K)key, delegated);
- }
- }
-
- return old;
- }
-
- protected Set<Entry<K, V>> mergedEntrySet()
- {
- final Map<K, V> merged = new HashMap<K, V>();
- if (delegate != null)
- {
- merged.putAll(delegate);
- }
-
- merged.putAll(getMap());
- return merged.entrySet();
- }
-
- protected Set<K> mergedKeySet()
- {
- final Set<K> merged = new HashSet<K>();
- if (delegate != null)
- {
- merged.addAll(delegate.keySet());
- }
-
- merged.addAll(getMap().keySet());
- return merged;
- }
-
- protected Collection<V> mergedValues()
- {
- final List<V> result = new ArrayList<V>();
- for (K key : keySet())
- {
- result.add(get(key));
- }
-
- return result;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Implementation note: AbstractDelegatingRegistry does not preserve the "modifyable view" contract of + * {@link Map#entrySet()} as well as of {@link Map#keySet()}, i.e. they are disconnected sets and modifications applied + * to them are not applied to their underlying AbstractDelegatingRegistry. + * <p> + * + * @author Eike Stepper + */ +public abstract class DelegatingRegistry<K, V> extends Registry<K, V> +{ + private IRegistry<K, V> delegate; + + public DelegatingRegistry(IRegistry<K, V> delegate) + { + this.delegate = delegate; + } + + public DelegatingRegistry(IRegistry<K, V> delegate, boolean autoCommit) + { + super(autoCommit); + this.delegate = delegate; + } + + @Override + public V get(Object key) + { + V result = getMap().get(key); + if (result == null && delegate != null) + { + result = delegate.get(key); + } + + return result; + } + + @Override + public Set<Entry<K, V>> entrySet() + { + return mergedEntrySet(); + } + + @Override + public Set<K> keySet() + { + return mergedKeySet(); + } + + @Override + public Collection<V> values() + { + return mergedValues(); + } + + @Override + protected V register(K key, V value) + { + V delegated = delegate != null ? delegate.get(key) : null; + V old = getMap().put(key, value); + if (old == null) + { + if (delegated != null) + { + // Unhidden delegated element now becomes hidden + getTransaction().rememberDeregistered(key, delegated); + } + + getTransaction().rememberRegistered(key, value); + return delegated; + } + + getTransaction().rememberDeregistered(key, old); + getTransaction().rememberRegistered(key, value); + return old; + } + + @SuppressWarnings("unchecked") + @Override + protected V deregister(Object key) + { + V delegated = delegate != null ? delegate.get(key) : null; + V old = getMap().remove(key); + if (old != null) + { + getTransaction().rememberDeregistered((K)key, old); + if (delegated != null) + { + // Hidden delegated element now becomes unhidden + getTransaction().rememberRegistered((K)key, delegated); + } + } + + return old; + } + + protected Set<Entry<K, V>> mergedEntrySet() + { + final Map<K, V> merged = new HashMap<K, V>(); + if (delegate != null) + { + merged.putAll(delegate); + } + + merged.putAll(getMap()); + return merged.entrySet(); + } + + protected Set<K> mergedKeySet() + { + final Set<K> merged = new HashSet<K>(); + if (delegate != null) + { + merged.addAll(delegate.keySet()); + } + + merged.addAll(getMap().keySet()); + return merged; + } + + protected Collection<V> mergedValues() + { + final List<V> result = new ArrayList<V>(); + for (K key : keySet()) + { + result.add(get(key)); + } + + return result; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java index a65b03216d..f29dbe7620 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapDelegatingRegistry.java @@ -1,52 +1,52 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public class HashMapDelegatingRegistry<K, V> extends DelegatingRegistry<K, V>
-{
- private Map<K, V> map;
-
- public HashMapDelegatingRegistry(IRegistry<K, V> delegate)
- {
- super(delegate);
- map = new HashMap<K, V>();
- }
-
- public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity)
- {
- super(delegate);
- map = new HashMap<K, V>(initialCapacity);
- }
-
- public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity, float loadFactor)
- {
- super(delegate);
- map = new HashMap<K, V>(initialCapacity, loadFactor);
- }
-
- public HashMapDelegatingRegistry(IRegistry<K, V> delegate, Map<? extends K, ? extends V> m)
- {
- super(delegate);
- map = new HashMap<K, V>(m);
- }
-
- @Override
- protected Map<K, V> getMap()
- {
- return map;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public class HashMapDelegatingRegistry<K, V> extends DelegatingRegistry<K, V> +{ + private Map<K, V> map; + + public HashMapDelegatingRegistry(IRegistry<K, V> delegate) + { + super(delegate); + map = new HashMap<K, V>(); + } + + public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity) + { + super(delegate); + map = new HashMap<K, V>(initialCapacity); + } + + public HashMapDelegatingRegistry(IRegistry<K, V> delegate, int initialCapacity, float loadFactor) + { + super(delegate); + map = new HashMap<K, V>(initialCapacity, loadFactor); + } + + public HashMapDelegatingRegistry(IRegistry<K, V> delegate, Map<? extends K, ? extends V> m) + { + super(delegate); + map = new HashMap<K, V>(m); + } + + @Override + protected Map<K, V> getMap() + { + return map; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java index da77b19312..7eff4ae116 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/HashMapRegistry.java @@ -1,48 +1,48 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public class HashMapRegistry<K, V> extends Registry<K, V>
-{
- private Map<K, V> map;
-
- public HashMapRegistry()
- {
- map = new HashMap<K, V>();
- }
-
- public HashMapRegistry(int initialCapacity)
- {
- map = new HashMap<K, V>(initialCapacity);
- }
-
- public HashMapRegistry(int initialCapacity, float loadFactor)
- {
- map = new HashMap<K, V>(initialCapacity, loadFactor);
- }
-
- public HashMapRegistry(Map<? extends K, ? extends V> m)
- {
- map = new HashMap<K, V>(m);
- }
-
- @Override
- protected Map<K, V> getMap()
- {
- return map;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public class HashMapRegistry<K, V> extends Registry<K, V> +{ + private Map<K, V> map; + + public HashMapRegistry() + { + map = new HashMap<K, V>(); + } + + public HashMapRegistry(int initialCapacity) + { + map = new HashMap<K, V>(initialCapacity); + } + + public HashMapRegistry(int initialCapacity, float loadFactor) + { + map = new HashMap<K, V>(initialCapacity, loadFactor); + } + + public HashMapRegistry(Map<? extends K, ? extends V> m) + { + map = new HashMap<K, V>(m); + } + + @Override + protected Map<K, V> getMap() + { + return map; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java index 0a1365231e..a9c928b6ac 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/IRegistry.java @@ -1,29 +1,29 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-import org.eclipse.net4j.util.container.IContainer;
-
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public interface IRegistry<K, V> extends Map<K, V>, IContainer<Map.Entry<K, V>>
-{
- public boolean isAutoCommit();
-
- public void setAutoCommit(boolean on);
-
- public void commit(boolean notifications);
-
- public void commit();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +import org.eclipse.net4j.util.container.IContainer; + +import java.util.Map; + +/** + * @author Eike Stepper + */ +public interface IRegistry<K, V> extends Map<K, V>, IContainer<Map.Entry<K, V>> +{ + public boolean isAutoCommit(); + + public void setAutoCommit(boolean on); + + public void commit(boolean notifications); + + public void commit(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java index 2bd61c5e45..a5a7a4f005 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/Registry.java @@ -1,328 +1,328 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-import org.eclipse.net4j.util.WrappedException;
-import org.eclipse.net4j.util.container.Container;
-import org.eclipse.net4j.util.container.ContainerEvent;
-import org.eclipse.net4j.util.container.IContainerDelta;
-
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author Eike Stepper
- */
-public abstract class Registry<K, V> extends Container<Map.Entry<K, V>> implements IRegistry<K, V>
-{
- private boolean autoCommit;
-
- private Transaction transaction;
-
- protected Registry(boolean autoCommit)
- {
- this.autoCommit = autoCommit;
- }
-
- protected Registry()
- {
- this(true);
- }
-
- @Override
- public boolean isEmpty()
- {
- return keySet().isEmpty();
- }
-
- public int size()
- {
- return keySet().size();
- }
-
- public Set<Entry<K, V>> entrySet()
- {
- return getMap().entrySet();
- }
-
- public Set<K> keySet()
- {
- return getMap().keySet();
- }
-
- public Collection<V> values()
- {
- return getMap().values();
- }
-
- public boolean containsKey(Object key)
- {
- return keySet().contains(key);
- }
-
- public boolean containsValue(Object value)
- {
- return values().contains(value);
- }
-
- public V get(Object key)
- {
- return getMap().get(key);
- }
-
- /**
- * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
- */
- public synchronized V put(K key, V value)
- {
- V result = register(key, value);
- autoCommit();
- return result;
- }
-
- /**
- * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
- */
- public synchronized void putAll(Map<? extends K, ? extends V> t)
- {
- if (!t.isEmpty())
- {
- Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator();
- while (i.hasNext())
- {
- Entry<? extends K, ? extends V> e = i.next();
- register(e.getKey(), e.getValue());
- }
-
- autoCommit();
- }
- }
-
- /**
- * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
- */
- public synchronized V remove(Object key)
- {
- V result = deregister(key);
- autoCommit();
- return result;
- }
-
- /**
- * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}.
- */
- public synchronized void clear()
- {
- if (!isEmpty())
- {
- for (Object key : keySet().toArray())
- {
- deregister(key);
- }
-
- autoCommit();
- }
- }
-
- @SuppressWarnings("unchecked")
- public Entry<K, V>[] getElements()
- {
- return entrySet().toArray(new Entry[size()]);
- }
-
- public boolean isAutoCommit()
- {
- return autoCommit;
- }
-
- public void setAutoCommit(boolean autoCommit)
- {
- this.autoCommit = autoCommit;
- }
-
- public synchronized void commit(boolean notifications)
- {
- if (transaction != null)
- {
- if (!transaction.isOwned())
- {
- OM.LOG.warn("Committing thread is not owner of transaction: " + Thread.currentThread()); //$NON-NLS-1$
- }
-
- transaction.commit(notifications);
- transaction = null;
- notifyAll();
- }
- }
-
- public void commit()
- {
- commit(true);
- }
-
- @Override
- public String toString()
- {
- return getMap().toString();
- }
-
- protected V register(K key, V value)
- {
- Transaction transaction = getTransaction();
- V oldValue = getMap().put(key, value);
- if (oldValue != null)
- {
- transaction.rememberDeregistered(key, oldValue);
- }
-
- transaction.rememberRegistered(key, value);
- return oldValue;
- }
-
- @SuppressWarnings("unchecked")
- protected V deregister(Object key)
- {
- V value = getMap().remove(key);
- if (value != null)
- {
- getTransaction().rememberDeregistered((K)key, value);
- }
-
- return value;
- }
-
- protected Transaction getTransaction()
- {
- for (;;)
- {
- if (transaction == null)
- {
- transaction = new Transaction();
- return transaction;
- }
-
- if (transaction.isOwned())
- {
- transaction.increaseNesting();
- return transaction;
- }
-
- try
- {
- wait();
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
- }
- }
-
- protected void autoCommit()
- {
- if (autoCommit)
- {
- commit();
- }
- }
-
- protected abstract Map<K, V> getMap();
-
- /**
- * @author Eike Stepper
- */
- protected class Transaction
- {
- private int nesting = 1;
-
- private ContainerEvent<Map.Entry<K, V>> event;
-
- private Thread owner;
-
- public Transaction()
- {
- owner = Thread.currentThread();
- initEvent();
- }
-
- private void initEvent()
- {
- event = newContainerEvent();
- }
-
- public boolean isOwned()
- {
- return owner == Thread.currentThread();
- }
-
- public void increaseNesting()
- {
- ++nesting;
- }
-
- public void commit(boolean notifications)
- {
- if (--nesting == 0)
- {
- if (notifications && !event.isEmpty())
- {
- fireEvent(event);
- }
-
- initEvent();
- }
- }
-
- public void rememberRegistered(K key, V value)
- {
- event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.ADDED);
- }
-
- public void rememberDeregistered(K key, V value)
- {
- event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.REMOVED);
- }
- }
-
- /**
- * @author Eike Stepper
- */
- private static final class Element<K, V> implements Map.Entry<K, V>
- {
- private final K key;
-
- private final V value;
-
- private Element(K key, V value)
- {
- this.key = key;
- this.value = value;
- }
-
- public K getKey()
- {
- return key;
- }
-
- public V getValue()
- {
- return value;
- }
-
- public V setValue(V value)
- {
- throw new UnsupportedOperationException();
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +import org.eclipse.net4j.internal.util.bundle.OM; +import org.eclipse.net4j.util.WrappedException; +import org.eclipse.net4j.util.container.Container; +import org.eclipse.net4j.util.container.ContainerEvent; +import org.eclipse.net4j.util.container.IContainerDelta; + +import java.util.Collection; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * @author Eike Stepper + */ +public abstract class Registry<K, V> extends Container<Map.Entry<K, V>> implements IRegistry<K, V> +{ + private boolean autoCommit; + + private Transaction transaction; + + protected Registry(boolean autoCommit) + { + this.autoCommit = autoCommit; + } + + protected Registry() + { + this(true); + } + + @Override + public boolean isEmpty() + { + return keySet().isEmpty(); + } + + public int size() + { + return keySet().size(); + } + + public Set<Entry<K, V>> entrySet() + { + return getMap().entrySet(); + } + + public Set<K> keySet() + { + return getMap().keySet(); + } + + public Collection<V> values() + { + return getMap().values(); + } + + public boolean containsKey(Object key) + { + return keySet().contains(key); + } + + public boolean containsValue(Object value) + { + return values().contains(value); + } + + public V get(Object key) + { + return getMap().get(key); + } + + /** + * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. + */ + public synchronized V put(K key, V value) + { + V result = register(key, value); + autoCommit(); + return result; + } + + /** + * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. + */ + public synchronized void putAll(Map<? extends K, ? extends V> t) + { + if (!t.isEmpty()) + { + Iterator<? extends Entry<? extends K, ? extends V>> i = t.entrySet().iterator(); + while (i.hasNext()) + { + Entry<? extends K, ? extends V> e = i.next(); + register(e.getKey(), e.getValue()); + } + + autoCommit(); + } + } + + /** + * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. + */ + public synchronized V remove(Object key) + { + V result = deregister(key); + autoCommit(); + return result; + } + + /** + * Requires {@link #commit()} to be called later if not {@link #isAutoCommit()}. + */ + public synchronized void clear() + { + if (!isEmpty()) + { + for (Object key : keySet().toArray()) + { + deregister(key); + } + + autoCommit(); + } + } + + @SuppressWarnings("unchecked") + public Entry<K, V>[] getElements() + { + return entrySet().toArray(new Entry[size()]); + } + + public boolean isAutoCommit() + { + return autoCommit; + } + + public void setAutoCommit(boolean autoCommit) + { + this.autoCommit = autoCommit; + } + + public synchronized void commit(boolean notifications) + { + if (transaction != null) + { + if (!transaction.isOwned()) + { + OM.LOG.warn("Committing thread is not owner of transaction: " + Thread.currentThread()); //$NON-NLS-1$ + } + + transaction.commit(notifications); + transaction = null; + notifyAll(); + } + } + + public void commit() + { + commit(true); + } + + @Override + public String toString() + { + return getMap().toString(); + } + + protected V register(K key, V value) + { + Transaction transaction = getTransaction(); + V oldValue = getMap().put(key, value); + if (oldValue != null) + { + transaction.rememberDeregistered(key, oldValue); + } + + transaction.rememberRegistered(key, value); + return oldValue; + } + + @SuppressWarnings("unchecked") + protected V deregister(Object key) + { + V value = getMap().remove(key); + if (value != null) + { + getTransaction().rememberDeregistered((K)key, value); + } + + return value; + } + + protected Transaction getTransaction() + { + for (;;) + { + if (transaction == null) + { + transaction = new Transaction(); + return transaction; + } + + if (transaction.isOwned()) + { + transaction.increaseNesting(); + return transaction; + } + + try + { + wait(); + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + } + } + + protected void autoCommit() + { + if (autoCommit) + { + commit(); + } + } + + protected abstract Map<K, V> getMap(); + + /** + * @author Eike Stepper + */ + protected class Transaction + { + private int nesting = 1; + + private ContainerEvent<Map.Entry<K, V>> event; + + private Thread owner; + + public Transaction() + { + owner = Thread.currentThread(); + initEvent(); + } + + private void initEvent() + { + event = newContainerEvent(); + } + + public boolean isOwned() + { + return owner == Thread.currentThread(); + } + + public void increaseNesting() + { + ++nesting; + } + + public void commit(boolean notifications) + { + if (--nesting == 0) + { + if (notifications && !event.isEmpty()) + { + fireEvent(event); + } + + initEvent(); + } + } + + public void rememberRegistered(K key, V value) + { + event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.ADDED); + } + + public void rememberDeregistered(K key, V value) + { + event.addDelta(new Element<K, V>(key, value), IContainerDelta.Kind.REMOVED); + } + } + + /** + * @author Eike Stepper + */ + private static final class Element<K, V> implements Map.Entry<K, V> + { + private final K key; + + private final V value; + + private Element(K key, V value) + { + this.key = key; + this.value = value; + } + + public K getKey() + { + return key; + } + + public V getValue() + { + return value; + } + + public V setValue(V value) + { + throw new UnsupportedOperationException(); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java index 14469845a1..5b22040fc7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/RegistryUtil.java @@ -1,31 +1,31 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-/**
- * @author Eike Stepper
- */
-public final class RegistryUtil
-{
- private RegistryUtil()
- {
- }
-
- public <K, V> IRegistry<K, V> unmodifiableRegistry(IRegistry<K, V> registry)
- {
- if (registry instanceof UnmodifiableRegistry<?, ?>)
- {
- return registry;
- }
-
- return new UnmodifiableRegistry<K, V>(registry);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +/** + * @author Eike Stepper + */ +public final class RegistryUtil +{ + private RegistryUtil() + { + } + + public <K, V> IRegistry<K, V> unmodifiableRegistry(IRegistry<K, V> registry) + { + if (registry instanceof UnmodifiableRegistry<?, ?>) + { + return registry; + } + + return new UnmodifiableRegistry<K, V>(registry); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java index a9b9a18f85..1d2bdbfac0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/UnmodifiableRegistry.java @@ -1,150 +1,150 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.registry;
-
-import org.eclipse.net4j.util.event.IListener;
-
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
-
-public class UnmodifiableRegistry<K, V> implements IRegistry<K, V>
-{
- private IRegistry<K, V> delegate;
-
- public UnmodifiableRegistry(IRegistry<K, V> delegate)
- {
- this.delegate = delegate;
- }
-
- public void addListener(IListener listener)
- {
- delegate.addListener(listener);
- }
-
- public void removeListener(IListener listener)
- {
- delegate.removeListener(listener);
- }
-
- /**
- * @since 3.0
- */
- public IListener[] getListeners()
- {
- return delegate.getListeners();
- }
-
- /**
- * @since 3.0
- */
- public boolean hasListeners()
- {
- return delegate.hasListeners();
- }
-
- public V put(K key, V value)
- {
- throw new UnsupportedOperationException();
- }
-
- public void putAll(Map<? extends K, ? extends V> t)
- {
- throw new UnsupportedOperationException();
- }
-
- public V remove(Object key)
- {
- throw new UnsupportedOperationException();
- }
-
- public void clear()
- {
- throw new UnsupportedOperationException();
- }
-
- public void commit()
- {
- throw new UnsupportedOperationException();
- }
-
- public void commit(boolean notifications)
- {
- throw new UnsupportedOperationException();
- }
-
- public void setAutoCommit(boolean on)
- {
- throw new UnsupportedOperationException();
- }
-
- public boolean isAutoCommit()
- {
- return delegate.isAutoCommit();
- }
-
- public boolean isEmpty()
- {
- return delegate.isEmpty();
- }
-
- public int size()
- {
- return delegate.size();
- }
-
- public Entry<K, V>[] getElements()
- {
- return delegate.getElements();
- }
-
- public V get(Object key)
- {
- return delegate.get(key);
- }
-
- public boolean containsKey(Object key)
- {
- return delegate.containsKey(key);
- }
-
- public boolean containsValue(Object value)
- {
- return delegate.containsValue(value);
- }
-
- public Set<Entry<K, V>> entrySet()
- {
- return delegate.entrySet();
- }
-
- public Set<K> keySet()
- {
- return delegate.keySet();
- }
-
- public Collection<V> values()
- {
- return delegate.values();
- }
-
- @Override
- public boolean equals(Object o)
- {
- return delegate.equals(o);
- }
-
- @Override
- public int hashCode()
- {
- return delegate.hashCode();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.registry; + +import org.eclipse.net4j.util.event.IListener; + +import java.util.Collection; +import java.util.Map; +import java.util.Set; + +public class UnmodifiableRegistry<K, V> implements IRegistry<K, V> +{ + private IRegistry<K, V> delegate; + + public UnmodifiableRegistry(IRegistry<K, V> delegate) + { + this.delegate = delegate; + } + + public void addListener(IListener listener) + { + delegate.addListener(listener); + } + + public void removeListener(IListener listener) + { + delegate.removeListener(listener); + } + + /** + * @since 3.0 + */ + public IListener[] getListeners() + { + return delegate.getListeners(); + } + + /** + * @since 3.0 + */ + public boolean hasListeners() + { + return delegate.hasListeners(); + } + + public V put(K key, V value) + { + throw new UnsupportedOperationException(); + } + + public void putAll(Map<? extends K, ? extends V> t) + { + throw new UnsupportedOperationException(); + } + + public V remove(Object key) + { + throw new UnsupportedOperationException(); + } + + public void clear() + { + throw new UnsupportedOperationException(); + } + + public void commit() + { + throw new UnsupportedOperationException(); + } + + public void commit(boolean notifications) + { + throw new UnsupportedOperationException(); + } + + public void setAutoCommit(boolean on) + { + throw new UnsupportedOperationException(); + } + + public boolean isAutoCommit() + { + return delegate.isAutoCommit(); + } + + public boolean isEmpty() + { + return delegate.isEmpty(); + } + + public int size() + { + return delegate.size(); + } + + public Entry<K, V>[] getElements() + { + return delegate.getElements(); + } + + public V get(Object key) + { + return delegate.get(key); + } + + public boolean containsKey(Object key) + { + return delegate.containsKey(key); + } + + public boolean containsValue(Object value) + { + return delegate.containsValue(value); + } + + public Set<Entry<K, V>> entrySet() + { + return delegate.entrySet(); + } + + public Set<K> keySet() + { + return delegate.keySet(); + } + + public Collection<V> values() + { + return delegate.values(); + } + + @Override + public boolean equals(Object o) + { + return delegate.equals(o); + } + + @Override + public int hashCode() + { + return delegate.hashCode(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java index 2a27162b50..99358404ed 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/registry/package-info.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for general purpose registries.
- * A registry is like a <code>Map</code> but has some additional features:
- * <ul>
- * <li>It provides a descriptor framework for registry elements that
- * are to be instantiated lazily
- * <li>It provides a notification framework that enables clients to
- * react on events (including the resolution of a lazy descriptor)
- * <ul>
- */
-package org.eclipse.net4j.util.registry;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for general purpose registries. + * A registry is like a <code>Map</code> but has some additional features: + * <ul> + * <li>It provides a descriptor framework for registry elements that + * are to be instantiated lazily + * <li>It provides a notification framework that enables clients to + * react on events (including the resolution of a lazy descriptor) + * <ul> + */ +package org.eclipse.net4j.util.registry; diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java index 18bb25752c..953cd8cb79 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiator.java @@ -1,146 +1,146 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.internal.util.bundle.OM;
-
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-
-/**
- * @author Eike Stepper
- */
-public class ChallengeNegotiator extends ChallengeResponseNegotiator
-{
- public static final int DEFAULT_TOKEN_LENGTH = 1024;
-
- private int tokenLength = DEFAULT_TOKEN_LENGTH;
-
- private IRandomizer randomizer;
-
- private IUserManager userManager;
-
- public ChallengeNegotiator()
- {
- super(true);
- }
-
- public int getTokenLength()
- {
- return tokenLength;
- }
-
- public void setTokenLength(int tokenLength)
- {
- this.tokenLength = tokenLength;
- }
-
- public IRandomizer getRandomizer()
- {
- return randomizer;
- }
-
- public void setRandomizer(IRandomizer randomizer)
- {
- this.randomizer = randomizer;
- }
-
- public IUserManager getUserManager()
- {
- return userManager;
- }
-
- public void setUserManager(IUserManager userManager)
- {
- this.userManager = userManager;
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- if (tokenLength <= 0)
- {
- throw new IllegalStateException("tokenLength must be positive"); //$NON-NLS-1$
- }
-
- if (randomizer == null)
- {
- throw new IllegalStateException("randomizer == null"); //$NON-NLS-1$
- }
-
- if (userManager == null)
- {
- throw new IllegalStateException("userManager == null"); //$NON-NLS-1$
- }
- }
-
- protected byte[] createRandomToken()
- {
- byte[] token = new byte[tokenLength];
- randomizer.nextBytes(token);
- return token;
- }
-
- protected byte[] encryptToken(String userID, byte[] token) throws NegotiationException
- {
- try
- {
- return userManager.encrypt(userID, token, getEncryptionAlgorithmName(), getEncryptionSaltBytes(),
- getEncryptionIterationCount());
- }
- catch (Exception ex)
- {
- OM.LOG.error("Token encryption failed", ex); //$NON-NLS-1$
- return null;
- }
- }
-
- @Override
- protected void createChallenge(INegotiationContext context, ByteBuffer challenge)
- {
- // Create and remember a random token
- byte[] randomToken = createRandomToken();
- context.setInfo(randomToken);
-
- // Set the token into challenge
- challenge.putInt(randomToken.length);
- challenge.put(randomToken);
- }
-
- @Override
- protected boolean handleResponse(INegotiationContext context, ByteBuffer response)
- {
- // Get remembered random token
- byte[] randomToken = (byte[])context.getInfo();
-
- // Get userID from response
- int size = response.getInt();
- byte[] userIDBytes = new byte[size];
- response.get(userIDBytes);
- String userID = new String(userIDBytes);
-
- // Get crypted token from response
- size = response.getInt();
- byte[] responseToken = new byte[size];
- response.get(responseToken);
-
- // Encrypt the remembered token and compare to crypted token from response
- byte[] cryptedToken = encryptToken(userID, randomToken);
- boolean success = Arrays.equals(responseToken, cryptedToken);
- if (success)
- {
- context.setUserID(userID);
- }
-
- return success;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.internal.util.bundle.OM; + +import java.nio.ByteBuffer; +import java.util.Arrays; + +/** + * @author Eike Stepper + */ +public class ChallengeNegotiator extends ChallengeResponseNegotiator +{ + public static final int DEFAULT_TOKEN_LENGTH = 1024; + + private int tokenLength = DEFAULT_TOKEN_LENGTH; + + private IRandomizer randomizer; + + private IUserManager userManager; + + public ChallengeNegotiator() + { + super(true); + } + + public int getTokenLength() + { + return tokenLength; + } + + public void setTokenLength(int tokenLength) + { + this.tokenLength = tokenLength; + } + + public IRandomizer getRandomizer() + { + return randomizer; + } + + public void setRandomizer(IRandomizer randomizer) + { + this.randomizer = randomizer; + } + + public IUserManager getUserManager() + { + return userManager; + } + + public void setUserManager(IUserManager userManager) + { + this.userManager = userManager; + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + if (tokenLength <= 0) + { + throw new IllegalStateException("tokenLength must be positive"); //$NON-NLS-1$ + } + + if (randomizer == null) + { + throw new IllegalStateException("randomizer == null"); //$NON-NLS-1$ + } + + if (userManager == null) + { + throw new IllegalStateException("userManager == null"); //$NON-NLS-1$ + } + } + + protected byte[] createRandomToken() + { + byte[] token = new byte[tokenLength]; + randomizer.nextBytes(token); + return token; + } + + protected byte[] encryptToken(String userID, byte[] token) throws NegotiationException + { + try + { + return userManager.encrypt(userID, token, getEncryptionAlgorithmName(), getEncryptionSaltBytes(), + getEncryptionIterationCount()); + } + catch (Exception ex) + { + OM.LOG.error("Token encryption failed", ex); //$NON-NLS-1$ + return null; + } + } + + @Override + protected void createChallenge(INegotiationContext context, ByteBuffer challenge) + { + // Create and remember a random token + byte[] randomToken = createRandomToken(); + context.setInfo(randomToken); + + // Set the token into challenge + challenge.putInt(randomToken.length); + challenge.put(randomToken); + } + + @Override + protected boolean handleResponse(INegotiationContext context, ByteBuffer response) + { + // Get remembered random token + byte[] randomToken = (byte[])context.getInfo(); + + // Get userID from response + int size = response.getInt(); + byte[] userIDBytes = new byte[size]; + response.get(userIDBytes); + String userID = new String(userIDBytes); + + // Get crypted token from response + size = response.getInt(); + byte[] responseToken = new byte[size]; + response.get(responseToken); + + // Encrypt the remembered token and compare to crypted token from response + byte[] cryptedToken = encryptToken(userID, randomToken); + boolean success = Arrays.equals(responseToken, cryptedToken); + if (success) + { + context.setUserID(userID); + } + + return success; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java index cacc2b51ea..6d4fff6652 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorConfigurer.java @@ -1,80 +1,80 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.container.IElementProcessor;
-import org.eclipse.net4j.util.container.IManagedContainer;
-
-/**
- * @author Eike Stepper
- */
-public class ChallengeNegotiatorConfigurer implements IElementProcessor
-{
- public ChallengeNegotiatorConfigurer()
- {
- }
-
- public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
- Object element)
- {
- if (element instanceof ChallengeNegotiator)
- {
- ChallengeNegotiator negotiator = (ChallengeNegotiator)element;
- if (negotiator.getRandomizer() == null)
- {
- IRandomizer randomizer = getRandomizer(container, description);
- negotiator.setRandomizer(randomizer);
- }
-
- if (negotiator.getUserManager() == null)
- {
- IUserManager userManager = getUserManager(container, description);
- negotiator.setUserManager(userManager);
- }
- }
-
- return element;
- }
-
- protected IRandomizer getRandomizer(IManagedContainer container, String description)
- {
- String productGroup = RandomizerFactory.PRODUCT_GROUP;
- String type = getRandomizerType(description);
- return (IRandomizer)container.getElement(productGroup, type, getRandomizerDescription(description));
- }
-
- protected String getRandomizerType(String description)
- {
- return RandomizerFactory.TYPE;
- }
-
- protected String getRandomizerDescription(String description)
- {
- return null;
- }
-
- protected IUserManager getUserManager(IManagedContainer container, String description)
- {
- String productGroup = FileUserManagerFactory.PRODUCT_GROUP;
- String type = getUserManagerType(description);
- return (IUserManager)container.getElement(productGroup, type, getUserManagerDescription(description));
- }
-
- protected String getUserManagerType(String description)
- {
- return FileUserManagerFactory.TYPE;
- }
-
- protected String getUserManagerDescription(String description)
- {
- return description;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.container.IElementProcessor; +import org.eclipse.net4j.util.container.IManagedContainer; + +/** + * @author Eike Stepper + */ +public class ChallengeNegotiatorConfigurer implements IElementProcessor +{ + public ChallengeNegotiatorConfigurer() + { + } + + public Object process(IManagedContainer container, String productGroup, String factoryType, String description, + Object element) + { + if (element instanceof ChallengeNegotiator) + { + ChallengeNegotiator negotiator = (ChallengeNegotiator)element; + if (negotiator.getRandomizer() == null) + { + IRandomizer randomizer = getRandomizer(container, description); + negotiator.setRandomizer(randomizer); + } + + if (negotiator.getUserManager() == null) + { + IUserManager userManager = getUserManager(container, description); + negotiator.setUserManager(userManager); + } + } + + return element; + } + + protected IRandomizer getRandomizer(IManagedContainer container, String description) + { + String productGroup = RandomizerFactory.PRODUCT_GROUP; + String type = getRandomizerType(description); + return (IRandomizer)container.getElement(productGroup, type, getRandomizerDescription(description)); + } + + protected String getRandomizerType(String description) + { + return RandomizerFactory.TYPE; + } + + protected String getRandomizerDescription(String description) + { + return null; + } + + protected IUserManager getUserManager(IManagedContainer container, String description) + { + String productGroup = FileUserManagerFactory.PRODUCT_GROUP; + String type = getUserManagerType(description); + return (IUserManager)container.getElement(productGroup, type, getUserManagerDescription(description)); + } + + protected String getUserManagerType(String description) + { + return FileUserManagerFactory.TYPE; + } + + protected String getUserManagerDescription(String description) + { + return description; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java index ac4dd6ab9f..61cb7f0da9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeNegotiatorFactory.java @@ -1,29 +1,29 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public class ChallengeNegotiatorFactory extends NegotiatorFactory
-{
- public static final String TYPE = "challenge"; //$NON-NLS-1$
-
- public ChallengeNegotiatorFactory()
- {
- super(TYPE);
- }
-
- public ChallengeNegotiator create(String description)
- {
- return new ChallengeNegotiator();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public class ChallengeNegotiatorFactory extends NegotiatorFactory +{ + public static final String TYPE = "challenge"; //$NON-NLS-1$ + + public ChallengeNegotiatorFactory() + { + super(TYPE); + } + + public ChallengeNegotiator create(String description) + { + return new ChallengeNegotiator(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java index 505459cdcf..66985290df 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ChallengeResponseNegotiator.java @@ -1,200 +1,200 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.concurrent.ConcurrencyUtil;
-import org.eclipse.net4j.util.fsm.ITransition;
-
-import java.nio.ByteBuffer;
-
-/**
- * @author Eike Stepper
- */
-public abstract class ChallengeResponseNegotiator extends
- Negotiator<IChallengeResponse.State, IChallengeResponse.Event> implements IChallengeResponse
-{
- private String encryptionAlgorithmName = SecurityUtil.PBE_WITH_MD5_AND_DES;
-
- private byte[] encryptionSaltBytes = SecurityUtil.DEFAULT_SALT;
-
- private int encryptionIterationCount = SecurityUtil.DEFAULT_ITERATION_COUNT;
-
- public ChallengeResponseNegotiator(boolean initiator)
- {
- super(State.class, Event.class, State.INITIAL, State.SUCCESS, State.FAILURE, Event.START, Event.BUFFER, initiator);
-
- init(State.INITIAL, Event.START, new Transition()
- {
- @Override
- protected void execute(INegotiationContext context, ByteBuffer NULL)
- {
- // Create and transmit challenge
- ByteBuffer challenge = context.getBuffer();
- createChallenge(context, challenge);
- context.transmitBuffer(challenge);
-
- // Set context state
- changeState(context, State.CHALLENGE);
- }
- });
-
- init(State.INITIAL, Event.BUFFER, new Transition()
- {
- @Override
- protected void execute(INegotiationContext context, ByteBuffer challenge)
- {
- // Handle challenge and transmit response
- ByteBuffer response = context.getBuffer();
- handleChallenge(context, challenge, response);
- context.transmitBuffer(response);
-
- // Set context state
- changeState(context, State.RESPONSE);
- }
- });
-
- init(State.CHALLENGE, Event.BUFFER, new Transition()
- {
- @Override
- protected void execute(INegotiationContext context, ByteBuffer response)
- {
- // Handle response
- boolean success = handleResponse(context, response);
-
- // Transmit acknowledgement
- ByteBuffer acknowledgement = context.getBuffer();
- acknowledgement.put(success ? ACKNOWLEDGE_SUCCESS : ACKNOWLEDGE_FAILURE);
- context.transmitBuffer(acknowledgement);
- ConcurrencyUtil.sleep(500);
-
- // Set context state
- changeState(context, success ? State.SUCCESS : State.FAILURE);
- }
- });
-
- init(State.RESPONSE, Event.BUFFER, new Transition()
- {
- @Override
- protected void execute(INegotiationContext context, ByteBuffer acknowledgement)
- {
- boolean success = acknowledgement.get() == ACKNOWLEDGE_SUCCESS;
- changeState(context, success ? State.SUCCESS : State.FAILURE);
- handleAcknowledgement(context, success);
- }
- });
- }
-
- /**
- * @since 2.0
- */
- public String getEncryptionAlgorithmName()
- {
- return encryptionAlgorithmName;
- }
-
- /**
- * @since 2.0
- */
- public void setEncryptionAlgorithmName(String encryptionAlgorithmName)
- {
- this.encryptionAlgorithmName = encryptionAlgorithmName;
- }
-
- /**
- * @since 2.0
- */
- public byte[] getEncryptionSaltBytes()
- {
- return encryptionSaltBytes;
- }
-
- /**
- * @since 2.0
- */
- public void setEncryptionSaltBytes(byte[] encryptionSaltBytes)
- {
- this.encryptionSaltBytes = encryptionSaltBytes;
- }
-
- /**
- * @since 2.0
- */
- public int getEncryptionIterationCount()
- {
- return encryptionIterationCount;
- }
-
- /**
- * @since 2.0
- */
- public void setEncryptionIterationCount(int encryptionIterationCount)
- {
- this.encryptionIterationCount = encryptionIterationCount;
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- checkState(encryptionAlgorithmName, "encryptionAlgorithmName"); //$NON-NLS-1$
- checkState(encryptionSaltBytes, "encryptionSaltBytes"); //$NON-NLS-1$
- checkState(encryptionSaltBytes.length > 0, "encryptionSaltBytes"); //$NON-NLS-1$
- checkState(encryptionIterationCount > 0, "encryptionIterationCount"); //$NON-NLS-1$
- }
-
- @Override
- protected State getState(INegotiationContext subject)
- {
- return (State)subject.getState();
- }
-
- @Override
- protected void setState(INegotiationContext subject, State state)
- {
- subject.setState(state);
- }
-
- protected void createChallenge(INegotiationContext context, ByteBuffer challenge)
- {
- throw new UnsupportedOperationException();
- }
-
- protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response)
- {
- throw new UnsupportedOperationException();
- }
-
- protected boolean handleResponse(INegotiationContext context, ByteBuffer response)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @since 2.0
- */
- protected void handleAcknowledgement(INegotiationContext context, boolean success)
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * @author Eike Stepper
- */
- protected abstract class Transition implements ITransition<State, Event, INegotiationContext, ByteBuffer>
- {
- public final void execute(INegotiationContext context, State state, Event event, ByteBuffer buffer)
- {
- execute(context, buffer);
- }
-
- protected abstract void execute(INegotiationContext context, ByteBuffer buffer);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.concurrent.ConcurrencyUtil; +import org.eclipse.net4j.util.fsm.ITransition; + +import java.nio.ByteBuffer; + +/** + * @author Eike Stepper + */ +public abstract class ChallengeResponseNegotiator extends + Negotiator<IChallengeResponse.State, IChallengeResponse.Event> implements IChallengeResponse +{ + private String encryptionAlgorithmName = SecurityUtil.PBE_WITH_MD5_AND_DES; + + private byte[] encryptionSaltBytes = SecurityUtil.DEFAULT_SALT; + + private int encryptionIterationCount = SecurityUtil.DEFAULT_ITERATION_COUNT; + + public ChallengeResponseNegotiator(boolean initiator) + { + super(State.class, Event.class, State.INITIAL, State.SUCCESS, State.FAILURE, Event.START, Event.BUFFER, initiator); + + init(State.INITIAL, Event.START, new Transition() + { + @Override + protected void execute(INegotiationContext context, ByteBuffer NULL) + { + // Create and transmit challenge + ByteBuffer challenge = context.getBuffer(); + createChallenge(context, challenge); + context.transmitBuffer(challenge); + + // Set context state + changeState(context, State.CHALLENGE); + } + }); + + init(State.INITIAL, Event.BUFFER, new Transition() + { + @Override + protected void execute(INegotiationContext context, ByteBuffer challenge) + { + // Handle challenge and transmit response + ByteBuffer response = context.getBuffer(); + handleChallenge(context, challenge, response); + context.transmitBuffer(response); + + // Set context state + changeState(context, State.RESPONSE); + } + }); + + init(State.CHALLENGE, Event.BUFFER, new Transition() + { + @Override + protected void execute(INegotiationContext context, ByteBuffer response) + { + // Handle response + boolean success = handleResponse(context, response); + + // Transmit acknowledgement + ByteBuffer acknowledgement = context.getBuffer(); + acknowledgement.put(success ? ACKNOWLEDGE_SUCCESS : ACKNOWLEDGE_FAILURE); + context.transmitBuffer(acknowledgement); + ConcurrencyUtil.sleep(500); + + // Set context state + changeState(context, success ? State.SUCCESS : State.FAILURE); + } + }); + + init(State.RESPONSE, Event.BUFFER, new Transition() + { + @Override + protected void execute(INegotiationContext context, ByteBuffer acknowledgement) + { + boolean success = acknowledgement.get() == ACKNOWLEDGE_SUCCESS; + changeState(context, success ? State.SUCCESS : State.FAILURE); + handleAcknowledgement(context, success); + } + }); + } + + /** + * @since 2.0 + */ + public String getEncryptionAlgorithmName() + { + return encryptionAlgorithmName; + } + + /** + * @since 2.0 + */ + public void setEncryptionAlgorithmName(String encryptionAlgorithmName) + { + this.encryptionAlgorithmName = encryptionAlgorithmName; + } + + /** + * @since 2.0 + */ + public byte[] getEncryptionSaltBytes() + { + return encryptionSaltBytes; + } + + /** + * @since 2.0 + */ + public void setEncryptionSaltBytes(byte[] encryptionSaltBytes) + { + this.encryptionSaltBytes = encryptionSaltBytes; + } + + /** + * @since 2.0 + */ + public int getEncryptionIterationCount() + { + return encryptionIterationCount; + } + + /** + * @since 2.0 + */ + public void setEncryptionIterationCount(int encryptionIterationCount) + { + this.encryptionIterationCount = encryptionIterationCount; + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + checkState(encryptionAlgorithmName, "encryptionAlgorithmName"); //$NON-NLS-1$ + checkState(encryptionSaltBytes, "encryptionSaltBytes"); //$NON-NLS-1$ + checkState(encryptionSaltBytes.length > 0, "encryptionSaltBytes"); //$NON-NLS-1$ + checkState(encryptionIterationCount > 0, "encryptionIterationCount"); //$NON-NLS-1$ + } + + @Override + protected State getState(INegotiationContext subject) + { + return (State)subject.getState(); + } + + @Override + protected void setState(INegotiationContext subject, State state) + { + subject.setState(state); + } + + protected void createChallenge(INegotiationContext context, ByteBuffer challenge) + { + throw new UnsupportedOperationException(); + } + + protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response) + { + throw new UnsupportedOperationException(); + } + + protected boolean handleResponse(INegotiationContext context, ByteBuffer response) + { + throw new UnsupportedOperationException(); + } + + /** + * @since 2.0 + */ + protected void handleAcknowledgement(INegotiationContext context, boolean success) + { + throw new UnsupportedOperationException(); + } + + /** + * @author Eike Stepper + */ + protected abstract class Transition implements ITransition<State, Event, INegotiationContext, ByteBuffer> + { + public final void execute(INegotiationContext context, State state, Event event, ByteBuffer buffer) + { + execute(context, buffer); + } + + protected abstract void execute(INegotiationContext context, ByteBuffer buffer); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java index 001280e4ac..872a4ca7f2 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Credentials.java @@ -1,29 +1,29 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public class Credentials implements ICredentials
-{
- private String userID;
-
- public Credentials(String userID)
- {
- this.userID = userID;
- }
-
- public String getUserID()
- {
- return userID;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public class Credentials implements ICredentials +{ + private String userID; + + public Credentials(String userID) + { + this.userID = userID; + } + + public String getUserID() + { + return userID; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java index 8ba0bda86f..cbc7b4582d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/CredentialsProviderFactory.java @@ -1,30 +1,30 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.factory.Factory;
-import org.eclipse.net4j.util.factory.ProductCreationException;
-
-/**
- * @author Eike Stepper
- * @since 3.0
- */
-public abstract class CredentialsProviderFactory extends Factory
-{
- public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.security.credentialsProviders"; //$NON-NLS-1$
-
- public CredentialsProviderFactory(String type)
- {
- super(PRODUCT_GROUP, type);
- }
-
- public abstract ICredentialsProvider create(String description) throws ProductCreationException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.factory.Factory; +import org.eclipse.net4j.util.factory.ProductCreationException; + +/** + * @author Eike Stepper + * @since 3.0 + */ +public abstract class CredentialsProviderFactory extends Factory +{ + public static final String PRODUCT_GROUP = "org.eclipse.net4j.util.security.credentialsProviders"; //$NON-NLS-1$ + + public CredentialsProviderFactory(String type) + { + super(PRODUCT_GROUP, type); + } + + public abstract ICredentialsProvider create(String description) throws ProductCreationException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java index aa6206657d..a2963ba06e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManager.java @@ -1,142 +1,142 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.io.IORuntimeException;
-import org.eclipse.net4j.util.io.IOUtil;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.text.MessageFormat;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Properties;
-
-/**
- * @author Eike Stepper
- */
-public class FileUserManager extends UserManager
-{
- protected String fileName;
-
- public FileUserManager()
- {
- }
-
- public String getFileName()
- {
- return fileName;
- }
-
- public void setFileName(String fileName)
- {
- this.fileName = fileName;
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- if (fileName == null)
- {
- throw new IllegalStateException("fileName == null"); //$NON-NLS-1$
- }
-
- File file = new File(fileName);
- if (file.exists())
- {
- if (!file.isFile())
- {
- throw new IllegalStateException("Not a file: " + fileName); //$NON-NLS-1$
- }
- }
- else
- {
- throw new FileNotFoundException("User manager file not found: " + fileName);
- }
- }
-
- @Override
- protected void load(Map<String, char[]> users) throws IORuntimeException
- {
- File file = new File(fileName);
- if (!file.exists())
- {
- return;
- }
-
- FileInputStream stream = IOUtil.openInputStream(new File(fileName));
- try
- {
- load(users, stream);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- IOUtil.closeSilent(stream);
- }
- }
-
- protected void load(Map<String, char[]> users, InputStream stream) throws IOException
- {
- Properties properties = new Properties();
- properties.load(stream);
- for (Entry<Object, Object> entry : properties.entrySet())
- {
- String userID = (String)entry.getKey();
- char[] password = ((String)entry.getValue()).toCharArray();
- users.put(userID, password);
- }
- }
-
- @Override
- protected void save(Map<String, char[]> users) throws IORuntimeException
- {
- File file = new File(fileName);
- if (!file.exists())
- {
- return;
- }
-
- FileOutputStream stream = IOUtil.openOutputStream(new File(fileName));
- try
- {
- save(users, stream);
- }
- catch (IOException ex)
- {
- throw new IORuntimeException(ex);
- }
- finally
- {
- IOUtil.closeSilent(stream);
- }
- }
-
- protected void save(Map<String, char[]> users, FileOutputStream stream) throws IOException
- {
- Properties properties = new Properties();
- for (Entry<String, char[]> entry : users.entrySet())
- {
- properties.put(entry.getKey(), new String(entry.getValue()));
- }
-
- String comment = MessageFormat.format("User database {0,date} {0,time,HH:mm:ss:SSS}", System.currentTimeMillis());
- properties.store(stream, comment);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.io.IORuntimeException; +import org.eclipse.net4j.util.io.IOUtil; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.text.MessageFormat; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +/** + * @author Eike Stepper + */ +public class FileUserManager extends UserManager +{ + protected String fileName; + + public FileUserManager() + { + } + + public String getFileName() + { + return fileName; + } + + public void setFileName(String fileName) + { + this.fileName = fileName; + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + if (fileName == null) + { + throw new IllegalStateException("fileName == null"); //$NON-NLS-1$ + } + + File file = new File(fileName); + if (file.exists()) + { + if (!file.isFile()) + { + throw new IllegalStateException("Not a file: " + fileName); //$NON-NLS-1$ + } + } + else + { + throw new FileNotFoundException("User manager file not found: " + fileName); + } + } + + @Override + protected void load(Map<String, char[]> users) throws IORuntimeException + { + File file = new File(fileName); + if (!file.exists()) + { + return; + } + + FileInputStream stream = IOUtil.openInputStream(new File(fileName)); + try + { + load(users, stream); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + IOUtil.closeSilent(stream); + } + } + + protected void load(Map<String, char[]> users, InputStream stream) throws IOException + { + Properties properties = new Properties(); + properties.load(stream); + for (Entry<Object, Object> entry : properties.entrySet()) + { + String userID = (String)entry.getKey(); + char[] password = ((String)entry.getValue()).toCharArray(); + users.put(userID, password); + } + } + + @Override + protected void save(Map<String, char[]> users) throws IORuntimeException + { + File file = new File(fileName); + if (!file.exists()) + { + return; + } + + FileOutputStream stream = IOUtil.openOutputStream(new File(fileName)); + try + { + save(users, stream); + } + catch (IOException ex) + { + throw new IORuntimeException(ex); + } + finally + { + IOUtil.closeSilent(stream); + } + } + + protected void save(Map<String, char[]> users, FileOutputStream stream) throws IOException + { + Properties properties = new Properties(); + for (Entry<String, char[]> entry : users.entrySet()) + { + properties.put(entry.getKey(), new String(entry.getValue())); + } + + String comment = MessageFormat.format("User database {0,date} {0,time,HH:mm:ss:SSS}", System.currentTimeMillis()); + properties.store(stream, comment); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java index 437ef9c948..9c4d862060 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/FileUserManagerFactory.java @@ -1,33 +1,33 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * TODO Consider file attributes when creating initially empty file
- *
- * @author Eike Stepper
- */
-public class FileUserManagerFactory extends UserManagerFactory
-{
- public static final String TYPE = "file"; //$NON-NLS-1$
-
- public FileUserManagerFactory()
- {
- super(TYPE);
- }
-
- public FileUserManager create(String description)
- {
- FileUserManager userManager = new FileUserManager();
- userManager.setFileName(description);
- return userManager;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * TODO Consider file attributes when creating initially empty file + * + * @author Eike Stepper + */ +public class FileUserManagerFactory extends UserManagerFactory +{ + public static final String TYPE = "file"; //$NON-NLS-1$ + + public FileUserManagerFactory() + { + super(TYPE); + } + + public FileUserManager create(String description) + { + FileUserManager userManager = new FileUserManager(); + userManager.setFileName(description); + return userManager; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java index 9e00189477..46e2443591 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IChallengeResponse.java @@ -1,37 +1,37 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface IChallengeResponse
-{
- public static final byte ACKNOWLEDGE_SUCCESS = 1;
-
- public static final byte ACKNOWLEDGE_FAILURE = 0;
-
- /**
- * @author Eike Stepper
- */
- public enum State
- {
- INITIAL, CHALLENGE, RESPONSE, SUCCESS, FAILURE
- }
-
- /**
- * @author Eike Stepper
- */
- public enum Event
- {
- START, BUFFER
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface IChallengeResponse +{ + public static final byte ACKNOWLEDGE_SUCCESS = 1; + + public static final byte ACKNOWLEDGE_FAILURE = 0; + + /** + * @author Eike Stepper + */ + public enum State + { + INITIAL, CHALLENGE, RESPONSE, SUCCESS, FAILURE + } + + /** + * @author Eike Stepper + */ + public enum Event + { + START, BUFFER + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java index 80f3c3f4d0..0f368eb691 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentials.java @@ -1,18 +1,18 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface ICredentials extends IUserAware
-{
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface ICredentials extends IUserAware +{ +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java index b979ca567d..80caef0f9f 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ICredentialsProvider.java @@ -1,21 +1,21 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface ICredentialsProvider
-{
- public boolean isInteractive();
-
- public ICredentials getCredentials();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface ICredentialsProvider +{ + public boolean isInteractive(); + + public ICredentials getCredentials(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java index 69188fa911..0d651c1675 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiationContext.java @@ -1,57 +1,57 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import java.nio.ByteBuffer;
-
-/**
- * @author Eike Stepper
- */
-public interface INegotiationContext
-{
- /**
- * @since 2.0
- */
- public static final int NO_TIMEOUT = -1;
-
- public ByteBuffer getBuffer();
-
- public void transmitBuffer(ByteBuffer buffer);
-
- public Receiver getReceiver();
-
- public void setReceiver(Receiver receiver);
-
- public Enum<?> getState();
-
- public void setState(Enum<?> state);
-
- public void setUserID(String userID);
-
- public Object getInfo();
-
- public void setInfo(Object info);
-
- public void setFinished(boolean success);
-
- /**
- * @since 2.0
- */
- public Enum<?> waitUntilFinished(long timeout);
-
- /**
- * @author Eike Stepper
- */
- public interface Receiver
- {
- public void receiveBuffer(INegotiationContext context, ByteBuffer buffer);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import java.nio.ByteBuffer; + +/** + * @author Eike Stepper + */ +public interface INegotiationContext +{ + /** + * @since 2.0 + */ + public static final int NO_TIMEOUT = -1; + + public ByteBuffer getBuffer(); + + public void transmitBuffer(ByteBuffer buffer); + + public Receiver getReceiver(); + + public void setReceiver(Receiver receiver); + + public Enum<?> getState(); + + public void setState(Enum<?> state); + + public void setUserID(String userID); + + public Object getInfo(); + + public void setInfo(Object info); + + public void setFinished(boolean success); + + /** + * @since 2.0 + */ + public Enum<?> waitUntilFinished(long timeout); + + /** + * @author Eike Stepper + */ + public interface Receiver + { + public void receiveBuffer(INegotiationContext context, ByteBuffer buffer); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java index 2005589fac..416dc223b8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiator.java @@ -1,24 +1,24 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface INegotiator
-{
- /**
- * @since 2.0
- */
- public boolean isInitiator();
-
- public void negotiate(INegotiationContext context);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface INegotiator +{ + /** + * @since 2.0 + */ + public boolean isInitiator(); + + public void negotiate(INegotiationContext context); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java index 4c6f0df6d5..82f164ac48 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/INegotiatorAware.java @@ -1,22 +1,22 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface INegotiatorAware
-{
- public INegotiator getNegotiator();
-
- public void setNegotiator(INegotiator negotiator);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface INegotiatorAware +{ + public INegotiator getNegotiator(); + + public void setNegotiator(INegotiator negotiator); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java index 952f9b7901..0e639b8174 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentials.java @@ -1,19 +1,19 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface IPasswordCredentials extends ICredentials
-{
- public char[] getPassword();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface IPasswordCredentials extends ICredentials +{ + public char[] getPassword(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java index 42b92466cb..e8957462ca 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IPasswordCredentialsProvider.java @@ -1,19 +1,19 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface IPasswordCredentialsProvider extends ICredentialsProvider
-{
- public IPasswordCredentials getCredentials();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface IPasswordCredentialsProvider extends ICredentialsProvider +{ + public IPasswordCredentials getCredentials(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java index 1883d7d7b1..59abe8c857 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IRandomizer.java @@ -1,37 +1,37 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface IRandomizer
-{
- public byte[] generateSeed(int numBytes);
-
- public boolean nextBoolean();
-
- public double nextDouble();
-
- public float nextFloat();
-
- public double nextGaussian();
-
- public int nextInt();
-
- public int nextInt(int n);
-
- public long nextLong();
-
- public void nextBytes(byte[] bytes);
-
- public String nextString(int length, String alphabet);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface IRandomizer +{ + public byte[] generateSeed(int numBytes); + + public boolean nextBoolean(); + + public double nextDouble(); + + public float nextFloat(); + + public double nextGaussian(); + + public int nextInt(); + + public int nextInt(int n); + + public long nextLong(); + + public void nextBytes(byte[] bytes); + + public String nextString(int length, String alphabet); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java index c2c68a11e2..0e4953a274 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserAware.java @@ -1,20 +1,20 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public interface IUserAware
-{
- public String getUserID();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public interface IUserAware +{ + public String getUserID(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java index 8f7148c996..cf10d1c19d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/IUserManager.java @@ -1,27 +1,27 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public interface IUserManager
-{
- public void addUser(String userID, char[] password);
-
- public void removeUser(String userID);
-
- /**
- * @since 2.0
- */
- public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count)
- throws SecurityException;
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public interface IUserManager +{ + public void addUser(String userID, char[] password); + + public void removeUser(String userID); + + /** + * @since 2.0 + */ + public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count) + throws SecurityException; +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java index 235a5942eb..dd9610206e 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationContext.java @@ -1,102 +1,102 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.WrappedException;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-/**
- * @author Eike Stepper
- */
-public abstract class NegotiationContext implements INegotiationContext
-{
- private Receiver receiver;
-
- private Enum<?> state;
-
- private Object info;
-
- private CountDownLatch finishedLatch = new CountDownLatch(1);
-
- public NegotiationContext()
- {
- }
-
- public Receiver getReceiver()
- {
- return receiver;
- }
-
- public void setReceiver(Receiver receiver)
- {
- this.receiver = receiver;
- }
-
- public Enum<?> getState()
- {
- return state;
- }
-
- public void setState(Enum<?> state)
- {
- this.state = state;
- }
-
- public Object getInfo()
- {
- return info;
- }
-
- public void setInfo(Object info)
- {
- this.info = info;
- }
-
- public void setFinished(boolean success)
- {
- if (finishedLatch != null)
- {
- finishedLatch.countDown();
- }
- }
-
- public Enum<?> waitUntilFinished(long timeout)
- {
- if (finishedLatch == null)
- {
- throw new IllegalStateException("finishedLatch == null"); //$NON-NLS-1$
- }
-
- try
- {
- if (timeout == NO_TIMEOUT)
- {
- finishedLatch.await();
- }
- else
- {
- finishedLatch.await(timeout, TimeUnit.MILLISECONDS);
- }
- }
- catch (InterruptedException ex)
- {
- throw WrappedException.wrap(ex);
- }
- finally
- {
- finishedLatch = null;
- }
-
- return state;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.WrappedException; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * @author Eike Stepper + */ +public abstract class NegotiationContext implements INegotiationContext +{ + private Receiver receiver; + + private Enum<?> state; + + private Object info; + + private CountDownLatch finishedLatch = new CountDownLatch(1); + + public NegotiationContext() + { + } + + public Receiver getReceiver() + { + return receiver; + } + + public void setReceiver(Receiver receiver) + { + this.receiver = receiver; + } + + public Enum<?> getState() + { + return state; + } + + public void setState(Enum<?> state) + { + this.state = state; + } + + public Object getInfo() + { + return info; + } + + public void setInfo(Object info) + { + this.info = info; + } + + public void setFinished(boolean success) + { + if (finishedLatch != null) + { + finishedLatch.countDown(); + } + } + + public Enum<?> waitUntilFinished(long timeout) + { + if (finishedLatch == null) + { + throw new IllegalStateException("finishedLatch == null"); //$NON-NLS-1$ + } + + try + { + if (timeout == NO_TIMEOUT) + { + finishedLatch.await(); + } + else + { + finishedLatch.await(timeout, TimeUnit.MILLISECONDS); + } + } + catch (InterruptedException ex) + { + throw WrappedException.wrap(ex); + } + finally + { + finishedLatch = null; + } + + return state; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java index 2fb8901411..2cc906fce7 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiationException.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public class NegotiationException extends SecurityException
-{
- private static final long serialVersionUID = 1L;
-
- public NegotiationException()
- {
- }
-
- public NegotiationException(String s)
- {
- super(s);
- }
-
- public NegotiationException(Throwable cause)
- {
- super(cause);
- }
-
- public NegotiationException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public class NegotiationException extends SecurityException +{ + private static final long serialVersionUID = 1L; + + public NegotiationException() + { + } + + public NegotiationException(String s) + { + super(s); + } + + public NegotiationException(Throwable cause) + { + super(cause); + } + + public NegotiationException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java index e10d2efb1f..2a76a24a80 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Negotiator.java @@ -1,147 +1,147 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.fsm.FiniteStateMachine;
-
-import java.nio.ByteBuffer;
-
-/**
- * @author Eike Stepper
- */
-public abstract class Negotiator<STATE extends Enum<?>, EVENT extends Enum<?>> extends
- FiniteStateMachine<STATE, EVENT, INegotiationContext> implements INegotiator, INegotiationContext.Receiver
-{
- private transient STATE initialState;
-
- private transient STATE successState;
-
- private transient STATE failureState;
-
- private transient EVENT startEvent;
-
- private transient EVENT bufferEvent;
-
- private boolean initiator;
-
- public Negotiator(Class<STATE> stateEnum, Class<EVENT> eventEnum, STATE initialState, STATE successState,
- STATE failureState, EVENT startEvent, EVENT bufferEvent, boolean initiator)
- {
- super(stateEnum, eventEnum);
- if (initialState == null)
- {
- throw new IllegalStateException("initialState == null"); //$NON-NLS-1$
- }
-
- if (successState == null)
- {
- throw new IllegalStateException("successState == null"); //$NON-NLS-1$
- }
-
- if (failureState == null)
- {
- throw new IllegalStateException("failureState == null"); //$NON-NLS-1$
- }
-
- if (startEvent == null)
- {
- throw new IllegalStateException("startEvent == null"); //$NON-NLS-1$
- }
-
- if (bufferEvent == null)
- {
- throw new IllegalStateException("bufferEvent == null"); //$NON-NLS-1$
- }
-
- this.initialState = initialState;
- this.successState = successState;
- this.failureState = failureState;
- this.startEvent = startEvent;
- this.bufferEvent = bufferEvent;
- this.initiator = initiator;
- }
-
- public STATE getInitialState()
- {
- return initialState;
- }
-
- public STATE getSuccessState()
- {
- return successState;
- }
-
- public STATE getFailureState()
- {
- return failureState;
- }
-
- public EVENT getBufferEvent()
- {
- return bufferEvent;
- }
-
- public EVENT getStartEvent()
- {
- return startEvent;
- }
-
- public boolean isInitiator()
- {
- return initiator;
- }
-
- public void negotiate(INegotiationContext context)
- {
- context.setReceiver(this);
- context.setState(initialState);
- if (initiator)
- {
- process(context, startEvent, null);
- postProcess(context);
- }
- }
-
- public void receiveBuffer(INegotiationContext context, ByteBuffer buffer)
- {
- process(context, bufferEvent, buffer);
- postProcess(context);
- }
-
- protected void postProcess(INegotiationContext context)
- {
- Enum<?> state = context.getState();
- if (state == successState)
- {
- handleSuccess(context);
- }
- else if (state == failureState)
- {
- handleFailure(context);
- }
- }
-
- /**
- * @since 2.0
- */
- protected void handleSuccess(INegotiationContext context)
- {
- context.setFinished(true);
- }
-
- /**
- * @since 2.0
- */
- protected void handleFailure(INegotiationContext context)
- {
- context.setFinished(false);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.fsm.FiniteStateMachine; + +import java.nio.ByteBuffer; + +/** + * @author Eike Stepper + */ +public abstract class Negotiator<STATE extends Enum<?>, EVENT extends Enum<?>> extends + FiniteStateMachine<STATE, EVENT, INegotiationContext> implements INegotiator, INegotiationContext.Receiver +{ + private transient STATE initialState; + + private transient STATE successState; + + private transient STATE failureState; + + private transient EVENT startEvent; + + private transient EVENT bufferEvent; + + private boolean initiator; + + public Negotiator(Class<STATE> stateEnum, Class<EVENT> eventEnum, STATE initialState, STATE successState, + STATE failureState, EVENT startEvent, EVENT bufferEvent, boolean initiator) + { + super(stateEnum, eventEnum); + if (initialState == null) + { + throw new IllegalStateException("initialState == null"); //$NON-NLS-1$ + } + + if (successState == null) + { + throw new IllegalStateException("successState == null"); //$NON-NLS-1$ + } + + if (failureState == null) + { + throw new IllegalStateException("failureState == null"); //$NON-NLS-1$ + } + + if (startEvent == null) + { + throw new IllegalStateException("startEvent == null"); //$NON-NLS-1$ + } + + if (bufferEvent == null) + { + throw new IllegalStateException("bufferEvent == null"); //$NON-NLS-1$ + } + + this.initialState = initialState; + this.successState = successState; + this.failureState = failureState; + this.startEvent = startEvent; + this.bufferEvent = bufferEvent; + this.initiator = initiator; + } + + public STATE getInitialState() + { + return initialState; + } + + public STATE getSuccessState() + { + return successState; + } + + public STATE getFailureState() + { + return failureState; + } + + public EVENT getBufferEvent() + { + return bufferEvent; + } + + public EVENT getStartEvent() + { + return startEvent; + } + + public boolean isInitiator() + { + return initiator; + } + + public void negotiate(INegotiationContext context) + { + context.setReceiver(this); + context.setState(initialState); + if (initiator) + { + process(context, startEvent, null); + postProcess(context); + } + } + + public void receiveBuffer(INegotiationContext context, ByteBuffer buffer) + { + process(context, bufferEvent, buffer); + postProcess(context); + } + + protected void postProcess(INegotiationContext context) + { + Enum<?> state = context.getState(); + if (state == successState) + { + handleSuccess(context); + } + else if (state == failureState) + { + handleFailure(context); + } + } + + /** + * @since 2.0 + */ + protected void handleSuccess(INegotiationContext context) + { + context.setFinished(true); + } + + /** + * @since 2.0 + */ + protected void handleFailure(INegotiationContext context) + { + context.setFinished(false); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java index c9c2c4851f..a9d73e787d 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/NegotiatorFactory.java @@ -1,26 +1,26 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.factory.Factory;
-
-/**
- * @author Eike Stepper
- */
-public abstract class NegotiatorFactory extends Factory
-{
- public static final String PRODUCT_GROUP = "org.eclipse.net4j.Negotiators"; //$NON-NLS-1$
-
- public NegotiatorFactory(String type)
- {
- super(PRODUCT_GROUP, type);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.factory.Factory; + +/** + * @author Eike Stepper + */ +public abstract class NegotiatorFactory extends Factory +{ + public static final String PRODUCT_GROUP = "org.eclipse.net4j.Negotiators"; //$NON-NLS-1$ + + public NegotiatorFactory(String type) + { + super(PRODUCT_GROUP, type); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java index 72f80b455c..1a75c67cf0 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentials.java @@ -1,35 +1,35 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public class PasswordCredentials extends Credentials implements IPasswordCredentials
-{
- private char[] password;
-
- public PasswordCredentials(String userID, char[] password)
- {
- super(userID);
- this.password = password;
- }
-
- public char[] getPassword()
- {
- return password;
- }
-
- public void setPassword(char[] password)
- {
- this.password = password;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public class PasswordCredentials extends Credentials implements IPasswordCredentials +{ + private char[] password; + + public PasswordCredentials(String userID, char[] password) + { + super(userID); + this.password = password; + } + + public char[] getPassword() + { + return password; + } + + public void setPassword(char[] password) + { + this.password = password; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java index 1dac8f502a..c848776640 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/PasswordCredentialsProvider.java @@ -1,103 +1,103 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public class PasswordCredentialsProvider implements IPasswordCredentialsProvider
-{
- private IPasswordCredentials credentials;
-
- /**
- * @since 3.1
- */
- public PasswordCredentialsProvider()
- {
- }
-
- public PasswordCredentialsProvider(IPasswordCredentials credentials)
- {
- this.credentials = credentials;
- }
-
- /**
- * @since 2.0
- */
- public PasswordCredentialsProvider(String userID, char[] password)
- {
- this(new PasswordCredentials(userID, password));
- }
-
- /**
- * @since 2.0
- */
- public PasswordCredentialsProvider(String userID, String password)
- {
- this(userID, password.toCharArray());
- }
-
- public boolean isInteractive()
- {
- return false;
- }
-
- public IPasswordCredentials getCredentials()
- {
- return credentials;
- }
-
- /**
- * @since 3.1
- */
- public void setCredentials(IPasswordCredentials credentials)
- {
- this.credentials = credentials;
- }
-
- /**
- * @author Eike Stepper
- * @since 3.1
- */
- public static class Delegating extends PasswordCredentialsProvider
- {
- private IPasswordCredentialsProvider delegate;
-
- public Delegating(IPasswordCredentialsProvider delegate)
- {
- this.delegate = delegate;
- }
-
- public IPasswordCredentialsProvider getDelegate()
- {
- return delegate;
- }
-
- @Override
- public boolean isInteractive()
- {
- return delegate.isInteractive();
- }
-
- @Override
- public IPasswordCredentials getCredentials()
- {
- IPasswordCredentials credentials = super.getCredentials();
- if (credentials == null)
- {
- credentials = delegate.getCredentials();
- setCredentials(credentials);
- }
-
- return credentials;
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public class PasswordCredentialsProvider implements IPasswordCredentialsProvider +{ + private IPasswordCredentials credentials; + + /** + * @since 3.1 + */ + public PasswordCredentialsProvider() + { + } + + public PasswordCredentialsProvider(IPasswordCredentials credentials) + { + this.credentials = credentials; + } + + /** + * @since 2.0 + */ + public PasswordCredentialsProvider(String userID, char[] password) + { + this(new PasswordCredentials(userID, password)); + } + + /** + * @since 2.0 + */ + public PasswordCredentialsProvider(String userID, String password) + { + this(userID, password.toCharArray()); + } + + public boolean isInteractive() + { + return false; + } + + public IPasswordCredentials getCredentials() + { + return credentials; + } + + /** + * @since 3.1 + */ + public void setCredentials(IPasswordCredentials credentials) + { + this.credentials = credentials; + } + + /** + * @author Eike Stepper + * @since 3.1 + */ + public static class Delegating extends PasswordCredentialsProvider + { + private IPasswordCredentialsProvider delegate; + + public Delegating(IPasswordCredentialsProvider delegate) + { + this.delegate = delegate; + } + + public IPasswordCredentialsProvider getDelegate() + { + return delegate; + } + + @Override + public boolean isInteractive() + { + return delegate.isInteractive(); + } + + @Override + public IPasswordCredentials getCredentials() + { + IPasswordCredentials credentials = super.getCredentials(); + if (credentials == null) + { + credentials = delegate.getCredentials(); + setCredentials(credentials); + } + + return credentials; + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java index f38b48e041..72fb761117 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/Randomizer.java @@ -1,188 +1,188 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-
-import java.security.SecureRandom;
-
-/**
- * @author Eike Stepper
- */
-public class Randomizer extends Lifecycle implements IRandomizer
-{
- public static final String ALGORITHM_SHA1PRNG = "SHA1PRNG"; //$NON-NLS-1$
-
- public static final String DEFAULT_ALGORITHM_NAME = ALGORITHM_SHA1PRNG;
-
- private String algorithmName = DEFAULT_ALGORITHM_NAME;
-
- private String providerName;
-
- @ExcludeFromDump
- private byte[] seed;
-
- @ExcludeFromDump
- private transient SecureRandom secureRandom;
-
- public Randomizer()
- {
- }
-
- public synchronized String getAlgorithmName()
- {
- return algorithmName;
- }
-
- public synchronized void setAlgorithmName(String algorithmName)
- {
- this.algorithmName = algorithmName;
- }
-
- public synchronized String getProviderName()
- {
- return providerName;
- }
-
- public synchronized void setProviderName(String providerName)
- {
- this.providerName = providerName;
- }
-
- public synchronized void setSeed(byte[] seed)
- {
- this.seed = seed;
- if (isActive())
- {
- setSeed();
- }
- }
-
- public synchronized void setSeed(long seed)
- {
- setSeed(String.valueOf(seed).getBytes());
- }
-
- public synchronized boolean nextBoolean()
- {
- checkActive();
- return secureRandom.nextBoolean();
- }
-
- public synchronized double nextDouble()
- {
- checkActive();
- return secureRandom.nextDouble();
- }
-
- public synchronized float nextFloat()
- {
- checkActive();
- return secureRandom.nextFloat();
- }
-
- public synchronized double nextGaussian()
- {
- checkActive();
- return secureRandom.nextGaussian();
- }
-
- public synchronized int nextInt()
- {
- checkActive();
- return secureRandom.nextInt();
- }
-
- public synchronized int nextInt(int n)
- {
- checkActive();
- return secureRandom.nextInt(n);
- }
-
- public synchronized long nextLong()
- {
- checkActive();
- return secureRandom.nextLong();
- }
-
- public synchronized byte[] generateSeed(int numBytes)
- {
- checkActive();
- return secureRandom.generateSeed(numBytes);
- }
-
- public synchronized String getAlgorithm()
- {
- checkActive();
- return secureRandom.getAlgorithm();
- }
-
- public synchronized void nextBytes(byte[] bytes)
- {
- checkActive();
- secureRandom.nextBytes(bytes);
- }
-
- public synchronized String nextString(int length, String alphabet)
- {
- checkActive();
- int n = alphabet.length();
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < length; i++)
- {
- int pos = nextInt(n);
- char c = alphabet.charAt(pos);
- builder.append(c);
- }
-
- return builder.toString();
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- checkState(algorithmName, "algorithmName"); //$NON-NLS-1$
- if (seed == null)
- {
- setSeed(System.currentTimeMillis());
- }
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- if (providerName == null)
- {
- secureRandom = SecureRandom.getInstance(algorithmName);
- }
- else
- {
- secureRandom = SecureRandom.getInstance(algorithmName, providerName);
- }
-
- setSeed();
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- secureRandom = null;
- super.doDeactivate();
- }
-
- private void setSeed()
- {
- secureRandom.setSeed(seed);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; +import org.eclipse.net4j.util.lifecycle.Lifecycle; + +import java.security.SecureRandom; + +/** + * @author Eike Stepper + */ +public class Randomizer extends Lifecycle implements IRandomizer +{ + public static final String ALGORITHM_SHA1PRNG = "SHA1PRNG"; //$NON-NLS-1$ + + public static final String DEFAULT_ALGORITHM_NAME = ALGORITHM_SHA1PRNG; + + private String algorithmName = DEFAULT_ALGORITHM_NAME; + + private String providerName; + + @ExcludeFromDump + private byte[] seed; + + @ExcludeFromDump + private transient SecureRandom secureRandom; + + public Randomizer() + { + } + + public synchronized String getAlgorithmName() + { + return algorithmName; + } + + public synchronized void setAlgorithmName(String algorithmName) + { + this.algorithmName = algorithmName; + } + + public synchronized String getProviderName() + { + return providerName; + } + + public synchronized void setProviderName(String providerName) + { + this.providerName = providerName; + } + + public synchronized void setSeed(byte[] seed) + { + this.seed = seed; + if (isActive()) + { + setSeed(); + } + } + + public synchronized void setSeed(long seed) + { + setSeed(String.valueOf(seed).getBytes()); + } + + public synchronized boolean nextBoolean() + { + checkActive(); + return secureRandom.nextBoolean(); + } + + public synchronized double nextDouble() + { + checkActive(); + return secureRandom.nextDouble(); + } + + public synchronized float nextFloat() + { + checkActive(); + return secureRandom.nextFloat(); + } + + public synchronized double nextGaussian() + { + checkActive(); + return secureRandom.nextGaussian(); + } + + public synchronized int nextInt() + { + checkActive(); + return secureRandom.nextInt(); + } + + public synchronized int nextInt(int n) + { + checkActive(); + return secureRandom.nextInt(n); + } + + public synchronized long nextLong() + { + checkActive(); + return secureRandom.nextLong(); + } + + public synchronized byte[] generateSeed(int numBytes) + { + checkActive(); + return secureRandom.generateSeed(numBytes); + } + + public synchronized String getAlgorithm() + { + checkActive(); + return secureRandom.getAlgorithm(); + } + + public synchronized void nextBytes(byte[] bytes) + { + checkActive(); + secureRandom.nextBytes(bytes); + } + + public synchronized String nextString(int length, String alphabet) + { + checkActive(); + int n = alphabet.length(); + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < length; i++) + { + int pos = nextInt(n); + char c = alphabet.charAt(pos); + builder.append(c); + } + + return builder.toString(); + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + checkState(algorithmName, "algorithmName"); //$NON-NLS-1$ + if (seed == null) + { + setSeed(System.currentTimeMillis()); + } + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + if (providerName == null) + { + secureRandom = SecureRandom.getInstance(algorithmName); + } + else + { + secureRandom = SecureRandom.getInstance(algorithmName, providerName); + } + + setSeed(); + } + + @Override + protected void doDeactivate() throws Exception + { + secureRandom = null; + super.doDeactivate(); + } + + private void setSeed() + { + secureRandom.setSeed(seed); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java index 0e0b806264..df38351526 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/RandomizerFactory.java @@ -1,40 +1,40 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.factory.Factory;
-import org.eclipse.net4j.util.factory.ProductCreationException;
-
-/**
- * @author Eike Stepper
- */
-public class RandomizerFactory extends Factory
-{
- public static final String PRODUCT_GROUP = "org.eclipse.net4j.randomizers"; //$NON-NLS-1$
-
- public static final String TYPE = "default"; //$NON-NLS-1$
-
- public RandomizerFactory()
- {
- super(PRODUCT_GROUP, TYPE);
- }
-
- public Randomizer create(String description) throws ProductCreationException
- {
- Randomizer randomizer = new Randomizer();
- if (description != null)
- {
- randomizer.setAlgorithmName(description);
- }
-
- return randomizer;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.factory.Factory; +import org.eclipse.net4j.util.factory.ProductCreationException; + +/** + * @author Eike Stepper + */ +public class RandomizerFactory extends Factory +{ + public static final String PRODUCT_GROUP = "org.eclipse.net4j.randomizers"; //$NON-NLS-1$ + + public static final String TYPE = "default"; //$NON-NLS-1$ + + public RandomizerFactory() + { + super(PRODUCT_GROUP, TYPE); + } + + public Randomizer create(String description) throws ProductCreationException + { + Randomizer randomizer = new Randomizer(); + if (description != null) + { + randomizer.setAlgorithmName(description); + } + + return randomizer; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java index 81eb488055..6ba1004560 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiator.java @@ -1,99 +1,99 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import java.nio.ByteBuffer;
-
-/**
- * @author Eike Stepper
- */
-public class ResponseNegotiator extends ChallengeResponseNegotiator
-{
- private IPasswordCredentialsProvider credentialsProvider;
-
- public ResponseNegotiator()
- {
- super(false);
- }
-
- public IPasswordCredentialsProvider getCredentialsProvider()
- {
- return credentialsProvider;
- }
-
- public void setCredentialsProvider(IPasswordCredentialsProvider credentialsProvider)
- {
- this.credentialsProvider = credentialsProvider;
- }
-
- @Override
- protected void doBeforeActivate() throws Exception
- {
- super.doBeforeActivate();
- if (credentialsProvider == null)
- {
- throw new IllegalStateException("credentialsProvider == null"); //$NON-NLS-1$
- }
- }
-
- @Override
- protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response)
- {
- // Get random token from challenge
- int size = challenge.getInt();
- byte[] randomToken = new byte[size];
- challenge.get(randomToken);
-
- // Get credentials and encrypt token
- IPasswordCredentials credentials = credentialsProvider.getCredentials();
- String userID = credentials.getUserID();
- context.setUserID(userID);
-
- // Set userID into response
- byte[] userIDBytes = userID.getBytes();
- response.putInt(userIDBytes.length);
- response.put(userIDBytes);
-
- // Set crypted token into response
- byte[] cryptedToken = encryptToken(credentials.getPassword(), randomToken);
- response.putInt(cryptedToken.length);
- response.put(cryptedToken);
- }
-
- /**
- * @since 2.0
- */
- @Override
- protected void handleAcknowledgement(INegotiationContext context, boolean success)
- {
- if (!success)
- {
- throw new NegotiationException("Negotiation failed"); //$NON-NLS-1$
- }
- }
-
- protected byte[] encryptToken(char[] password, byte[] token)
- {
- try
- {
- return SecurityUtil.encrypt(token, password, getEncryptionAlgorithmName(), getEncryptionSaltBytes(),
- getEncryptionIterationCount());
- }
- catch (RuntimeException ex)
- {
- throw ex;
- }
- catch (Exception ex)
- {
- throw new SecurityException(ex);
- }
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import java.nio.ByteBuffer; + +/** + * @author Eike Stepper + */ +public class ResponseNegotiator extends ChallengeResponseNegotiator +{ + private IPasswordCredentialsProvider credentialsProvider; + + public ResponseNegotiator() + { + super(false); + } + + public IPasswordCredentialsProvider getCredentialsProvider() + { + return credentialsProvider; + } + + public void setCredentialsProvider(IPasswordCredentialsProvider credentialsProvider) + { + this.credentialsProvider = credentialsProvider; + } + + @Override + protected void doBeforeActivate() throws Exception + { + super.doBeforeActivate(); + if (credentialsProvider == null) + { + throw new IllegalStateException("credentialsProvider == null"); //$NON-NLS-1$ + } + } + + @Override + protected void handleChallenge(INegotiationContext context, ByteBuffer challenge, ByteBuffer response) + { + // Get random token from challenge + int size = challenge.getInt(); + byte[] randomToken = new byte[size]; + challenge.get(randomToken); + + // Get credentials and encrypt token + IPasswordCredentials credentials = credentialsProvider.getCredentials(); + String userID = credentials.getUserID(); + context.setUserID(userID); + + // Set userID into response + byte[] userIDBytes = userID.getBytes(); + response.putInt(userIDBytes.length); + response.put(userIDBytes); + + // Set crypted token into response + byte[] cryptedToken = encryptToken(credentials.getPassword(), randomToken); + response.putInt(cryptedToken.length); + response.put(cryptedToken); + } + + /** + * @since 2.0 + */ + @Override + protected void handleAcknowledgement(INegotiationContext context, boolean success) + { + if (!success) + { + throw new NegotiationException("Negotiation failed"); //$NON-NLS-1$ + } + } + + protected byte[] encryptToken(char[] password, byte[] token) + { + try + { + return SecurityUtil.encrypt(token, password, getEncryptionAlgorithmName(), getEncryptionSaltBytes(), + getEncryptionIterationCount()); + } + catch (RuntimeException ex) + { + throw ex; + } + catch (Exception ex) + { + throw new SecurityException(ex); + } + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java index 21179215c2..b78c5de82c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorFactory.java @@ -1,29 +1,29 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-/**
- * @author Eike Stepper
- */
-public class ResponseNegotiatorFactory extends NegotiatorFactory
-{
- public static final String TYPE = "response"; //$NON-NLS-1$
-
- public ResponseNegotiatorFactory()
- {
- super(TYPE);
- }
-
- public ResponseNegotiator create(String description)
- {
- return new ResponseNegotiator();
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +/** + * @author Eike Stepper + */ +public class ResponseNegotiatorFactory extends NegotiatorFactory +{ + public static final String TYPE = "response"; //$NON-NLS-1$ + + public ResponseNegotiatorFactory() + { + super(TYPE); + } + + public ResponseNegotiator create(String description) + { + return new ResponseNegotiator(); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java index 163b4e9f0d..ccad86262c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/ResponseNegotiatorInjector.java @@ -1,57 +1,57 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.container.IElementProcessor;
-import org.eclipse.net4j.util.container.IManagedContainer;
-
-/**
- * @author Eike Stepper
- * @since 2.0
- */
-public abstract class ResponseNegotiatorInjector implements IElementProcessor
-{
- private INegotiator negotiator;
-
- public ResponseNegotiatorInjector(INegotiator negotiator)
- {
- this.negotiator = negotiator;
- }
-
- public INegotiator getNegotiator()
- {
- return negotiator;
- }
-
- public Object process(IManagedContainer container, String productGroup, String factoryType, String description,
- Object element)
- {
- if (element instanceof INegotiatorAware)
- {
- INegotiatorAware negotiatorAware = (INegotiatorAware)element;
- if (negotiatorAware.getNegotiator() == null)
- {
- if (filterElement(productGroup, factoryType, description, negotiatorAware))
- {
- if (negotiator != null)
- {
- negotiatorAware.setNegotiator(negotiator);
- }
- }
- }
- }
-
- return element;
- }
-
- protected abstract boolean filterElement(String productGroup, String factoryType, String description,
- INegotiatorAware negotiatorAware);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.container.IElementProcessor; +import org.eclipse.net4j.util.container.IManagedContainer; + +/** + * @author Eike Stepper + * @since 2.0 + */ +public abstract class ResponseNegotiatorInjector implements IElementProcessor +{ + private INegotiator negotiator; + + public ResponseNegotiatorInjector(INegotiator negotiator) + { + this.negotiator = negotiator; + } + + public INegotiator getNegotiator() + { + return negotiator; + } + + public Object process(IManagedContainer container, String productGroup, String factoryType, String description, + Object element) + { + if (element instanceof INegotiatorAware) + { + INegotiatorAware negotiatorAware = (INegotiatorAware)element; + if (negotiatorAware.getNegotiator() == null) + { + if (filterElement(productGroup, factoryType, description, negotiatorAware)) + { + if (negotiator != null) + { + negotiatorAware.setNegotiator(negotiator); + } + } + } + } + + return element; + } + + protected abstract boolean filterElement(String productGroup, String factoryType, String description, + INegotiatorAware negotiatorAware); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java index cb9fdbf74e..7ee484a5d5 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/SecurityUtil.java @@ -1,70 +1,70 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.SecretKey;
-import javax.crypto.SecretKeyFactory;
-import javax.crypto.spec.PBEKeySpec;
-import javax.crypto.spec.PBEParameterSpec;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.spec.InvalidKeySpecException;
-
-/**
- * @author Eike Stepper
- */
-public final class SecurityUtil
-{
- public static final String PBE_WITH_MD5_AND_DES = "PBEWithMD5AndDES"; //$NON-NLS-1$
-
- /**
- * @since 2.0
- */
- public static final byte[] DEFAULT_SALT = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8,
- (byte)0xee, (byte)0x99 };
-
- /**
- * @since 2.0
- */
- public static final int DEFAULT_ITERATION_COUNT = 20;
-
- private SecurityUtil()
- {
- }
-
- /**
- * @since 2.0
- */
- public static byte[] encrypt(byte[] data, char[] password, String algorithmName, byte[] salt, int count)
- throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
- InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
- {
- // Create PBE parameter set
- PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
- PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
- SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithmName);
- SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
-
- // Create PBE Cipher
- Cipher pbeCipher = Cipher.getInstance(algorithmName);
-
- // Initialize PBE Cipher with key and parameters
- pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
-
- return pbeCipher.doFinal(data);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.PBEParameterSpec; + +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; + +/** + * @author Eike Stepper + */ +public final class SecurityUtil +{ + public static final String PBE_WITH_MD5_AND_DES = "PBEWithMD5AndDES"; //$NON-NLS-1$ + + /** + * @since 2.0 + */ + public static final byte[] DEFAULT_SALT = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, + (byte)0xee, (byte)0x99 }; + + /** + * @since 2.0 + */ + public static final int DEFAULT_ITERATION_COUNT = 20; + + private SecurityUtil() + { + } + + /** + * @since 2.0 + */ + public static byte[] encrypt(byte[] data, char[] password, String algorithmName, byte[] salt, int count) + throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, + InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException + { + // Create PBE parameter set + PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count); + PBEKeySpec pbeKeySpec = new PBEKeySpec(password); + SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithmName); + SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); + + // Create PBE Cipher + Cipher pbeCipher = Cipher.getInstance(algorithmName); + + // Initialize PBE Cipher with key and parameters + pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); + + return pbeCipher.doFinal(data); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java index fe9b29e469..03d8752097 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManager.java @@ -1,98 +1,98 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump;
-import org.eclipse.net4j.util.io.IORuntimeException;
-import org.eclipse.net4j.util.lifecycle.Lifecycle;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Eike Stepper
- */
-public class UserManager extends Lifecycle implements IUserManager
-{
- @ExcludeFromDump
- protected transient Map<String, char[]> users = new HashMap<String, char[]>();
-
- public UserManager()
- {
- }
-
- public synchronized void addUser(String userID, char[] password)
- {
- users.put(userID, password);
- save(users);
- }
-
- public synchronized void removeUser(String userID)
- {
- if (users.remove(userID) != null)
- {
- save(users);
- }
- }
-
- /**
- * @since 2.0
- */
- public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count)
- throws SecurityException
- {
- char[] password;
- synchronized (this)
- {
- password = users.get(userID);
- }
-
- if (password == null)
- {
- throw new SecurityException("No such user: " + userID); //$NON-NLS-1$
- }
-
- try
- {
- return SecurityUtil.encrypt(data, password, algorithmName, salt, count);
- }
- catch (RuntimeException ex)
- {
- throw ex;
- }
- catch (Exception ex)
- {
- throw new SecurityException(ex);
- }
- }
-
- @Override
- protected void doActivate() throws Exception
- {
- super.doActivate();
- load(users);
- }
-
- @Override
- protected void doDeactivate() throws Exception
- {
- users.clear();
- super.doDeactivate();
- }
-
- protected void load(Map<String, char[]> users) throws IORuntimeException
- {
- }
-
- protected void save(Map<String, char[]> users) throws IORuntimeException
- {
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.ReflectUtil.ExcludeFromDump; +import org.eclipse.net4j.util.io.IORuntimeException; +import org.eclipse.net4j.util.lifecycle.Lifecycle; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Eike Stepper + */ +public class UserManager extends Lifecycle implements IUserManager +{ + @ExcludeFromDump + protected transient Map<String, char[]> users = new HashMap<String, char[]>(); + + public UserManager() + { + } + + public synchronized void addUser(String userID, char[] password) + { + users.put(userID, password); + save(users); + } + + public synchronized void removeUser(String userID) + { + if (users.remove(userID) != null) + { + save(users); + } + } + + /** + * @since 2.0 + */ + public byte[] encrypt(String userID, byte[] data, String algorithmName, byte[] salt, int count) + throws SecurityException + { + char[] password; + synchronized (this) + { + password = users.get(userID); + } + + if (password == null) + { + throw new SecurityException("No such user: " + userID); //$NON-NLS-1$ + } + + try + { + return SecurityUtil.encrypt(data, password, algorithmName, salt, count); + } + catch (RuntimeException ex) + { + throw ex; + } + catch (Exception ex) + { + throw new SecurityException(ex); + } + } + + @Override + protected void doActivate() throws Exception + { + super.doActivate(); + load(users); + } + + @Override + protected void doDeactivate() throws Exception + { + users.clear(); + super.doDeactivate(); + } + + protected void load(Map<String, char[]> users) throws IORuntimeException + { + } + + protected void save(Map<String, char[]> users) throws IORuntimeException + { + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java index 414d1ed3c6..5b03f1f1e6 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/UserManagerFactory.java @@ -1,26 +1,26 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.security;
-
-import org.eclipse.net4j.util.factory.Factory;
-
-/**
- * @author Eike Stepper
- */
-public abstract class UserManagerFactory extends Factory
-{
- public static final String PRODUCT_GROUP = "org.eclipse.net4j.userManagers"; //$NON-NLS-1$
-
- public UserManagerFactory(String type)
- {
- super(PRODUCT_GROUP, type);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.security; + +import org.eclipse.net4j.util.factory.Factory; + +/** + * @author Eike Stepper + */ +public abstract class UserManagerFactory extends Factory +{ + public static final String PRODUCT_GROUP = "org.eclipse.net4j.userManagers"; //$NON-NLS-1$ + + public UserManagerFactory(String type) + { + super(PRODUCT_GROUP, type); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java index 5a1ca1cf9f..e9a0460aa9 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/security/package-info.java @@ -1,17 +1,17 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * Interfaces and classes for security, negotiation, authentication, authorization and cryptography.
- * @apiviz.exclude .*
- */
-package org.eclipse.net4j.util.security;
-
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * Interfaces and classes for security, negotiation, authentication, authorization and cryptography. + * @apiviz.exclude .* + */ +package org.eclipse.net4j.util.security; + diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java index 5b707b97d4..8358688265 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransaction.java @@ -1,27 +1,27 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.transaction;
-
-/**
- * @author Eike Stepper
- */
-public interface ITransaction<CONTEXT>
-{
- public boolean isActive();
-
- public CONTEXT getContext();
-
- public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException;
-
- public void commit();
-
- public void rollback();
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.transaction; + +/** + * @author Eike Stepper + */ +public interface ITransaction<CONTEXT> +{ + public boolean isActive(); + + public CONTEXT getContext(); + + public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException; + + public void commit(); + + public void rollback(); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java index 229a8b53ed..e24a58b5c3 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/ITransactionalOperation.java @@ -1,23 +1,23 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.transaction;
-
-/**
- * @author Eike Stepper
- */
-public interface ITransactionalOperation<CONTEXT>
-{
- public void phase1(CONTEXT context) throws Exception;
-
- public void phase2(CONTEXT context);
-
- public void undoPhase1(CONTEXT context);
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.transaction; + +/** + * @author Eike Stepper + */ +public interface ITransactionalOperation<CONTEXT> +{ + public void phase1(CONTEXT context) throws Exception; + + public void phase2(CONTEXT context); + + public void undoPhase1(CONTEXT context); +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java index cef3e57673..e373dc1654 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/Transaction.java @@ -1,102 +1,102 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.transaction;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Eike Stepper
- */
-public class Transaction<CONTEXT> implements ITransaction<CONTEXT>
-{
- private List<ITransactionalOperation<CONTEXT>> operations = new ArrayList<ITransactionalOperation<CONTEXT>>();
-
- private CONTEXT context;
-
- private boolean undoPhase1OnRollback;
-
- public Transaction(CONTEXT context, boolean undoPhase1OnRollback)
- {
- this.context = context;
- this.undoPhase1OnRollback = undoPhase1OnRollback;
- }
-
- public Transaction(CONTEXT context)
- {
- this(context, true);
- }
-
- public boolean isUndoPhase1OnRollback()
- {
- return undoPhase1OnRollback;
- }
-
- public boolean isActive()
- {
- return operations != null;
- }
-
- public CONTEXT getContext()
- {
- return context;
- }
-
- public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException
- {
- if (!isActive())
- {
- throw new TransactionException("Transaction inactive"); //$NON-NLS-1$
- }
-
- try
- {
- operation.phase1(context);
- operations.add(operation);
- }
- catch (RuntimeException ex)
- {
- rollback();
- throw ex;
- }
- catch (Exception ex)
- {
- rollback();
- throw new TransactionException(ex);
- }
- }
-
- public void commit()
- {
- for (ITransactionalOperation<CONTEXT> operation : end())
- {
- operation.phase2(context);
- }
- }
-
- public void rollback()
- {
- if (undoPhase1OnRollback)
- {
- for (ITransactionalOperation<CONTEXT> operation : end())
- {
- operation.undoPhase1(context);
- }
- }
- }
-
- private List<ITransactionalOperation<CONTEXT>> end()
- {
- List<ITransactionalOperation<CONTEXT>> tmp = operations;
- operations = null;
- return tmp;
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.transaction; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Eike Stepper + */ +public class Transaction<CONTEXT> implements ITransaction<CONTEXT> +{ + private List<ITransactionalOperation<CONTEXT>> operations = new ArrayList<ITransactionalOperation<CONTEXT>>(); + + private CONTEXT context; + + private boolean undoPhase1OnRollback; + + public Transaction(CONTEXT context, boolean undoPhase1OnRollback) + { + this.context = context; + this.undoPhase1OnRollback = undoPhase1OnRollback; + } + + public Transaction(CONTEXT context) + { + this(context, true); + } + + public boolean isUndoPhase1OnRollback() + { + return undoPhase1OnRollback; + } + + public boolean isActive() + { + return operations != null; + } + + public CONTEXT getContext() + { + return context; + } + + public void execute(ITransactionalOperation<CONTEXT> operation) throws TransactionException + { + if (!isActive()) + { + throw new TransactionException("Transaction inactive"); //$NON-NLS-1$ + } + + try + { + operation.phase1(context); + operations.add(operation); + } + catch (RuntimeException ex) + { + rollback(); + throw ex; + } + catch (Exception ex) + { + rollback(); + throw new TransactionException(ex); + } + } + + public void commit() + { + for (ITransactionalOperation<CONTEXT> operation : end()) + { + operation.phase2(context); + } + } + + public void rollback() + { + if (undoPhase1OnRollback) + { + for (ITransactionalOperation<CONTEXT> operation : end()) + { + operation.undoPhase1(context); + } + } + } + + private List<ITransactionalOperation<CONTEXT>> end() + { + List<ITransactionalOperation<CONTEXT>> tmp = operations; + operations = null; + return tmp; + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java index b7cf022c97..128f0e74b1 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionException.java @@ -1,39 +1,39 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.transaction;
-
-/**
- * @author Eike Stepper
- * @noextend This interface is not intended to be extended by clients.
- */
-public class TransactionException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- public TransactionException()
- {
- }
-
- public TransactionException(String message)
- {
- super(message);
- }
-
- public TransactionException(Throwable cause)
- {
- super(cause);
- }
-
- public TransactionException(String message, Throwable cause)
- {
- super(message, cause);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.transaction; + +/** + * @author Eike Stepper + * @noextend This interface is not intended to be extended by clients. + */ +public class TransactionException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public TransactionException() + { + } + + public TransactionException(String message) + { + super(message); + } + + public TransactionException(Throwable cause) + { + super(cause); + } + + public TransactionException(String message, Throwable cause) + { + super(message, cause); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java index 49335c3401..9ba302473c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/TransactionUtil.java @@ -1,26 +1,26 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-package org.eclipse.net4j.util.transaction;
-
-/**
- * @author Eike Stepper
- */
-public final class TransactionUtil
-{
- private TransactionUtil()
- {
- }
-
- public static <CONTEXT> ITransaction<CONTEXT> createTransaction(CONTEXT context)
- {
- return new Transaction<CONTEXT>(context);
- }
-}
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ +package org.eclipse.net4j.util.transaction; + +/** + * @author Eike Stepper + */ +public final class TransactionUtil +{ + private TransactionUtil() + { + } + + public static <CONTEXT> ITransaction<CONTEXT> createTransaction(CONTEXT context) + { + return new Transaction<CONTEXT>(context); + } +} diff --git a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java index e9bedd31a0..f42ca7a2a8 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/transaction/package-info.java @@ -1,15 +1,15 @@ -/*
- * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Eike Stepper - initial API and implementation
- */
-
-/**
- * A framework for transactional operations.
- */
-package org.eclipse.net4j.util.transaction;
+/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Eike Stepper - initial API and implementation + */ + +/** + * A framework for transactional operations. + */ +package org.eclipse.net4j.util.transaction; |