From 0266166cb9ff9535c150250073ea1e57b42d2693 Mon Sep 17 00:00:00 2001 From: Eike Stepper Date: Sat, 14 Jan 2012 11:27:01 +0100 Subject: Adjusted copyrights to 2012 --- .../.settings/org.eclipse.jdt.ui.prefs | 240 +-- plugins/org.eclipse.net4j.util/build.properties | 50 +- plugins/org.eclipse.net4j.util/copyright.txt | 14 +- plugins/org.eclipse.net4j.util/plugin.properties | 26 +- plugins/org.eclipse.net4j.util/plugin.xml | 78 +- .../schema/elementProcessors.exsd | 212 +-- .../org.eclipse.net4j.util/schema/factories.exsd | 250 +-- .../net4j/internal/util/bundle/AbstractBundle.java | 912 +++++----- .../internal/util/bundle/AbstractPlatform.java | 760 ++++---- .../org/eclipse/net4j/internal/util/bundle/OM.java | 210 +-- .../internal/util/container/PluginContainer.java | 154 +- .../util/container/PluginElementProcessorList.java | 506 +++--- .../util/factory/PluginFactoryRegistry.java | 254 +-- .../net4j/internal/util/om/LegacyBundle.java | 686 ++++---- .../net4j/internal/util/om/LegacyPlatform.java | 116 +- .../eclipse/net4j/internal/util/om/OSGiBundle.java | 232 +-- .../net4j/internal/util/om/OSGiPlatform.java | 218 +-- .../internal/util/om/pref/ArrayPreference.java | 190 +- .../internal/util/om/pref/BooleanPreference.java | 78 +- .../internal/util/om/pref/BytesPreference.java | 82 +- .../internal/util/om/pref/DoublePreference.java | 78 +- .../internal/util/om/pref/FloatPreference.java | 78 +- .../internal/util/om/pref/IntegerPreference.java | 78 +- .../internal/util/om/pref/LongPreference.java | 78 +- .../net4j/internal/util/om/pref/Preference.java | 242 +-- .../net4j/internal/util/om/pref/Preferences.java | 594 +++---- .../util/om/pref/PreferencesChangeEvent.java | 114 +- .../internal/util/om/pref/StringPreference.java | 78 +- .../src/org/eclipse/net4j/util/AdapterUtil.java | 190 +- .../src/org/eclipse/net4j/util/CheckUtil.java | 128 +- .../src/org/eclipse/net4j/util/HexUtil.java | 384 ++-- .../src/org/eclipse/net4j/util/IErrorHandler.java | 44 +- .../eclipse/net4j/util/ImplementationError.java | 84 +- .../src/org/eclipse/net4j/util/ObjectUtil.java | 220 +-- .../src/org/eclipse/net4j/util/ReflectUtil.java | 1206 ++++++------- .../src/org/eclipse/net4j/util/StringUtil.java | 786 ++++----- .../src/org/eclipse/net4j/util/UUIDGenerator.java | 2 +- .../org/eclipse/net4j/util/WrappedException.java | 132 +- .../src/org/eclipse/net4j/util/cache/Cache.java | 216 +-- .../org/eclipse/net4j/util/cache/CacheMonitor.java | 502 +++--- .../net4j/util/cache/CacheRegistration.java | 220 +-- .../util/cache/HysteresisConditionPolicy.java | 210 +-- .../src/org/eclipse/net4j/util/cache/ICache.java | 48 +- .../eclipse/net4j/util/cache/ICacheMonitor.java | 120 +- .../net4j/util/cache/ICacheMonitorEvent.java | 60 +- .../org/eclipse/net4j/util/cache/ICacheProbe.java | 66 +- .../net4j/util/cache/ICacheRegistration.java | 46 +- .../net4j/util/cache/ThresholdConditionPolicy.java | 128 +- .../org/eclipse/net4j/util/cache/package-info.java | 2 +- .../net4j/util/collection/AbstractIterator.java | 2 +- .../net4j/util/collection/ArrayIterator.java | 144 +- .../eclipse/net4j/util/collection/BidiMapper.java | 160 +- .../net4j/util/collection/ByteArrayWrapper.java | 152 +- .../util/collection/CaseInsensitiveStringSet.java | 2 +- .../eclipse/net4j/util/collection/Closeable.java | 48 +- .../net4j/util/collection/CloseableIterator.java | 44 +- .../net4j/util/collection/ConcurrentArray.java | 406 ++--- .../net4j/util/collection/DynamicArray.java | 194 +-- .../eclipse/net4j/util/collection/FastList.java | 42 +- .../org/eclipse/net4j/util/collection/HashBag.java | 372 ++-- .../org/eclipse/net4j/util/collection/History.java | 434 ++--- .../net4j/util/collection/HistoryElement.java | 148 +- .../eclipse/net4j/util/collection/HistoryUtil.java | 66 +- .../eclipse/net4j/util/collection/IHistory.java | 78 +- .../net4j/util/collection/IHistoryChangeEvent.java | 52 +- .../net4j/util/collection/IHistoryElement.java | 46 +- .../eclipse/net4j/util/collection/IndexedList.java | 560 +++--- .../eclipse/net4j/util/collection/MapEntry.java | 168 +- .../net4j/util/collection/MoveableArrayList.java | 168 +- .../net4j/util/collection/MoveableList.java | 42 +- .../eclipse/net4j/util/collection/MultiMap.java | 1550 ++++++++--------- .../org/eclipse/net4j/util/collection/Pair.java | 200 +-- .../net4j/util/collection/PreferenceHistory.java | 108 +- .../util/collection/RoundRobinBlockingQueue.java | 736 ++++---- .../org/eclipse/net4j/util/collection/Triplet.java | 158 +- .../net4j/util/collection/package-info.java | 2 +- .../concurrent/AsynchronousWorkSerializer.java | 322 ++-- .../util/concurrent/CompletionWorkSerializer.java | 132 +- .../net4j/util/concurrent/ConcurrencyUtil.java | 94 +- .../net4j/util/concurrent/ConcurrentValue.java | 220 +-- .../util/concurrent/ExecutorServiceFactory.java | 244 +-- .../eclipse/net4j/util/concurrent/ICorrelator.java | 50 +- .../net4j/util/concurrent/IRWLockManager.java | 126 +- .../net4j/util/concurrent/IRWOLockManager.java | 58 +- .../net4j/util/concurrent/ISynchronizer.java | 56 +- .../net4j/util/concurrent/IWorkSerializer.java | 42 +- .../net4j/util/concurrent/MonitoredThread.java | 522 +++--- .../util/concurrent/NonBlockingIntCounter.java | 134 +- .../util/concurrent/NonBlockingLongCounter.java | 134 +- .../net4j/util/concurrent/OnePendingExecutor.java | 128 +- .../eclipse/net4j/util/concurrent/QueueRunner.java | 56 +- .../eclipse/net4j/util/concurrent/QueueWorker.java | 268 +-- .../util/concurrent/QueueWorkerWorkSerializer.java | 60 +- .../org/eclipse/net4j/util/concurrent/RWLock.java | 224 +-- .../net4j/util/concurrent/RWLockManager.java | 1586 ++++++++--------- .../net4j/util/concurrent/RWOLockManager.java | 1498 ++++++++-------- .../net4j/util/concurrent/ResultSynchronizer.java | 196 +-- .../net4j/util/concurrent/RoundRobinList.java | 1024 +++++------ .../org/eclipse/net4j/util/concurrent/Sleeper.java | 126 +- .../util/concurrent/SynchronizingCorrelator.java | 252 +-- .../util/concurrent/SynchronousWorkSerializer.java | 74 +- .../util/concurrent/TimeoutRuntimeException.java | 100 +- .../eclipse/net4j/util/concurrent/Timeouter.java | 226 +-- .../net4j/util/concurrent/TimerLifecycle.java | 268 +-- .../org/eclipse/net4j/util/concurrent/Worker.java | 624 +++---- .../net4j/util/concurrent/package-info.java | 2 +- .../eclipse/net4j/util/container/Container.java | 230 +-- .../net4j/util/container/ContainerDelta.java | 90 +- .../net4j/util/container/ContainerEvent.java | 274 +-- .../util/container/ContainerEventAdapter.java | 142 +- .../net4j/util/container/ContainerUtil.java | 220 +-- .../util/container/FactoryNotFoundException.java | 92 +- .../eclipse/net4j/util/container/IContainer.java | 102 +- .../net4j/util/container/IContainerDelta.java | 68 +- .../net4j/util/container/IContainerEvent.java | 84 +- .../util/container/IContainerEventVisitor.java | 76 +- .../net4j/util/container/IElementProcessor.java | 44 +- .../net4j/util/container/IManagedContainer.java | 154 +- .../net4j/util/container/IPluginContainer.java | 56 +- .../org/eclipse/net4j/util/container/ISlow.java | 44 +- .../util/container/LifecycleEventConverter.java | 176 +- .../net4j/util/container/ManagedContainer.java | 1324 +++++++------- .../util/container/SingleDeltaContainerEvent.java | 204 +-- .../util/container/delegate/AbstractDelegator.java | 262 +-- .../container/delegate/ContainerBlockingQueue.java | 250 +-- .../container/delegate/ContainerCollection.java | 440 ++--- .../util/container/delegate/ContainerList.java | 436 ++--- .../util/container/delegate/ContainerMap.java | 418 ++--- .../util/container/delegate/ContainerQueue.java | 182 +- .../util/container/delegate/ContainerSet.java | 66 +- .../container/delegate/ContainerSortedSet.java | 164 +- .../delegate/IContainerBlockingQueue.java | 42 +- .../container/delegate/IContainerCollection.java | 50 +- .../util/container/delegate/IContainerList.java | 50 +- .../util/container/delegate/IContainerMap.java | 50 +- .../util/container/delegate/IContainerQueue.java | 50 +- .../util/container/delegate/IContainerSet.java | 50 +- .../container/delegate/IContainerSortedSet.java | 50 +- .../util/container/delegate/package-info.java | 2 +- .../eclipse/net4j/util/container/package-info.java | 2 +- .../src/org/eclipse/net4j/util/event/Event.java | 102 +- .../org/eclipse/net4j/util/event/EventUtil.java | 122 +- .../net4j/util/event/ExecutorServiceNotifier.java | 104 +- .../src/org/eclipse/net4j/util/event/IEvent.java | 44 +- .../org/eclipse/net4j/util/event/IListener.java | 48 +- .../org/eclipse/net4j/util/event/INotifier.java | 114 +- .../src/org/eclipse/net4j/util/event/Notifier.java | 310 ++-- .../org/eclipse/net4j/util/event/ValueEvent.java | 2 +- .../eclipse/net4j/util/event/ValueNotifier.java | 2 +- .../org/eclipse/net4j/util/event/package-info.java | 2 +- .../org/eclipse/net4j/util/factory/Factory.java | 118 +- .../util/factory/FactoryCreationException.java | 84 +- .../net4j/util/factory/FactoryDescriptor.java | 172 +- .../org/eclipse/net4j/util/factory/FactoryKey.java | 196 +-- .../org/eclipse/net4j/util/factory/IFactory.java | 54 +- .../eclipse/net4j/util/factory/IFactoryKey.java | 52 +- .../util/factory/ProductCreationException.java | 86 +- .../eclipse/net4j/util/factory/package-info.java | 2 +- .../eclipse/net4j/util/fsm/FiniteStateMachine.java | 780 ++++----- .../org/eclipse/net4j/util/fsm/ITransition.java | 44 +- .../org/eclipse/net4j/util/fsm/package-info.java | 2 +- .../eclipse/net4j/util/io/AsyncOutputStream.java | 148 +- .../src/org/eclipse/net4j/util/io/AsyncWriter.java | 148 +- .../org/eclipse/net4j/util/io/CachedFileMap.java | 96 +- .../eclipse/net4j/util/io/DataInputExtender.java | 274 +-- .../eclipse/net4j/util/io/DataOutputExtender.java | 240 +-- .../net4j/util/io/DelegatingInputStream.java | 358 ++-- .../net4j/util/io/DelegatingOutputStream.java | 228 +-- .../net4j/util/io/DelegatingStreamWrapper.java | 126 +- .../org/eclipse/net4j/util/io/DigestWriter.java | 270 +-- .../net4j/util/io/ExpectedFileInputStream.java | 240 +-- .../eclipse/net4j/util/io/ExpectedFileReader.java | 258 +-- .../eclipse/net4j/util/io/ExtendedDataInput.java | 398 ++--- .../net4j/util/io/ExtendedDataInputStream.java | 162 +- .../eclipse/net4j/util/io/ExtendedDataOutput.java | 340 ++-- .../net4j/util/io/ExtendedDataOutputStream.java | 138 +- .../eclipse/net4j/util/io/ExtendedIOAdapter.java | 64 +- .../eclipse/net4j/util/io/ExtendedIOHandler.java | 38 +- .../org/eclipse/net4j/util/io/ExtendedIOUtil.java | 594 +++---- .../net4j/util/io/ExtendedInputHandler.java | 44 +- .../net4j/util/io/ExtendedOutputHandler.java | 44 +- .../eclipse/net4j/util/io/GZIPStreamWrapper.java | 200 +-- .../src/org/eclipse/net4j/util/io/IOFilter.java | 38 +- .../src/org/eclipse/net4j/util/io/IORunnable.java | 44 +- .../eclipse/net4j/util/io/IORuntimeException.java | 76 +- .../eclipse/net4j/util/io/IOTimeoutException.java | 100 +- .../src/org/eclipse/net4j/util/io/IOUtil.java | 1830 ++++++++++---------- .../src/org/eclipse/net4j/util/io/IOVisitor.java | 44 +- .../org/eclipse/net4j/util/io/IStreamWrapper.java | 58 +- .../eclipse/net4j/util/io/LimitedInputStream.java | 224 +-- .../org/eclipse/net4j/util/io/LimitedReader.java | 224 +-- .../src/org/eclipse/net4j/util/io/NIOUtil.java | 438 ++--- .../org/eclipse/net4j/util/io/SortedFileMap.java | 462 ++--- .../eclipse/net4j/util/io/StreamWrapperChain.java | 116 +- .../eclipse/net4j/util/io/StringCompressor.java | 912 +++++----- .../src/org/eclipse/net4j/util/io/StringIO.java | 86 +- .../src/org/eclipse/net4j/util/io/TMPUtil.java | 354 ++-- .../src/org/eclipse/net4j/util/io/XMLOutput.java | 634 +++---- .../org/eclipse/net4j/util/io/XORInputStream.java | 110 +- .../org/eclipse/net4j/util/io/XOROutputStream.java | 102 +- .../eclipse/net4j/util/io/XORStreamWrapper.java | 122 +- .../src/org/eclipse/net4j/util/io/ZIPUtil.java | 816 ++++----- .../org/eclipse/net4j/util/io/package-info.java | 2 +- .../eclipse/net4j/util/lifecycle/ILifecycle.java | 90 +- .../net4j/util/lifecycle/ILifecycleEvent.java | 86 +- .../eclipse/net4j/util/lifecycle/Lifecycle.java | 606 +++---- .../net4j/util/lifecycle/LifecycleEvent.java | 94 +- .../util/lifecycle/LifecycleEventAdapter.java | 160 +- .../net4j/util/lifecycle/LifecycleException.java | 84 +- .../net4j/util/lifecycle/LifecycleState.java | 44 +- .../net4j/util/lifecycle/LifecycleUtil.java | 892 +++++----- .../eclipse/net4j/util/lifecycle/package-info.java | 2 +- .../src/org/eclipse/net4j/util/om/LegacyUtil.java | 134 +- .../src/org/eclipse/net4j/util/om/OMBundle.java | 354 ++-- .../src/org/eclipse/net4j/util/om/OMPlatform.java | 184 +- .../org/eclipse/net4j/util/om/OSGiActivator.java | 640 +++---- .../org/eclipse/net4j/util/om/OSGiApplication.java | 294 ++-- .../net4j/util/om/log/AbstractLogHandler.java | 152 +- .../net4j/util/om/log/EclipseLoggingBridge.java | 128 +- .../eclipse/net4j/util/om/log/FileLogHandler.java | 128 +- .../src/org/eclipse/net4j/util/om/log/Logger.java | 226 +-- .../org/eclipse/net4j/util/om/log/OMLogFilter.java | 62 +- .../eclipse/net4j/util/om/log/OMLogHandler.java | 42 +- .../org/eclipse/net4j/util/om/log/OMLogger.java | 122 +- .../net4j/util/om/log/OSGiLoggingBridge.java | 162 +- .../eclipse/net4j/util/om/log/PrintLogHandler.java | 100 +- .../eclipse/net4j/util/om/log/package-info.java | 2 +- .../net4j/util/om/monitor/AbstractMonitor.java | 414 ++--- .../net4j/util/om/monitor/DelegatingMonitor.java | 210 +-- .../net4j/util/om/monitor/EclipseMonitor.java | 364 ++-- .../org/eclipse/net4j/util/om/monitor/Monitor.java | 194 +-- .../util/om/monitor/MonitorCanceledException.java | 80 +- .../net4j/util/om/monitor/NestedMonitor.java | 214 +-- .../net4j/util/om/monitor/NotifyingMonitor.java | 248 +-- .../eclipse/net4j/util/om/monitor/OMMonitor.java | 212 +-- .../net4j/util/om/monitor/OMMonitorProgress.java | 68 +- .../util/om/monitor/ProgressDistributable.java | 108 +- .../net4j/util/om/monitor/ProgressDistributor.java | 346 ++-- .../net4j/util/om/monitor/TimeoutMonitor.java | 264 +-- .../net4j/util/om/monitor/package-info.java | 2 +- .../org/eclipse/net4j/util/om/package-info.java | 2 +- .../eclipse/net4j/util/om/pref/OMPreference.java | 86 +- .../eclipse/net4j/util/om/pref/OMPreferences.java | 192 +- .../util/om/pref/OMPreferencesChangeEvent.java | 70 +- .../eclipse/net4j/util/om/pref/package-info.java | 2 +- .../eclipse/net4j/util/om/trace/ContextTracer.java | 178 +- .../net4j/util/om/trace/OMTraceHandler.java | 38 +- .../net4j/util/om/trace/OMTraceHandlerEvent.java | 58 +- .../org/eclipse/net4j/util/om/trace/OMTracer.java | 94 +- .../eclipse/net4j/util/om/trace/PerfTracer.java | 162 +- .../net4j/util/om/trace/PrintTraceHandler.java | 264 +-- .../net4j/util/om/trace/RemoteTraceHandler.java | 294 ++-- .../net4j/util/om/trace/RemoteTraceServer.java | 798 ++++----- .../net4j/util/om/trace/TraceHandlerEvent.java | 152 +- .../org/eclipse/net4j/util/om/trace/Tracer.java | 256 +-- .../eclipse/net4j/util/om/trace/package-info.java | 2 +- .../org/eclipse/net4j/util/options/IOptions.java | 56 +- .../net4j/util/options/IOptionsContainer.java | 42 +- .../eclipse/net4j/util/options/IOptionsEvent.java | 50 +- .../eclipse/net4j/util/options/OptionsEvent.java | 68 +- .../eclipse/net4j/util/options/package-info.java | 2 +- .../src/org/eclipse/net4j/util/package-info.java | 2 +- .../util/properties/DefaultPropertyTester.java | 204 +-- .../eclipse/net4j/util/properties/IProperties.java | 52 +- .../net4j/util/properties/IPropertyProvider.java | 2 +- .../eclipse/net4j/util/properties/Properties.java | 128 +- .../eclipse/net4j/util/properties/Property.java | 2 +- .../net4j/util/properties/package-info.java | 2 +- .../net4j/util/ref/KeyedPhantomReference.java | 90 +- .../org/eclipse/net4j/util/ref/KeyedReference.java | 88 +- .../eclipse/net4j/util/ref/KeyedSoftReference.java | 102 +- .../net4j/util/ref/KeyedStrongReference.java | 130 +- .../eclipse/net4j/util/ref/KeyedWeakReference.java | 102 +- .../net4j/util/ref/ReferenceQueueWorker.java | 202 +-- .../org/eclipse/net4j/util/ref/ReferenceType.java | 40 +- .../eclipse/net4j/util/ref/ReferenceValueMap.java | 1006 +++++------ .../org/eclipse/net4j/util/ref/package-info.java | 2 +- .../net4j/util/registry/DelegatingRegistry.java | 298 ++-- .../util/registry/HashMapDelegatingRegistry.java | 104 +- .../net4j/util/registry/HashMapRegistry.java | 96 +- .../org/eclipse/net4j/util/registry/IRegistry.java | 58 +- .../org/eclipse/net4j/util/registry/Registry.java | 656 +++---- .../eclipse/net4j/util/registry/RegistryUtil.java | 62 +- .../net4j/util/registry/UnmodifiableRegistry.java | 300 ++-- .../eclipse/net4j/util/registry/package-info.java | 2 +- .../net4j/util/security/ChallengeNegotiator.java | 292 ++-- .../security/ChallengeNegotiatorConfigurer.java | 160 +- .../util/security/ChallengeNegotiatorFactory.java | 58 +- .../util/security/ChallengeResponseNegotiator.java | 400 ++--- .../eclipse/net4j/util/security/Credentials.java | 58 +- .../util/security/CredentialsProviderFactory.java | 60 +- .../net4j/util/security/FileUserManager.java | 284 +-- .../util/security/FileUserManagerFactory.java | 66 +- .../net4j/util/security/IChallengeResponse.java | 74 +- .../eclipse/net4j/util/security/ICredentials.java | 36 +- .../net4j/util/security/ICredentialsProvider.java | 42 +- .../net4j/util/security/INegotiationContext.java | 114 +- .../eclipse/net4j/util/security/INegotiator.java | 48 +- .../net4j/util/security/INegotiatorAware.java | 44 +- .../net4j/util/security/IPasswordCredentials.java | 38 +- .../security/IPasswordCredentialsProvider.java | 38 +- .../eclipse/net4j/util/security/IRandomizer.java | 74 +- .../eclipse/net4j/util/security/IUserAware.java | 40 +- .../eclipse/net4j/util/security/IUserManager.java | 54 +- .../net4j/util/security/NegotiationContext.java | 204 +-- .../net4j/util/security/NegotiationException.java | 78 +- .../eclipse/net4j/util/security/Negotiator.java | 294 ++-- .../net4j/util/security/NegotiatorFactory.java | 52 +- .../net4j/util/security/PasswordCredentials.java | 70 +- .../util/security/PasswordCredentialsProvider.java | 206 +-- .../eclipse/net4j/util/security/Randomizer.java | 376 ++-- .../net4j/util/security/RandomizerFactory.java | 80 +- .../net4j/util/security/ResponseNegotiator.java | 198 +-- .../util/security/ResponseNegotiatorFactory.java | 58 +- .../util/security/ResponseNegotiatorInjector.java | 114 +- .../eclipse/net4j/util/security/SecurityUtil.java | 140 +- .../eclipse/net4j/util/security/UserManager.java | 196 +-- .../net4j/util/security/UserManagerFactory.java | 52 +- .../eclipse/net4j/util/security/package-info.java | 2 +- .../net4j/util/transaction/ITransaction.java | 54 +- .../util/transaction/ITransactionalOperation.java | 46 +- .../net4j/util/transaction/Transaction.java | 204 +-- .../util/transaction/TransactionException.java | 78 +- .../net4j/util/transaction/TransactionUtil.java | 52 +- .../net4j/util/transaction/package-info.java | 2 +- 325 files changed, 32279 insertions(+), 32279 deletions(-) (limited to 'plugins/org.eclipse.net4j.util') diff --git a/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs b/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs index aaef0ccba1..6726e7034a 100644 --- a/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs +++ b/plugins/org.eclipse.net4j.util/.settings/org.eclipse.jdt.ui.prefs @@ -1,120 +1,120 @@ -#Thu Feb 04 09:44:24 CET 2010 -cleanup.add_default_serial_version_id=true -cleanup.add_generated_serial_version_id=false -cleanup.add_missing_annotations=true -cleanup.add_missing_deprecated_annotations=true -cleanup.add_missing_methods=false -cleanup.add_missing_nls_tags=false -cleanup.add_missing_override_annotations=true -cleanup.add_missing_override_annotations_interface_methods=true -cleanup.add_serial_version_id=true -cleanup.always_use_blocks=true -cleanup.always_use_parentheses_in_expressions=false -cleanup.always_use_this_for_non_static_field_access=false -cleanup.always_use_this_for_non_static_method_access=false -cleanup.convert_to_enhanced_for_loop=false -cleanup.correct_indentation=true -cleanup.format_source_code=true -cleanup.format_source_code_changes_only=false -cleanup.make_local_variable_final=true -cleanup.make_parameters_final=false -cleanup.make_private_fields_final=true -cleanup.make_type_abstract_if_missing_method=false -cleanup.make_variable_declarations_final=false -cleanup.never_use_blocks=false -cleanup.never_use_parentheses_in_expressions=true -cleanup.organize_imports=true -cleanup.qualify_static_field_accesses_with_declaring_class=false -cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -cleanup.qualify_static_member_accesses_with_declaring_class=false -cleanup.qualify_static_method_accesses_with_declaring_class=false -cleanup.remove_private_constructors=true -cleanup.remove_trailing_whitespaces=true -cleanup.remove_trailing_whitespaces_all=true -cleanup.remove_trailing_whitespaces_ignore_empty=false -cleanup.remove_unnecessary_casts=true -cleanup.remove_unnecessary_nls_tags=true -cleanup.remove_unused_imports=true -cleanup.remove_unused_local_variables=false -cleanup.remove_unused_private_fields=true -cleanup.remove_unused_private_members=false -cleanup.remove_unused_private_methods=true -cleanup.remove_unused_private_types=true -cleanup.sort_members=false -cleanup.sort_members_all=false -cleanup.use_blocks=true -cleanup.use_blocks_only_for_return_and_throw=false -cleanup.use_parentheses_in_expressions=true -cleanup.use_this_for_non_static_field_access=true -cleanup.use_this_for_non_static_field_access_only_if_necessary=true -cleanup.use_this_for_non_static_method_access=true -cleanup.use_this_for_non_static_method_access_only_if_necessary=true -cleanup_profile=_EMFT -cleanup_settings_version=2 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -formatter_profile=_EMFT -formatter_settings_version=11 -org.eclipse.jdt.ui.exception.name=ex -org.eclipse.jdt.ui.gettersetter.use.is=true -org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=org.eclipse.emf.cdo;org.eclipse.emf.internal.cdo;org.eclipse.net4j;org.eclipse.internal.net4j;org.eclipse.emf;org.eclipse;com;org;javax;java; -org.eclipse.jdt.ui.javadoc=true -org.eclipse.jdt.ui.keywordthis=false -org.eclipse.jdt.ui.ondemandthreshold=99 -org.eclipse.jdt.ui.overrideannotation=true -org.eclipse.jdt.ui.staticondemandthreshold=99 -org.eclipse.jdt.ui.text.custom_code_templates=/*\r\n * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.\r\n * All rights reserved. This program and the accompanying materials\r\n * are made available under the terms of the Eclipse Public License v1.0\r\n * which accompanies this distribution, and is available at\r\n * http\://www.eclipse.org/legal/epl-v10.html\r\n * \r\n * Contributors\:\r\n * Eike Stepper - initial API and implementation\r\n *//**\r\n * @author Eike Stepper\r\n */${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}\r\n\r\n\r\n\r\n${exception_var}.printStackTrace();${body_statement}${body_statement}return ${field};${field} \= ${param}; -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=false -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=false -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=false -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=false -sp_cleanup.make_local_variable_final=false -sp_cleanup.make_parameters_final=false -sp_cleanup.make_private_fields_final=true -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=false -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=true -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=false -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=true -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=true -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true +#Thu Feb 04 09:44:24 CET 2010 +cleanup.add_default_serial_version_id=true +cleanup.add_generated_serial_version_id=false +cleanup.add_missing_annotations=true +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=true +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=false +cleanup.always_use_this_for_non_static_method_access=false +cleanup.convert_to_enhanced_for_loop=false +cleanup.correct_indentation=true +cleanup.format_source_code=true +cleanup.format_source_code_changes_only=false +cleanup.make_local_variable_final=true +cleanup.make_parameters_final=false +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=false +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=true +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=false +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=false +cleanup.sort_members_all=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_parentheses_in_expressions=true +cleanup.use_this_for_non_static_field_access=true +cleanup.use_this_for_non_static_field_access_only_if_necessary=true +cleanup.use_this_for_non_static_method_access=true +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup_profile=_EMFT +cleanup_settings_version=2 +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true +formatter_profile=_EMFT +formatter_settings_version=11 +org.eclipse.jdt.ui.exception.name=ex +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=org.eclipse.emf.cdo;org.eclipse.emf.internal.cdo;org.eclipse.net4j;org.eclipse.internal.net4j;org.eclipse.emf;org.eclipse;com;org;javax;java; +org.eclipse.jdt.ui.javadoc=true +org.eclipse.jdt.ui.keywordthis=false +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.staticondemandthreshold=99 +org.eclipse.jdt.ui.text.custom_code_templates=/*\r\n * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.\r\n * All rights reserved. This program and the accompanying materials\r\n * are made available under the terms of the Eclipse Public License v1.0\r\n * which accompanies this distribution, and is available at\r\n * http\://www.eclipse.org/legal/epl-v10.html\r\n * \r\n * Contributors\:\r\n * Eike Stepper - initial API and implementation\r\n *//**\r\n * @author Eike Stepper\r\n */${filecomment}\r\n${package_declaration}\r\n\r\n${typecomment}\r\n${type_declaration}\r\n\r\n\r\n\r\n${exception_var}.printStackTrace();${body_statement}${body_statement}return ${field};${field} \= ${param}; +sp_cleanup.add_default_serial_version_id=true +sp_cleanup.add_generated_serial_version_id=false +sp_cleanup.add_missing_annotations=true +sp_cleanup.add_missing_deprecated_annotations=true +sp_cleanup.add_missing_methods=false +sp_cleanup.add_missing_nls_tags=false +sp_cleanup.add_missing_override_annotations=true +sp_cleanup.add_missing_override_annotations_interface_methods=false +sp_cleanup.add_serial_version_id=false +sp_cleanup.always_use_blocks=true +sp_cleanup.always_use_parentheses_in_expressions=false +sp_cleanup.always_use_this_for_non_static_field_access=false +sp_cleanup.always_use_this_for_non_static_method_access=false +sp_cleanup.convert_to_enhanced_for_loop=false +sp_cleanup.correct_indentation=true +sp_cleanup.format_source_code=true +sp_cleanup.format_source_code_changes_only=false +sp_cleanup.make_local_variable_final=false +sp_cleanup.make_parameters_final=false +sp_cleanup.make_private_fields_final=true +sp_cleanup.make_type_abstract_if_missing_method=false +sp_cleanup.make_variable_declarations_final=false +sp_cleanup.never_use_blocks=false +sp_cleanup.never_use_parentheses_in_expressions=true +sp_cleanup.on_save_use_additional_actions=true +sp_cleanup.organize_imports=true +sp_cleanup.qualify_static_field_accesses_with_declaring_class=false +sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +sp_cleanup.qualify_static_member_accesses_with_declaring_class=false +sp_cleanup.qualify_static_method_accesses_with_declaring_class=false +sp_cleanup.remove_private_constructors=true +sp_cleanup.remove_trailing_whitespaces=true +sp_cleanup.remove_trailing_whitespaces_all=true +sp_cleanup.remove_trailing_whitespaces_ignore_empty=false +sp_cleanup.remove_unnecessary_casts=true +sp_cleanup.remove_unnecessary_nls_tags=true +sp_cleanup.remove_unused_imports=true +sp_cleanup.remove_unused_local_variables=false +sp_cleanup.remove_unused_private_fields=true +sp_cleanup.remove_unused_private_members=false +sp_cleanup.remove_unused_private_methods=true +sp_cleanup.remove_unused_private_types=true +sp_cleanup.sort_members=false +sp_cleanup.sort_members_all=false +sp_cleanup.use_blocks=true +sp_cleanup.use_blocks_only_for_return_and_throw=false +sp_cleanup.use_parentheses_in_expressions=true +sp_cleanup.use_this_for_non_static_field_access=true +sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true +sp_cleanup.use_this_for_non_static_method_access=true +sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/plugins/org.eclipse.net4j.util/build.properties b/plugins/org.eclipse.net4j.util/build.properties index a888fd517c..dca3406b70 100644 --- a/plugins/org.eclipse.net4j.util/build.properties +++ b/plugins/org.eclipse.net4j.util/build.properties @@ -1,25 +1,25 @@ -# Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# Eike Stepper - initial API and implementation - -# NLS_MESSAGEFORMAT_VAR - -source.. = src/ -output.. = bin/ -bin.includes = META-INF/,\ - .,\ - .options,\ - about.html,\ - copyright.txt,\ - plugin.properties,\ - plugin.xml,\ - schema/ -src.includes = about.html,\ - copyright.txt - -doc.project = org.eclipse.net4j.util.doc +# Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Eike Stepper - initial API and implementation + +# NLS_MESSAGEFORMAT_VAR + +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + .options,\ + about.html,\ + copyright.txt,\ + plugin.properties,\ + plugin.xml,\ + schema/ +src.includes = about.html,\ + copyright.txt + +doc.project = org.eclipse.net4j.util.doc diff --git a/plugins/org.eclipse.net4j.util/copyright.txt b/plugins/org.eclipse.net4j.util/copyright.txt index e921242cf0..8f6328980e 100644 --- a/plugins/org.eclipse.net4j.util/copyright.txt +++ b/plugins/org.eclipse.net4j.util/copyright.txt @@ -1,8 +1,8 @@ -Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. -All rights reserved. This program and the accompanying materials -are made available under the terms of the Eclipse Public License v1.0 -which accompanies this distribution, and is available at -http://www.eclipse.org/legal/epl-v10.html - -Contributors: +Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. +All rights reserved. This program and the accompanying materials +are made available under the terms of the Eclipse Public License v1.0 +which accompanies this distribution, and is available at +http://www.eclipse.org/legal/epl-v10.html + +Contributors: Eike Stepper - initial API and implementation \ No newline at end of file diff --git a/plugins/org.eclipse.net4j.util/plugin.properties b/plugins/org.eclipse.net4j.util/plugin.properties index 53a57f2b9a..f250e4d207 100644 --- a/plugins/org.eclipse.net4j.util/plugin.properties +++ b/plugins/org.eclipse.net4j.util/plugin.properties @@ -1,14 +1,14 @@ -# Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. -# All rights reserved. This program and the accompanying materials -# are made available under the terms of the Eclipse Public License v1.0 -# which accompanies this distribution, and is available at -# http://www.eclipse.org/legal/epl-v10.html -# -# Contributors: -# Eike Stepper - initial API and implementation - -pluginName = Net4j Utilities -providerName = Eclipse Modeling Project - -extension-point.name = Factories +# Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Eclipse Public License v1.0 +# which accompanies this distribution, and is available at +# http://www.eclipse.org/legal/epl-v10.html +# +# Contributors: +# Eike Stepper - initial API and implementation + +pluginName = Net4j Utilities +providerName = Eclipse Modeling Project + +extension-point.name = Factories extension-point.name.0 = Element Processors \ No newline at end of file diff --git a/plugins/org.eclipse.net4j.util/plugin.xml b/plugins/org.eclipse.net4j.util/plugin.xml index 6c151aa3b3..8bbd7636ba 100644 --- a/plugins/org.eclipse.net4j.util/plugin.xml +++ b/plugins/org.eclipse.net4j.util/plugin.xml @@ -1,39 +1,39 @@ - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd b/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd index b6ada0d28e..978f855009 100644 --- a/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd +++ b/plugins/org.eclipse.net4j.util/schema/elementProcessors.exsd @@ -1,106 +1,106 @@ - - - - - - - - - [Enter description of this extension point.] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [Enter the first release in which this extension point appears.] - - - - - - - - - [Enter extension point usage example here.] - - - - - - - - - [Enter API information here.] - - - - - - - - - [Enter information about supplied implementation of this extension point.] - - - - - - - - - Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.<br> -All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> - - - - + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + + + + + Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.<br> +All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> + + + + diff --git a/plugins/org.eclipse.net4j.util/schema/factories.exsd b/plugins/org.eclipse.net4j.util/schema/factories.exsd index 5d4fe31ba2..d0ee9cfccc 100644 --- a/plugins/org.eclipse.net4j.util/schema/factories.exsd +++ b/plugins/org.eclipse.net4j.util/schema/factories.exsd @@ -1,125 +1,125 @@ - - - - - - - - - [Enter description of this extension point.] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [Enter the first release in which this extension point appears.] - - - - - - - - - [Enter extension point usage example here.] - - - - - - - - - [Enter API information here.] - - - - - - - - - [Enter information about supplied implementation of this extension point.] - - - - - - - - - Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others.<br> -All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> - - - - + + + + + + + + + [Enter description of this extension point.] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + [Enter the first release in which this extension point appears.] + + + + + + + + + [Enter extension point usage example here.] + + + + + + + + + [Enter API information here.] + + + + + + + + + [Enter information about supplied implementation of this extension point.] + + + + + + + + + Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.<br> +All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a> + + + + 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 a61c00f2be..d997a4969c 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 tracers = new ConcurrentHashMap(0); - - private OMLogger logger; - - private Preferences preferences; - - private ResourceBundle resourceBundle; - - private ResourceBundle untranslatedResourceBundle; - - private Map strings = new HashMap(0); - - private Map untranslatedStrings = new HashMap(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 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 tracers = new ConcurrentHashMap(0); + + private OMLogger logger; + + private Preferences preferences; + + private ResourceBundle resourceBundle; + + private ResourceBundle untranslatedResourceBundle; + + private Map strings = new HashMap(0); + + private Map untranslatedStrings = new HashMap(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 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 103b9ebb53..7d0aef5db7 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 bundles = new ConcurrentHashMap(0); - - private ConcurrentArray logFilters = new ConcurrentArray.Unique() - { - @Override - protected OMLogFilter[] newArray(int length) - { - return new OMLogFilter[length]; - } - }; - - private ConcurrentArray logHandlers = new ConcurrentArray.Unique() - { - @Override - protected OMLogHandler[] newArray(int length) - { - return new OMLogHandler[length]; - } - }; - - private ConcurrentArray traceHandlers = new ConcurrentArray.Unique() - { - @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 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 bundles = new ConcurrentHashMap(0); + + private ConcurrentArray logFilters = new ConcurrentArray.Unique() + { + @Override + protected OMLogFilter[] newArray(int length) + { + return new OMLogFilter[length]; + } + }; + + private ConcurrentArray logHandlers = new ConcurrentArray.Unique() + { + @Override + protected OMLogHandler[] newArray(int length) + { + return new OMLogHandler[length]; + } + }; + + private ConcurrentArray traceHandlers = new ConcurrentArray.Unique() + { + @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 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 30222f89ea..d9cb9960d5 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 Operations & Maintenance 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 Operations & Maintenance 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/PluginContainer.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java index 4be81e8b9f..2a245e1c2c 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/internal/util/container/PluginContainer.java @@ -1,77 +1,77 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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.internal.util.factory.PluginFactoryRegistry; -import org.eclipse.net4j.util.container.IElementProcessor; -import org.eclipse.net4j.util.container.IPluginContainer; -import org.eclipse.net4j.util.container.ManagedContainer; -import org.eclipse.net4j.util.factory.IFactory; -import org.eclipse.net4j.util.factory.IFactoryKey; -import org.eclipse.net4j.util.lifecycle.LifecycleUtil; -import org.eclipse.net4j.util.om.log.OMLogger; -import org.eclipse.net4j.util.registry.IRegistry; - -import java.util.List; - -/** - * @author Eike Stepper - */ -public class PluginContainer extends ManagedContainer implements IPluginContainer -{ - private static PluginContainer instance; - - private PluginContainer() - { - } - - @Override - protected IRegistry createFactoryRegistry() - { - return new PluginFactoryRegistry(); - } - - @Override - protected List createPostProcessors() - { - return new PluginElementProcessorList(); - } - - public static void dispose() - { - if (instance != null) - { - LifecycleUtil.deactivate(instance, OMLogger.Level.WARN); - instance = null; - } - } - - public static synchronized PluginContainer getInstance() - { - if (instance == null) - { - instance = new PluginContainer(); - - try - { - instance.activate(); - } - catch (Exception ex) - { - OM.LOG.error(ex); - instance = null; - } - } - - return instance; - } -} +/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this 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.internal.util.factory.PluginFactoryRegistry; +import org.eclipse.net4j.util.container.IElementProcessor; +import org.eclipse.net4j.util.container.IPluginContainer; +import org.eclipse.net4j.util.container.ManagedContainer; +import org.eclipse.net4j.util.factory.IFactory; +import org.eclipse.net4j.util.factory.IFactoryKey; +import org.eclipse.net4j.util.lifecycle.LifecycleUtil; +import org.eclipse.net4j.util.om.log.OMLogger; +import org.eclipse.net4j.util.registry.IRegistry; + +import java.util.List; + +/** + * @author Eike Stepper + */ +public class PluginContainer extends ManagedContainer implements IPluginContainer +{ + private static PluginContainer instance; + + private PluginContainer() + { + } + + @Override + protected IRegistry createFactoryRegistry() + { + return new PluginFactoryRegistry(); + } + + @Override + protected List createPostProcessors() + { + return new PluginElementProcessorList(); + } + + public static void dispose() + { + if (instance != null) + { + LifecycleUtil.deactivate(instance, OMLogger.Level.WARN); + instance = null; + } + } + + public static synchronized PluginContainer getInstance() + { + if (instance == null) + { + instance = new PluginContainer(); + + try + { + instance.activate(); + } + catch (Exception ex) + { + OM.LOG.error(ex); + instance = null; + } + } + + return instance; + } +} 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 dc7cc9798b..8fa5704f59 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 processors = new ArrayList(); - - 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 iterator() - { - return processors.iterator(); - } - - public int lastIndexOf(Object o) - { - return processors.lastIndexOf(o); - } - - public ListIterator listIterator() - { - return processors.listIterator(); - } - - public ListIterator 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 subList(int fromIndex, int toIndex) - { - return processors.subList(fromIndex, toIndex); - } - - public Object[] toArray() - { - return processors.toArray(); - } - - public 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 +{ + 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 processors = new ArrayList(); + + 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 iterator() + { + return processors.iterator(); + } + + public int lastIndexOf(Object o) + { + return processors.lastIndexOf(o); + } + + public ListIterator listIterator() + { + return processors.listIterator(); + } + + public ListIterator 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 subList(int fromIndex, int toIndex) + { + return processors.subList(fromIndex, toIndex); + } + + public Object[] toArray() + { + return processors.toArray(); + } + + public 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 c992c1e257..04f569d54e 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 d793bfd388..2cfb67bb15 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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> getClasses() - { - List> result = new ArrayList>(); - - if (isArchiveProtocol(baseURL.getProtocol())) - { - JarFile jarFile = null; - - try - { - jarFile = new JarFile(baseURL.getFile()); - - Enumeration 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> 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 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> getClasses() + { + List> result = new ArrayList>(); + + if (isArchiveProtocol(baseURL.getProtocol())) + { + JarFile jarFile = null; + + try + { + jarFile = new JarFile(baseURL.getFile()); + + Enumeration 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> 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 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 7d523705e6..f5df96131d 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 debugOptions = new ConcurrentHashMap(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 debugOptions = new ConcurrentHashMap(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 5c965fa0e1..ed6d5bd4d1 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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> getClasses() - { - final Queue folders = new LinkedList(); - folders.offer("/"); - - return new AbstractIterator>() - { - private Enumeration 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> getClasses() + { + final Queue folders = new LinkedList(); + folders.offer("/"); + + return new AbstractIterator>() + { + private Enumeration 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 22e05b4e4c..e32483f1c9 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 241e61736b..cf413fb9a6 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 416447fdd0..1167003eab 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 008daf3e58..bec70ea622 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 324a1872e0..e3d9617f70 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 9797b4462a..ae5b951b62 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 97599599e0..bd5fe357ef 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 f6c69691b6..6607f71f4b 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 ec84e5aab6..1c7edf0d14 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 implements OMPreference -{ - 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 implements OMPreference +{ + 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 c269de82d6..18f650667b 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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> prefs = new HashMap>(); - - 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() - { - 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() - { - 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 init(String name, boolean defaultValue) - { - return init(new BooleanPreference(this, name, defaultValue)); - } - - public OMPreference init(String name, int defaultValue) - { - return init(new IntegerPreference(this, name, defaultValue)); - } - - public OMPreference init(String name, long defaultValue) - { - return init(new LongPreference(this, name, defaultValue)); - } - - public OMPreference init(String name, float defaultValue) - { - return init(new FloatPreference(this, name, defaultValue)); - } - - public OMPreference init(String name, double defaultValue) - { - return init(new DoublePreference(this, name, defaultValue)); - } - - public OMPreference init(String name, String defaultValue) - { - return init(new StringPreference(this, name, defaultValue)); - } - - public OMPreference init(String name, String[] defaultValue) - { - return init(new ArrayPreference(this, name, defaultValue)); - } - - public OMPreference init(String name, byte[] defaultValue) - { - return init(new BytesPreference(this, name, defaultValue)); - } - - public OMPreference initBoolean(String name) - { - return init(name, DEFAULT_BOOLEAN); - } - - public OMPreference initInteger(String name) - { - return init(name, DEFAULT_INTEGER); - } - - public OMPreference initLong(String name) - { - return init(name, DEFAULT_LONG); - } - - public OMPreference initFloat(String name) - { - return init(name, DEFAULT_FLOAT); - } - - public OMPreference initDouble(String name) - { - return init(name, DEFAULT_DOUBLE); - } - - public OMPreference initString(String name) - { - return init(name, DEFAULT_STRING); - } - - public OMPreference initArray(String name) - { - return init(name, DEFAULT_ARRAY); - } - - public OMPreference 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 getBoolean(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getInteger(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getLong(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getFloat(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getDouble(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getString(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getArray(String name) - { - return (OMPreference)get(name); - } - - @SuppressWarnings("unchecked") - public OMPreference getBytes(String name) - { - return (OMPreference)get(name); - } - - public void fireChangeEvent(Preference preference, T oldValue, T newValue) - { - dirty = true; - IListener[] listeners = getListeners(); - if (listeners != null) - { - fireEvent(new PreferencesChangeEvent(preference, oldValue, newValue), listeners); - } - } - - private OMPreference init(Preference 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> prefs = new HashMap>(); + + 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() + { + 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() + { + 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 init(String name, boolean defaultValue) + { + return init(new BooleanPreference(this, name, defaultValue)); + } + + public OMPreference init(String name, int defaultValue) + { + return init(new IntegerPreference(this, name, defaultValue)); + } + + public OMPreference init(String name, long defaultValue) + { + return init(new LongPreference(this, name, defaultValue)); + } + + public OMPreference init(String name, float defaultValue) + { + return init(new FloatPreference(this, name, defaultValue)); + } + + public OMPreference init(String name, double defaultValue) + { + return init(new DoublePreference(this, name, defaultValue)); + } + + public OMPreference init(String name, String defaultValue) + { + return init(new StringPreference(this, name, defaultValue)); + } + + public OMPreference init(String name, String[] defaultValue) + { + return init(new ArrayPreference(this, name, defaultValue)); + } + + public OMPreference init(String name, byte[] defaultValue) + { + return init(new BytesPreference(this, name, defaultValue)); + } + + public OMPreference initBoolean(String name) + { + return init(name, DEFAULT_BOOLEAN); + } + + public OMPreference initInteger(String name) + { + return init(name, DEFAULT_INTEGER); + } + + public OMPreference initLong(String name) + { + return init(name, DEFAULT_LONG); + } + + public OMPreference initFloat(String name) + { + return init(name, DEFAULT_FLOAT); + } + + public OMPreference initDouble(String name) + { + return init(name, DEFAULT_DOUBLE); + } + + public OMPreference initString(String name) + { + return init(name, DEFAULT_STRING); + } + + public OMPreference initArray(String name) + { + return init(name, DEFAULT_ARRAY); + } + + public OMPreference 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 getBoolean(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getInteger(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getLong(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getFloat(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getDouble(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getString(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getArray(String name) + { + return (OMPreference)get(name); + } + + @SuppressWarnings("unchecked") + public OMPreference getBytes(String name) + { + return (OMPreference)get(name); + } + + public void fireChangeEvent(Preference preference, T oldValue, T newValue) + { + dirty = true; + IListener[] listeners = getListeners(); + if (listeners != null) + { + fireEvent(new PreferencesChangeEvent(preference, oldValue, newValue), listeners); + } + } + + private OMPreference init(Preference 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 7040e28ab5..ff56a8291d 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 extends Event implements OMPreferencesChangeEvent -{ - private static final long serialVersionUID = 1L; - - private Preference preference; - - private T oldValue; - - private T newValue; - - public PreferencesChangeEvent(Preference 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 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 extends Event implements OMPreferencesChangeEvent +{ + private static final long serialVersionUID = 1L; + + private Preference preference; + + private T oldValue; + + private T newValue; + + public PreferencesChangeEvent(Preference 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 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 133e8f62ec..8038862b37 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this 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 -{ - 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 +{ + 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 b5363c8438..d7604fa61b 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 adapt(Object object, Class 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 adapt(Object object, Class 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 07c989df4a..bb37bb3984 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 806037e177..e051534586 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 36d1d3f56e..2ae7afa3a2 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 1e029361d7..b92523b645 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 2f250612b5..43a51b8dae 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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[] 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 boolean isEmpty(T[] array) - { - return array == null || array.length == 0; - } - - /** - * @since 3.1 - */ - public static > boolean isEmpty(Map, ?> map) - { - return map == null || map.isEmpty(); - } - - /** - * @since 3.1 - */ - public static > 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[] 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 boolean isEmpty(T[] array) + { + return array == null || array.length == 0; + } + + /** + * @since 3.1 + */ + public static > boolean isEmpty(Map, ?> map) + { + return map == null || map.isEmpty(); + } + + /** + * @since 3.1 + */ + public static > 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/ReflectUtil.java b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java index 3dc48958aa..8a7d4f9a08 100644 --- a/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java +++ b/plugins/org.eclipse.net4j.util/src/org/eclipse/net4j/util/ReflectUtil.java @@ -1,603 +1,603 @@ -/* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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.internal.util.bundle.OM; -import org.eclipse.net4j.util.collection.Pair; -import org.eclipse.net4j.util.io.IOUtil; -import org.eclipse.net4j.util.lifecycle.Lifecycle; - -import java.io.PrintStream; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.WeakHashMap; - -/** - * Various static helper methods for dealing with Java reflection. - * - * @author Eike Stepper - */ -public final class ReflectUtil -{ - private static final String NAMESPACE_SEPARATOR = "."; //$NON-NLS-1$ - - public static final Class ROOT_CLASS = Object.class; - - public static final Class>[] NO_PARAMETERS = null; - - public static final Object[] NO_ARGUMENTS = null; - - private static final Method HASH_CODE_METHOD = lookupHashCodeMethod(); - - private static final Map ids = new WeakHashMap(); - - public static boolean DUMP_STATICS = false; - - private static long lastID; - - private ReflectUtil() - { - } - - public static Method getMethod(Class> c, String methodName, Class>... parameterTypes) - { - try - { - try - { - return c.getDeclaredMethod(methodName, parameterTypes); - } - catch (NoSuchMethodException ex) - { - Class> superclass = c.getSuperclass(); - if (superclass != null) - { - return getMethod(superclass, methodName, parameterTypes); - } - - throw ex; - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static Object invokeMethod(Method method, Object target, Object... arguments) - { - boolean accessible = method.isAccessible(); - if (!accessible) - { - method.setAccessible(true); - } - - try - { - return method.invoke(target, arguments); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - finally - { - if (!accessible) - { - method.setAccessible(false); - } - } - } - - public static Field getField(Class> c, String fieldName) - { - try - { - try - { - return c.getDeclaredField(fieldName); - } - catch (NoSuchFieldException ex) - { - Class> superclass = c.getSuperclass(); - if (superclass != null) - { - return getField(superclass, fieldName); - } - - return null; - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void collectFields(Class> c, List fields) - { - if (c == ROOT_CLASS) - { - return; - } - - // Recurse - collectFields(c.getSuperclass(), fields); - - try - { - Field[] declaredFields = c.getDeclaredFields(); - for (Field field : declaredFields) - { - if (field.isSynthetic()) - { - continue; - } - - if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS) - { - continue; - } - - if (field.getAnnotation(ExcludeFromDump.class) != null) - { - continue; - } - - fields.add(field); - } - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static Object getValue(Field field, Object target) - { - if (!field.isAccessible()) - { - field.setAccessible(true); - } - - try - { - return field.get(target); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void setValue(Field field, Object target, Object value) - { - if (!field.isAccessible()) - { - field.setAccessible(true); - } - - try - { - field.set(target, value); - } - catch (Exception ex) - { - throw WrappedException.wrap(ex); - } - } - - public static void printStackTrace(PrintStream out, StackTraceElement[] stackTrace) - { - for (int i = 2; i < stackTrace.length; i++) - { - StackTraceElement stackTraceElement = stackTrace[i]; - out.println("\tat " + stackTraceElement); //$NON-NLS-1$ - } - } - - public static void printStackTrace(StackTraceElement[] stackTrace) - { - printStackTrace(System.err, stackTrace); - } - - public static Integer getHashCode(Object object) - { - try - { - return (Integer)HASH_CODE_METHOD.invoke(object, NO_ARGUMENTS); - } - catch (Exception ex) - { - IOUtil.print(ex); - } - - return 0; - } - - public static synchronized Long getID(Object object) - { - Long id = ids.get(object); - if (id == null) - { - id = ++lastID; - ids.put(object, id); - } - - return id; - } - - public static String getPackageName(Class extends Object> c) - { - if (c == null) - { - return null; - } - - return getPackageName(c.getName()); - } - - public static String getPackageName(String className) - { - if (className == null) - { - return null; - } - - int lastDot = className.lastIndexOf('.'); - if (lastDot != -1) - { - className = className.substring(0, lastDot); - } - - return className; - } - - public static String getSimpleName(Class extends Object> c) - { - if (c == null) - { - return null; - } - - return c.getSimpleName(); - } - - public static String getSimpleClassName(String name) - { - if (name == null) - { - return null; - } - - int lastDot = name.lastIndexOf('.'); - if (lastDot != -1) - { - name = name.substring(lastDot + 1); - } - - return name.replace('$', '.'); - } - - public static String getSimpleClassName(Object object) - { - if (object == null) - { - return null; - } - - return getSimpleName(object.getClass()); - } - - public static String getLabel(Object object) - { - if (object == null) - { - return null; - } - - String name = object.getClass().getSimpleName(); - if (name.length() == 0) - { - name = "anonymous"; //$NON-NLS-1$ - } - - return name + "@" + getID(object); //$NON-NLS-1$ - } - - public static void dump(Object object) - { - dump(object, ""); //$NON-NLS-1$ - } - - public static void dump(Object object, String prefix) - { - dump(object, prefix, IOUtil.OUT()); - } - - public static void dump(Object object, String prefix, PrintStream out) - { - out.print(toString(object, prefix)); - } - - @SuppressWarnings("unchecked") - public static Pair[] dumpToArray(Object object) - { - List fields = new ArrayList(); - collectFields(object.getClass(), fields); - Pair[] result = new Pair[fields.size()]; - int i = 0; - for (Field field : fields) - { - Object value = getValue(field, object); - result[i++] = new Pair(field, value); - } - - return result; - } - - public static Object instantiate(Map properties, String namespace, String classKey, - ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, - IllegalArgumentException, InvocationTargetException - { - if (namespace != null) - { - if (namespace.length() == 0) - { - namespace = null; - } - else if (!namespace.endsWith(NAMESPACE_SEPARATOR)) - { - namespace += NAMESPACE_SEPARATOR; - } - } - - String className = null; - Map values = new HashMap(); - for (Entry entry : properties.entrySet()) - { - if (entry.getKey() instanceof String) - { - String key = (String)entry.getKey(); - if (namespace != null) - { - if (key.startsWith(namespace)) - { - key = key.substring(namespace.length()); - } - else - { - continue; - } - } - - if (classKey.equals(key)) - { - Object classValue = entry.getValue(); - if (classValue instanceof String) - { - className = (String)classValue; - } - else - { - OM.LOG.warn("Value of classKey " + classKey + " is not a String"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - else - { - values.put(key, entry.getValue()); - } - } - } - - if (className == null) - { - throw new IllegalArgumentException("Properties do not contain a valid class name for key " + classKey); //$NON-NLS-1$ - } - - Class> c = classLoader.loadClass(className); - Object instance = c.newInstance(); - Method[] methods = c.getMethods(); - for (Method method : methods) - { - if (isSetter(method)) - { - String name = StringUtil.uncap(method.getName().substring(3)); - Object value = values.get(name); - if (value != null) - { - Class> type = method.getParameterTypes()[0]; - if (!type.isAssignableFrom(value.getClass())) - { - if (value instanceof String) - { - String str = (String)value; - value = null; - if (type.isAssignableFrom(Boolean.class)) - { - value = Boolean.parseBoolean(str); - } - else if (type.isAssignableFrom(Byte.class)) - { - value = Byte.parseByte(str); - } - else if (type.isAssignableFrom(Short.class)) - { - value = Short.parseShort(str); - } - else if (type.isAssignableFrom(Integer.class)) - { - value = Integer.parseInt(str); - } - else if (type.isAssignableFrom(Long.class)) - { - value = Long.parseLong(str); - } - else if (type.isAssignableFrom(Float.class)) - { - value = Float.parseFloat(str); - } - else if (type.isAssignableFrom(Double.class)) - { - value = Double.parseDouble(str); - } - } - else - { - value = null; - } - } - - if (value == null) - { - throw new IllegalArgumentException("Value of property " + name + " can not be assigned to type " //$NON-NLS-1$ //$NON-NLS-2$ - + type.getName()); - } - - method.invoke(instance, value); - } - } - } - - return instance; - } - - public static boolean isSetter(Method method) - { - return method.getParameterTypes().length == 1 && isSetterName(method.getName()); - } - - public static boolean isSetterName(String name) - { - return name.startsWith("set") && name.length() > 3 && Character.isUpperCase(name.charAt(3)); //$NON-NLS-1$ - } - - public static String toString(Object object) - { - return toString(object, " "); //$NON-NLS-1$ - } - - public static String toString(Object object, String prefix) - { - StringBuilder builder = new StringBuilder(); - builder.append(prefix); - builder.append(getLabel(object)); - builder.append(StringUtil.NL); - toString(object.getClass(), object, prefix, builder); - return builder.toString(); - } - - private static void toString(Class extends Object> segment, Object object, String prefix, StringBuilder builder) - { - if (segment == ROOT_CLASS || segment == Lifecycle.class) - { - return; - } - - // Recurse - toString(segment.getSuperclass(), object, prefix, builder); - - String segmentPrefix = segment == object.getClass() ? "" : getSimpleName(segment) + NAMESPACE_SEPARATOR; //$NON-NLS-1$ - for (Field field : segment.getDeclaredFields()) - { - if (field.isSynthetic()) - { - continue; - } - - if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS) - { - continue; - } - - if (field.getAnnotation(ExcludeFromDump.class) != null) - { - continue; - } - - builder.append(prefix); - builder.append(segmentPrefix); - builder.append(field.getName()); - builder.append(" = "); //$NON-NLS-1$ - - Object value = getValue(field, object); - if (value instanceof Map, ?>) - { - value = ((Map, ?>)value).entrySet(); - } - - if (value instanceof Collection>) - { - builder.append(StringUtil.NL); - Collection> collection = (Collection>)value; - Object[] array = collection.toArray(new Object[collection.size()]); - for (Object element : array) - { - builder.append(" "); //$NON-NLS-1$ - builder.append(element); - builder.append(StringUtil.NL); - } - } - else - { - builder.append(value); - builder.append(StringUtil.NL); - } - } - } - - private static Method lookupHashCodeMethod() - { - Method method; - - try - { - method = ROOT_CLASS.getMethod("hashCode", NO_PARAMETERS); //$NON-NLS-1$ - } - catch (Exception ex) - { - // This can really not happen - throw new AssertionError(); - } - - if (!method.isAccessible()) - { - method.setAccessible(true); - } - - return method; - } - - /** - * Annotates fields that are to be skipped in {@link ReflectUtil#collectFields(Class, List) - * ReflectUtil.collectFields()} and {@link ReflectUtil#toString(Object) ReflectUtil.toString()}. - * - * @author Eike Stepper - * @apiviz.exclude - */ - @Retention(RetentionPolicy.RUNTIME) - @Target(ElementType.FIELD) - public @interface ExcludeFromDump - { - } -} +/* + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, 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.internal.util.bundle.OM; +import org.eclipse.net4j.util.collection.Pair; +import org.eclipse.net4j.util.io.IOUtil; +import org.eclipse.net4j.util.lifecycle.Lifecycle; + +import java.io.PrintStream; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.WeakHashMap; + +/** + * Various static helper methods for dealing with Java reflection. + * + * @author Eike Stepper + */ +public final class ReflectUtil +{ + private static final String NAMESPACE_SEPARATOR = "."; //$NON-NLS-1$ + + public static final Class ROOT_CLASS = Object.class; + + public static final Class>[] NO_PARAMETERS = null; + + public static final Object[] NO_ARGUMENTS = null; + + private static final Method HASH_CODE_METHOD = lookupHashCodeMethod(); + + private static final Map ids = new WeakHashMap(); + + public static boolean DUMP_STATICS = false; + + private static long lastID; + + private ReflectUtil() + { + } + + public static Method getMethod(Class> c, String methodName, Class>... parameterTypes) + { + try + { + try + { + return c.getDeclaredMethod(methodName, parameterTypes); + } + catch (NoSuchMethodException ex) + { + Class> superclass = c.getSuperclass(); + if (superclass != null) + { + return getMethod(superclass, methodName, parameterTypes); + } + + throw ex; + } + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + public static Object invokeMethod(Method method, Object target, Object... arguments) + { + boolean accessible = method.isAccessible(); + if (!accessible) + { + method.setAccessible(true); + } + + try + { + return method.invoke(target, arguments); + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + finally + { + if (!accessible) + { + method.setAccessible(false); + } + } + } + + public static Field getField(Class> c, String fieldName) + { + try + { + try + { + return c.getDeclaredField(fieldName); + } + catch (NoSuchFieldException ex) + { + Class> superclass = c.getSuperclass(); + if (superclass != null) + { + return getField(superclass, fieldName); + } + + return null; + } + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + public static void collectFields(Class> c, List fields) + { + if (c == ROOT_CLASS) + { + return; + } + + // Recurse + collectFields(c.getSuperclass(), fields); + + try + { + Field[] declaredFields = c.getDeclaredFields(); + for (Field field : declaredFields) + { + if (field.isSynthetic()) + { + continue; + } + + if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS) + { + continue; + } + + if (field.getAnnotation(ExcludeFromDump.class) != null) + { + continue; + } + + fields.add(field); + } + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + public static Object getValue(Field field, Object target) + { + if (!field.isAccessible()) + { + field.setAccessible(true); + } + + try + { + return field.get(target); + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + public static void setValue(Field field, Object target, Object value) + { + if (!field.isAccessible()) + { + field.setAccessible(true); + } + + try + { + field.set(target, value); + } + catch (Exception ex) + { + throw WrappedException.wrap(ex); + } + } + + public static void printStackTrace(PrintStream out, StackTraceElement[] stackTrace) + { + for (int i = 2; i < stackTrace.length; i++) + { + StackTraceElement stackTraceElement = stackTrace[i]; + out.println("\tat " + stackTraceElement); //$NON-NLS-1$ + } + } + + public static void printStackTrace(StackTraceElement[] stackTrace) + { + printStackTrace(System.err, stackTrace); + } + + public static Integer getHashCode(Object object) + { + try + { + return (Integer)HASH_CODE_METHOD.invoke(object, NO_ARGUMENTS); + } + catch (Exception ex) + { + IOUtil.print(ex); + } + + return 0; + } + + public static synchronized Long getID(Object object) + { + Long id = ids.get(object); + if (id == null) + { + id = ++lastID; + ids.put(object, id); + } + + return id; + } + + public static String getPackageName(Class extends Object> c) + { + if (c == null) + { + return null; + } + + return getPackageName(c.getName()); + } + + public static String getPackageName(String className) + { + if (className == null) + { + return null; + } + + int lastDot = className.lastIndexOf('.'); + if (lastDot != -1) + { + className = className.substring(0, lastDot); + } + + return className; + } + + public static String getSimpleName(Class extends Object> c) + { + if (c == null) + { + return null; + } + + return c.getSimpleName(); + } + + public static String getSimpleClassName(String name) + { + if (name == null) + { + return null; + } + + int lastDot = name.lastIndexOf('.'); + if (lastDot != -1) + { + name = name.substring(lastDot + 1); + } + + return name.replace('$', '.'); + } + + public static String getSimpleClassName(Object object) + { + if (object == null) + { + return null; + } + + return getSimpleName(object.getClass()); + } + + public static String getLabel(Object object) + { + if (object == null) + { + return null; + } + + String name = object.getClass().getSimpleName(); + if (name.length() == 0) + { + name = "anonymous"; //$NON-NLS-1$ + } + + return name + "@" + getID(object); //$NON-NLS-1$ + } + + public static void dump(Object object) + { + dump(object, ""); //$NON-NLS-1$ + } + + public static void dump(Object object, String prefix) + { + dump(object, prefix, IOUtil.OUT()); + } + + public static void dump(Object object, String prefix, PrintStream out) + { + out.print(toString(object, prefix)); + } + + @SuppressWarnings("unchecked") + public static Pair[] dumpToArray(Object object) + { + List fields = new ArrayList(); + collectFields(object.getClass(), fields); + Pair[] result = new Pair[fields.size()]; + int i = 0; + for (Field field : fields) + { + Object value = getValue(field, object); + result[i++] = new Pair(field, value); + } + + return result; + } + + public static Object instantiate(Map properties, String namespace, String classKey, + ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException + { + if (namespace != null) + { + if (namespace.length() == 0) + { + namespace = null; + } + else if (!namespace.endsWith(NAMESPACE_SEPARATOR)) + { + namespace += NAMESPACE_SEPARATOR; + } + } + + String className = null; + Map values = new HashMap(); + for (Entry entry : properties.entrySet()) + { + if (entry.getKey() instanceof String) + { + String key = (String)entry.getKey(); + if (namespace != null) + { + if (key.startsWith(namespace)) + { + key = key.substring(namespace.length()); + } + else + { + continue; + } + } + + if (classKey.equals(key)) + { + Object classValue = entry.getValue(); + if (classValue instanceof String) + { + className = (String)classValue; + } + else + { + OM.LOG.warn("Value of classKey " + classKey + " is not a String"); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + else + { + values.put(key, entry.getValue()); + } + } + } + + if (className == null) + { + throw new IllegalArgumentException("Properties do not contain a valid class name for key " + classKey); //$NON-NLS-1$ + } + + Class> c = classLoader.loadClass(className); + Object instance = c.newInstance(); + Method[] methods = c.getMethods(); + for (Method method : methods) + { + if (isSetter(method)) + { + String name = StringUtil.uncap(method.getName().substring(3)); + Object value = values.get(name); + if (value != null) + { + Class> type = method.getParameterTypes()[0]; + if (!type.isAssignableFrom(value.getClass())) + { + if (value instanceof String) + { + String str = (String)value; + value = null; + if (type.isAssignableFrom(Boolean.class)) + { + value = Boolean.parseBoolean(str); + } + else if (type.isAssignableFrom(Byte.class)) + { + value = Byte.parseByte(str); + } + else if (type.isAssignableFrom(Short.class)) + { + value = Short.parseShort(str); + } + else if (type.isAssignableFrom(Integer.class)) + { + value = Integer.parseInt(str); + } + else if (type.isAssignableFrom(Long.class)) + { + value = Long.parseLong(str); + } + else if (type.isAssignableFrom(Float.class)) + { + value = Float.parseFloat(str); + } + else if (type.isAssignableFrom(Double.class)) + { + value = Double.parseDouble(str); + } + } + else + { + value = null; + } + } + + if (value == null) + { + throw new IllegalArgumentException("Value of property " + name + " can not be assigned to type " //$NON-NLS-1$ //$NON-NLS-2$ + + type.getName()); + } + + method.invoke(instance, value); + } + } + } + + return instance; + } + + public static boolean isSetter(Method method) + { + return method.getParameterTypes().length == 1 && isSetterName(method.getName()); + } + + public static boolean isSetterName(String name) + { + return name.startsWith("set") && name.length() > 3 && Character.isUpperCase(name.charAt(3)); //$NON-NLS-1$ + } + + public static String toString(Object object) + { + return toString(object, " "); //$NON-NLS-1$ + } + + public static String toString(Object object, String prefix) + { + StringBuilder builder = new StringBuilder(); + builder.append(prefix); + builder.append(getLabel(object)); + builder.append(StringUtil.NL); + toString(object.getClass(), object, prefix, builder); + return builder.toString(); + } + + private static void toString(Class extends Object> segment, Object object, String prefix, StringBuilder builder) + { + if (segment == ROOT_CLASS || segment == Lifecycle.class) + { + return; + } + + // Recurse + toString(segment.getSuperclass(), object, prefix, builder); + + String segmentPrefix = segment == object.getClass() ? "" : getSimpleName(segment) + NAMESPACE_SEPARATOR; //$NON-NLS-1$ + for (Field field : segment.getDeclaredFields()) + { + if (field.isSynthetic()) + { + continue; + } + + if ((field.getModifiers() & Modifier.STATIC) != 0 && !DUMP_STATICS) + { + continue; + } + + if (field.getAnnotation(ExcludeFromDump.class) != null) + { + continue; + } + + builder.append(prefix); + builder.append(segmentPrefix); + builder.append(field.getName()); + builder.append(" = "); //$NON-NLS-1$ + + Object value = getValue(field, object); + if (value instanceof Map, ?>) + { + value = ((Map, ?>)value).entrySet(); + } + + if (value instanceof Collection>) + { + builder.append(StringUtil.NL); + Collection> collection = (Collection>)value; + Object[] array = collection.toArray(new Object[collection.size()]); + for (Object element : array) + { + builder.append(" "); //$NON-NLS-1$ + builder.append(element); + builder.append(StringUtil.NL); + } + } + else + { + builder.append(value); + builder.append(StringUtil.NL); + } + } + } + + private static Method lookupHashCodeMethod() + { + Method method; + + try + { + method = ROOT_CLASS.getMethod("hashCode", NO_PARAMETERS); //$NON-NLS-1$ + } + catch (Exception ex) + { + // This can really not happen + throw new AssertionError(); + } + + if (!method.isAccessible()) + { + method.setAccessible(true); + } + + return method; + } + + /** + * Annotates fields that are to be skipped in {@link ReflectUtil#collectFields(Class, List) + * ReflectUtil.collectFields()} and {@link ReflectUtil#toString(Object) ReflectUtil.toString()}. + * + * @author Eike Stepper + * @apiviz.exclude + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface ExcludeFromDump + { + } +} 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 30806f9e02..3fb7bdd0a1 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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. - * - * Pattern description: - * - * * matches 0 or more characters - * ? matches a single character - * [...] matches a set and/or range of characters - * \ escapes the following character - * - * - * @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. - * - * Pattern description: - * - * * matches 0 or more characters - * ? matches a single character - * [...] matches a set and/or range of characters - * \ escapes the following character - * - * - * @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. + * + * Pattern description: + * + * * matches 0 or more characters + * ? matches a single character + * [...] matches a set and/or range of characters + * \ escapes the following character + * + * + * @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. + * + * Pattern description: + * + * * matches 0 or more characters + * ? matches a single character + * [...] matches a set and/or range of characters + * \ escapes the following character + * + * + * @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 1ac1fa0167..82a1f8e45a 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,5 +1,5 @@ /* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at 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 64f09560bf..7ee8967faf 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 00b6908a0a..c4de6167a0 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 extends Worker implements ICache -{ - private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class); - - private ICacheMonitor cacheMonitor; - - private ICacheProbe cacheProbe; - - private ReferenceQueue referenceQueue = new ReferenceQueue(); - - public Cache() - { - } - - public ICacheMonitor getCacheMonitor() - { - return cacheMonitor; - } - - public void setCacheMonitor(ICacheMonitor cacheMonitor) - { - this.cacheMonitor = cacheMonitor; - } - - protected ICacheProbe getCacheProbe() - { - return cacheProbe; - } - - protected ReferenceQueue 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 extends Worker implements ICache +{ + private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, Cache.class); + + private ICacheMonitor cacheMonitor; + + private ICacheProbe cacheProbe; + + private ReferenceQueue referenceQueue = new ReferenceQueue(); + + public Cache() + { + } + + public ICacheMonitor getCacheMonitor() + { + return cacheMonitor; + } + + public void setCacheMonitor(ICacheMonitor cacheMonitor) + { + this.cacheMonitor = cacheMonitor; + } + + protected ICacheProbe getCacheProbe() + { + return cacheProbe; + } + + protected ReferenceQueue 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 9ad020d686..f4dc24ce36 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 registrations = new HashMap(); - - 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 registrations = new HashMap(); + + 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 a6b8fe976f..43e5f0edf2 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 d6a6c08c1b..a341c9fe97 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 8fd6c44e8d..43c55009fa 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 elementCount 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 elementCount 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 d795c7bc3a..f8c9aefb6d 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 GREEN indicates that the system is operating normally and enough free memory is available so - * that caches are free to cache additional elements. - */ - GREEN, - - /** - * Condition YELLOW 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 RED 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 GREEN indicates that the system is operating normally and enough free memory is available so + * that caches are free to cache additional elements. + */ + GREEN, + + /** + * Condition YELLOW 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 RED 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 5f82e55068..9ebebc683e 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 b2919ed265..e4c9c93074 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 3a95717d77..7cc730a3f2 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 2883bb64d8..01a228948d 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 1049573dce..dc74f11f66 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,5 +1,5 @@ /* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at 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 897a487bb0..37a4ffd0ed 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,5 +1,5 @@ /* - * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, Germany) and others. + * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at 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 9f8b282702..c7ecb0b8b9 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 implements Iterator -{ - 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 implements Iterator +{ + 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 6c5867de5c..8d04d15bff 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 - 2011 Eike Stepper (Berlin, Germany) and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, 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 -{ - private Map map1 = new HashMap(); - - private Map map2 = new HashMap(); - - 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 +{ + private Map
- * Pattern description: - *
*
?
[...]
\
+ * Pattern description: + *