From fe90cd66048ff3d7951526ae71f2bf75eb4d44b9 Mon Sep 17 00:00:00 2001 From: brinn <brinn> Date: Wed, 19 Mar 2008 19:16:41 +0000 Subject: [PATCH] change: CISD formatting conventions: max line length 120 -> 100 (mass formatting) SVN: 4950 --- .../cisd/ant/common/DummyProjectHandler.java | 4 +- .../ant/common/EclipseClasspathReader.java | 13 +- .../FileBaseEclipseClasspathLocation.java | 4 +- .../ant/common/IEclipseClasspathLocation.java | 4 +- .../cisd/ant/common/IProjectHandler.java | 13 +- .../ant/common/RecursiveProjectTraverser.java | 9 +- .../TextBasedEclipseClasspathLocation.java | 5 +- .../systemsx/cisd/ant/task/RecursiveJar.java | 10 +- .../ant/task/SetEclipseClasspathTask.java | 10 +- .../BuildJavaSubprojectsTask.java | 2 +- .../AntTaskSimpleLoggerAdapter.java | 13 +- .../GatherRevisionAndVersionTask.java | 17 +- .../cisd/ant/task/subversion/ISVNActions.java | 3 +- .../ant/task/subversion/ISVNCheckout.java | 3 +- .../cisd/ant/task/subversion/ISVNCopy.java | 4 +- .../cisd/ant/task/subversion/ISVNInfo.java | 4 +- .../subversion/ISVNProjectPathProvider.java | 4 +- .../cisd/ant/task/subversion/SVNActions.java | 46 +++-- .../task/subversion/SVNBranchAndTagTask.java | 73 +++++--- .../cisd/ant/task/subversion/SVNCheckout.java | 4 +- .../SVNDependentProjectsCollector.java | 10 +- .../ant/task/subversion/SVNException.java | 4 +- .../ant/task/subversion/SVNInfoRecord.java | 121 +++++++------ .../subversion/SVNInfoRecordExtractor.java | 39 ++-- .../ant/task/subversion/SVNItemStatus.java | 29 +-- .../subversion/SVNRecursiveCheckoutTask.java | 16 +- .../SVNRepositoryProjectContext.java | 38 ++-- .../ant/task/subversion/SVNUtilities.java | 46 +++-- .../subversion/SVNWCProjectPathProvider.java | 15 +- .../ant/task/SetEclipseClasspathTaskTest.java | 46 +++-- .../GatherRevisionAndVersionTaskTest.java | 62 ++++--- .../subversion/SVNBranchAndTagTaskTest.java | 139 ++++++++------ .../SVNDependentProjectCollectorTest.java | 127 ++++++++----- .../SVNInfoRecordExtractorTest.java | 106 +++++------ .../SVNRecursiveCheckoutTaskTest.java | 46 +++-- .../SVNRepositoryProjectContextTest.java | 43 +++-- .../ant/task/subversion/SVNUtilitiesTest.java | 14 +- .../SVNWCProjectPathProviderTest.java | 28 +-- .../NullAuthenticationService.java | 4 +- .../cisd/authentication/Principal.java | 16 +- .../crowd/CrowdAuthenticationService.java | 96 ++++++---- .../crowd/IRequestExecutor.java | 4 +- .../crowd/CrowdAuthenticationServiceTest.java | 77 +++++--- .../crowd/RealCrowdAuthenticationTest.java | 10 +- .../cisd/bds/AbstractFormattedData.java | 7 +- .../java/ch/systemsx/cisd/bds/Constants.java | 2 +- .../cisd/bds/DataStructureLoader.java | 10 +- .../systemsx/cisd/bds/DataStructureV1_0.java | 20 +- .../cisd/bds/ExperimentIdentifier.java | 9 +- .../cisd/bds/ExperimentRegistratorDate.java | 3 +- .../java/ch/systemsx/cisd/bds/Factory.java | 23 ++- .../java/ch/systemsx/cisd/bds/Format.java | 3 +- .../systemsx/cisd/bds/FormatParameters.java | 12 +- .../ch/systemsx/cisd/bds/FormatStore.java | 7 +- .../cisd/bds/FormattedDataContext.java | 3 +- .../cisd/bds/FormattedDataFactory.java | 16 +- .../ch/systemsx/cisd/bds/IAnnotations.java | 2 - .../ch/systemsx/cisd/bds/IDataStructure.java | 3 +- .../cisd/bds/IFormatParameterFactory.java | 41 +++-- .../ch/systemsx/cisd/bds/IFormattedData.java | 5 +- .../ch/systemsx/cisd/bds/IHasVersion.java | 2 +- .../systemsx/cisd/bds/MeasurementEntity.java | 3 +- .../systemsx/cisd/bds/UnknownFormatV1_0.java | 4 +- .../java/ch/systemsx/cisd/bds/Utilities.java | 14 +- .../java/ch/systemsx/cisd/bds/Version.java | 3 +- .../bds/exception/DataStructureException.java | 7 +- .../cisd/bds/handler/ChecksumHandler.java | 32 ++-- .../bds/handler/MD5ChecksumCalculator.java | 1 - .../cisd/bds/handler/MappingFileHandler.java | 17 +- .../ch/systemsx/cisd/bds/hcs/Channel.java | 3 +- .../ch/systemsx/cisd/bds/hcs/ChannelList.java | 3 +- .../cisd/bds/hcs/FormatParameterFactory.java | 3 +- .../ch/systemsx/cisd/bds/hcs/Geometry.java | 3 +- .../cisd/bds/hcs/HCSImageAnnotations.java | 19 +- .../cisd/bds/hcs/HCSImageFormatV1_0.java | 4 +- .../cisd/bds/hcs/HCSImageFormattedData.java | 64 ++++--- .../cisd/bds/hcs/IHCSImageFormattedData.java | 8 +- .../ch/systemsx/cisd/bds/hcs/Location.java | 3 +- .../systemsx/cisd/bds/storage/IDirectory.java | 3 +- .../ch/systemsx/cisd/bds/storage/ILink.java | 2 +- .../systemsx/cisd/bds/storage/IStorage.java | 9 +- .../cisd/bds/storage/NodeFilters.java | 7 +- .../bds/storage/filesystem/AbstractNode.java | 12 +- .../bds/storage/filesystem/Directory.java | 30 +-- .../cisd/bds/storage/filesystem/File.java | 11 +- .../bds/storage/filesystem/FileStorage.java | 6 +- .../cisd/bds/storage/filesystem/Link.java | 3 +- .../bds/storage/filesystem/NodeFactory.java | 10 +- .../cisd/bds/storage/hdf5/HDF5Storage.java | 4 +- .../cisd/bds/DataStructureFactoryTest.java | 9 +- .../cisd/bds/DataStructureLoaderTest.java | 3 +- .../cisd/bds/DataStructureTestV1_0.java | 41 +++-- .../ch/systemsx/cisd/bds/UtilitiesTest.java | 3 +- .../bds/handler/MappingFileHandlerTest.java | 13 +- .../bds/hcs/HCSDataStructureTestV1_0.java | 16 +- .../bds/hcs/HCSImageFormattedDataTest.java | 21 ++- .../cisd/bds/hcs/PlateGeometryTest.java | 3 +- .../cisd/bds/hcs/WellGeometryTest.java | 3 +- .../cisd/bds/storage/filesystem/FileTest.java | 6 +- .../storage/filesystem/NodeFactoryTest.java | 4 +- .../ch/systemsx/cisd/common/Constants.java | 7 +- .../java/ch/systemsx/cisd/common/Script.java | 10 +- .../AbstractCollectionDecorator.java | 2 +- .../cisd/common/collections/CollectionIO.java | 28 +-- .../common/collections/CollectionStyle.java | 4 +- .../common/collections/CollectionUtils.java | 30 +-- .../collections/FilteredCollection.java | 3 +- .../common/collections/IKeyExtractor.java | 2 +- .../cisd/common/collections/TableMap.java | 6 +- .../collections/TableMapNonUniqueKey.java | 5 +- .../compression/file/CompressionWorker.java | 19 +- .../common/compression/file/Compressor.java | 28 ++- .../compression/file/ICompressionMethod.java | 2 +- .../file/InPlaceCompressionMethod.java | 29 +-- .../compression/tiff/TiffCompressor.java | 3 +- .../tiff/TiffZipCompressionMethod.java | 23 ++- .../concurrent/ConcurrencyUtilities.java | 20 +- .../cisd/common/converter/ConverterPool.java | 3 +- .../cisd/common/db/DBRestrictionParser.java | 41 +++-- .../cisd/common/db/ISequenceNameMapper.java | 2 +- .../common/db/ISqlScriptExecutionLogger.java | 6 +- .../cisd/common/db/ISqlScriptExecutor.java | 3 +- .../common/db/OracleSequencerHandler.java | 2 +- .../cisd/common/db/SQLCommandTokenizer.java | 18 +- .../cisd/common/db/SQLStateUtils.java | 2 +- .../cisd/common/db/SqlUnitTestRunner.java | 63 ++++--- .../common/db/StandardSequenceNameMapper.java | 4 +- .../ConfigurationFailureException.java | 3 +- .../EnvironmentFailureException.java | 3 +- .../common/exceptions/HighLevelException.java | 4 +- .../exceptions/InvalidSessionException.java | 1 - .../exceptions/NotImplementedException.java | 4 +- .../RetriableEnvironmentFailureException.java | 7 +- .../cisd/common/exceptions/Status.java | 4 +- .../cisd/common/exceptions/StatusFlag.java | 4 +- .../exceptions/UserFailureException.java | 3 +- .../systemsx/cisd/common/io/ILinePrinter.java | 2 +- .../cisd/common/io/SimpleLinePrinter.java | 8 +- .../cisd/common/logging/ConsoleLogger.java | 2 +- .../cisd/common/logging/ISimpleLogger.java | 4 +- .../cisd/common/logging/LogFactory.java | 3 +- .../cisd/common/logging/LogInitializer.java | 3 +- .../common/logging/LogInvocationHandler.java | 9 +- .../common/logging/LoggingContextHandler.java | 2 - .../cisd/common/mail/IMailClient.java | 3 +- .../systemsx/cisd/common/mail/MailClient.java | 37 ++-- .../parser/AbstractParserObjectFactory.java | 28 +-- .../cisd/common/parser/BeanAnalyzer.java | 21 ++- .../parser/ColumnSizeMismatchException.java | 8 +- .../parser/DefaultAliasPropertyMapper.java | 14 +- .../common/parser/DefaultLineTokenizer.java | 6 +- .../cisd/common/parser/DefaultParser.java | 4 +- .../common/parser/DefaultPropertyMapper.java | 10 +- .../cisd/common/parser/HeaderLineFilter.java | 4 +- .../common/parser/IAliasPropertyMapper.java | 2 +- .../cisd/common/parser/ILineTokenizer.java | 2 +- .../systemsx/cisd/common/parser/IParser.java | 4 +- .../common/parser/IParserObjectFactory.java | 3 +- .../parser/IParserObjectFactoryFactory.java | 3 +- .../cisd/common/parser/IPropertyMapper.java | 3 +- .../parser/IndexOutOfBoundsException.java | 3 +- .../ch/systemsx/cisd/common/parser/Line.java | 3 +- .../cisd/common/parser/ParserUtilities.java | 9 +- .../cisd/common/parser/ParsingException.java | 3 +- .../cisd/common/parser/TabFileLoader.java | 9 +- .../parser/UnmatchedPropertiesException.java | 12 +- .../cisd/common/process/CleanUpCallable.java | 1 - .../cisd/common/process/CleanUpRegistry.java | 3 +- .../common/process/FileRenamingProcess.java | 13 +- .../cisd/common/process/ICleanUpRegistry.java | 4 +- .../process/ProcessExecutionHelper.java | 60 +++--- .../cisd/common/process/ProcessResult.java | 21 ++- .../common/test/InterfaceForRMIChecker.java | 28 +-- .../common/utilities/AbstractHashable.java | 4 +- .../cisd/common/utilities/BeanUtils.java | 126 ++++++++----- .../cisd/common/utilities/ClassUtils.java | 29 +-- .../utilities/DirectoryScanningTimerTask.java | 21 ++- .../cisd/common/utilities/ExceptionUtils.java | 9 +- .../common/utilities/ExtendedProperties.java | 6 +- .../cisd/common/utilities/FileUtilities.java | 111 +++++++----- .../cisd/common/utilities/FileWatcher.java | 6 +- .../utilities/FileWatcherSynchronizer.java | 24 ++- .../cisd/common/utilities/IExitHandler.java | 4 +- .../cisd/common/utilities/ITriggerable.java | 6 +- .../ModifiedShortPrefixToStringStyle.java | 17 +- .../utilities/NamePrefixFileFilter.java | 4 +- .../cisd/common/utilities/OSUtilities.java | 14 +- .../common/utilities/PasswordGenerator.java | 20 +- .../common/utilities/PathPrefixPrepender.java | 14 +- .../utilities/RecursiveHardLinkMaker.java | 62 ++++--- .../common/utilities/RegexFileFilter.java | 3 +- .../common/utilities/StringUtilities.java | 63 ++++--- .../utilities/SynchronizationMonitor.java | 6 +- .../cisd/common/utilities/Template.java | 89 +++++---- .../cisd/common/utilities/TimerHelper.java | 4 +- .../common/utilities/TriggeringTimerTask.java | 14 +- .../common/collections/CollectionIOTest.java | 10 +- .../collections/CollectionUtilsTest.java | 6 +- .../common/collections/FilteredListTest.java | 2 +- .../collections/TableMapNonUniqueKeyTest.java | 33 ++-- .../cisd/common/collections/TableMapTest.java | 8 +- .../collections/ValidatorUtilsTest.java | 12 +- .../file/CompressionWorkerTest.java | 4 +- .../concurrent/ConcurrencyUtilitiesTest.java | 85 ++++----- .../common/db/DBRestrictionParserTest.java | 48 +++-- .../common/db/SQLCommandTokenizerTest.java | 6 +- .../cisd/common/db/SqlUnitTestRunnerTest.java | 126 +++++++------ .../exceptions/UserFailureExceptionTest.java | 12 +- .../common/logging/LogMonitoringAppender.java | 13 +- .../cisd/common/mail/MailClientTest.java | 13 +- .../AbstractParserObjectFactoryTest.java | 17 +- .../cisd/common/parser/DefaultParserTest.java | 18 +- .../common/parser/HeaderLineFilterTest.java | 31 ++-- .../common/parser/ParserUtilitiesTest.java | 10 +- .../cisd/common/parser/TabFileLoaderTest.java | 8 +- .../process/ProcessExecutionHelperTest.java | 53 +++--- .../test/InterfaceForRMICheckerTest.java | 90 +++++---- .../test/StoringUncaughtExceptionHandler.java | 4 +- .../cisd/common/utilities/BeanUtilsTest.java | 66 ++++--- .../cisd/common/utilities/ClassUtilsTest.java | 26 ++- .../DirectoryScanningTimerTaskTest.java | 51 ++++-- .../common/utilities/ExceptionUtilsTest.java | 52 +++--- .../FileUtilitiesDeleteRecursivelyTest.java | 3 +- .../FileUtilitiesLastChangedTest.java | 35 ++-- .../common/utilities/FileUtilitiesTest.java | 43 +++-- .../common/utilities/FileWatcherTest.java | 12 +- .../utilities/NamePrefixFileFilterTest.java | 6 +- .../common/utilities/OSUtilitiesTest.java | 3 +- .../utilities/PathPrefixPrependerTest.java | 11 +- .../utilities/RecursiveHardLinkMakerTest.java | 6 +- .../common/utilities/RegexFileFilterTest.java | 41 +++-- .../common/utilities/StringUtilitiesTest.java | 5 +- .../cisd/common/utilities/TemplateTest.java | 28 ++- .../ch/systemsx/cisd/datamover/DataMover.java | 26 ++- .../cisd/datamover/IncomingProcessor.java | 36 ++-- .../cisd/datamover/LocalProcessor.java | 37 ++-- .../java/ch/systemsx/cisd/datamover/Main.java | 36 ++-- .../systemsx/cisd/datamover/Parameters.java | 75 +++++--- .../ch/systemsx/cisd/datamover/SelfTest.java | 18 +- .../filesystem/FileStoreFactory.java | 6 +- .../filesystem/FileSysOperationsFactory.java | 19 +- .../RemoteMonitoredMoverFactory.java | 10 +- .../filesystem/RetryingPathMover.java | 26 ++- .../filesystem/RetryingPathRemover.java | 15 +- .../datamover/filesystem/intf/FileStore.java | 15 +- .../filesystem/intf/IExtendedFileStore.java | 2 +- .../datamover/filesystem/intf/IFileStore.java | 2 +- .../intf/IFileSysOperationsFactory.java | 1 - .../datamover/filesystem/intf/IPathMover.java | 3 +- .../intf/IRecoverableTimerTaskFactory.java | 2 +- .../remote/CopyActivityMonitor.java | 71 +++++--- .../filesystem/remote/RemotePathMover.java | 87 +++++---- .../filesystem/remote/rsync/RsyncCopier.java | 80 ++++---- .../remote/rsync/RsyncVersionChecker.java | 18 +- .../filesystem/store/FileStoreLocal.java | 33 ++-- .../cisd/datamover/utils/LocalBufferDirs.java | 4 +- .../utils/QuietPeriodFileFilter.java | 17 +- .../ch/systemsx/cisd/datamover/MainTest.java | 110 ++++++----- .../cisd/datamover/ParametersTest.java | 37 ++-- .../systemsx/cisd/datamover/SelfTestTest.java | 24 ++- .../remote/CopyActivityMonitorTest.java | 44 +++-- .../remote/rsync/RsyncCopierTest.java | 25 ++- .../utils/QuietPeriodFileFilterTest.java | 9 +- .../cisd/dbmigration/DBMigrationEngine.java | 43 +++-- .../cisd/dbmigration/DBScriptFormatter.java | 89 ++++----- .../cisd/dbmigration/DBUtilities.java | 7 +- .../DatabaseConfigurationContext.java | 6 +- .../cisd/dbmigration/DatabaseEngine.java | 19 +- .../dbmigration/DatabaseVersionLogDAO.java | 89 +++++---- .../cisd/dbmigration/IDataSourceFactory.java | 2 +- .../cisd/dbmigration/IDatabaseAdminDAO.java | 14 +- .../dbmigration/IDatabaseVersionLogDAO.java | 9 +- .../systemsx/cisd/dbmigration/LogEntry.java | 41 +++-- .../cisd/dbmigration/MassUploadFileType.java | 10 +- .../cisd/dbmigration/SqlScriptExecutor.java | 20 +- .../cisd/dbmigration/SqlScriptProvider.java | 12 +- .../cisd/dbmigration/h2/H2AdminDAO.java | 26 ++- .../cisd/dbmigration/h2/H2MassUploader.java | 50 +++-- .../dbmigration/h2/H2StoredProcedures.java | 10 +- .../postgresql/DumpPreparator.java | 37 ++-- .../postgresql/PostgreSQLAdminDAO.java | 36 ++-- .../postgresql/PostgreSQLDAOFactory.java | 5 +- .../postgresql/PostgreSQLMassUploader.java | 44 +++-- .../dbmigration/DBMigrationEngineTest.java | 171 +++++++++++------- .../cisd/dbmigration/DBUtilitiesTest.java | 12 +- .../dbmigration/SqlScriptExecutorTest.java | 36 ++-- .../dbmigration/SqlScriptProviderTest.java | 50 +++-- .../h2/H2TestStoredProcedures.java | 10 +- .../postgresql/DumpPreparatorTest.java | 161 ++++++++--------- 289 files changed, 3658 insertions(+), 2603 deletions(-) diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/DummyProjectHandler.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/DummyProjectHandler.java index c13a5c9af9a..1c431e3bc3a 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/DummyProjectHandler.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/DummyProjectHandler.java @@ -17,14 +17,12 @@ package ch.systemsx.cisd.ant.common; /** - * - * * @author felmer */ public class DummyProjectHandler implements IProjectHandler { public static final IProjectHandler INSTANCE = new DummyProjectHandler(); - + public IProjectHandler createHandler(EclipseClasspathEntry entry) { return INSTANCE; diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/EclipseClasspathReader.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/EclipseClasspathReader.java index 01c2e6b649e..b38b8b3b8d3 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/EclipseClasspathReader.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/EclipseClasspathReader.java @@ -34,7 +34,7 @@ public class EclipseClasspathReader { /** Name of the Eclipse classpath file. */ public static final String CLASSPATH_FILE = ".classpath"; - + private static final String CLASSPATH = "classpath"; private static final String PATH_ATTRIBUTE = "path"; @@ -46,14 +46,15 @@ public class EclipseClasspathReader /** * Reads from the specified Eclipse classpath file all classpathentry elements. */ - public static List<EclipseClasspathEntry> readClasspathEntries(IEclipseClasspathLocation location) + public static List<EclipseClasspathEntry> readClasspathEntries( + IEclipseClasspathLocation location) { String displayableLocation = location.getDisplayableLocation(); Node root = location.getDocument().getChildNodes().item(0); if (CLASSPATH.equalsIgnoreCase(root.getNodeName()) == false) { - throw new IllegalArgumentException("Root element of '" + displayableLocation + "' is not '" + CLASSPATH - + "'."); + throw new IllegalArgumentException("Root element of '" + displayableLocation + + "' is not '" + CLASSPATH + "'."); } NodeList children = root.getChildNodes(); List<Element> elements = new ArrayList<Element>(); @@ -85,8 +86,8 @@ public class EclipseClasspathReader } catch (Exception e) { - throw new IllegalArgumentException((i + 1) + ". element of '" + displayableLocation + "': " - + e.getMessage(), e); + throw new IllegalArgumentException((i + 1) + ". element of '" + displayableLocation + + "': " + e.getMessage(), e); } } return entries; diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/FileBaseEclipseClasspathLocation.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/FileBaseEclipseClasspathLocation.java index 2fb8db3130f..7bbf481f603 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/FileBaseEclipseClasspathLocation.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/FileBaseEclipseClasspathLocation.java @@ -24,8 +24,6 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; /** - * - * * @author felmer */ public class FileBaseEclipseClasspathLocation implements IEclipseClasspathLocation @@ -37,7 +35,7 @@ public class FileBaseEclipseClasspathLocation implements IEclipseClasspathLocati assert classpathFile != null; this.classpathFile = classpathFile; } - + public String getDisplayableLocation() { return classpathFile.getPath(); diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IEclipseClasspathLocation.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IEclipseClasspathLocation.java index 4fb38cbdff6..6ea219997eb 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IEclipseClasspathLocation.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IEclipseClasspathLocation.java @@ -19,13 +19,11 @@ package ch.systemsx.cisd.ant.common; import org.w3c.dom.Document; /** - * - * * @author felmer */ public interface IEclipseClasspathLocation { public Document getDocument(); - + public String getDisplayableLocation(); } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IProjectHandler.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IProjectHandler.java index 55f96e36201..591ac3044ee 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IProjectHandler.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/IProjectHandler.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.ant.common; /** * Call-back interface used by {@link RecursiveProjectTraverser} for traversing project dependency graphs. - * + * * @author felmer */ public interface IProjectHandler @@ -27,27 +27,26 @@ public interface IProjectHandler * Handle project when entering its graph vertex. */ public void handleOnEntering(); - + /** * Handle project when entering its graph vertex. */ public void handleOnLeaving(); - + /** * Returns the Eclipse classpath location for the correcponding project vertex. * * @return <code>null</code> if this project has no Eclipse classpath location. */ public IEclipseClasspathLocation createLocation(); - + /** * Handles specified entry. */ public void handleEntry(EclipseClasspathEntry entry); - + /** - * Creates a new project handler based on the specified entry. - * Implementations should never return <code>null</code>. + * Creates a new project handler based on the specified entry. Implementations should never return <code>null</code>. */ public IProjectHandler createHandler(EclipseClasspathEntry entry); } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/RecursiveProjectTraverser.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/RecursiveProjectTraverser.java index 6fe0f59f868..1f21ddfb8f6 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/RecursiveProjectTraverser.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/RecursiveProjectTraverser.java @@ -21,8 +21,6 @@ import java.util.List; import java.util.Set; /** - * - * * @author felmer */ public class RecursiveProjectTraverser @@ -31,8 +29,9 @@ public class RecursiveProjectTraverser { traverse(projectHandler, new HashSet<EclipseClasspathEntry>()); } - - private static void traverse(IProjectHandler projectHandler, Set<EclipseClasspathEntry> visitedEntries) + + private static void traverse(IProjectHandler projectHandler, + Set<EclipseClasspathEntry> visitedEntries) { projectHandler.handleOnEntering(); IEclipseClasspathLocation loc = projectHandler.createLocation(); @@ -50,6 +49,6 @@ public class RecursiveProjectTraverser } } projectHandler.handleOnLeaving(); - + } } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/TextBasedEclipseClasspathLocation.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/TextBasedEclipseClasspathLocation.java index b496737a19d..2ec80f51fdc 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/common/TextBasedEclipseClasspathLocation.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/common/TextBasedEclipseClasspathLocation.java @@ -24,13 +24,12 @@ import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; /** - * - * * @author felmer */ public class TextBasedEclipseClasspathLocation implements IEclipseClasspathLocation { private final String text; + private final String displayableLocation; public TextBasedEclipseClasspathLocation(String text, String displayableLocation) @@ -39,7 +38,7 @@ public class TextBasedEclipseClasspathLocation implements IEclipseClasspathLocat this.text = text; this.displayableLocation = displayableLocation == null ? "UNKNOWN" : displayableLocation; } - + public String getDisplayableLocation() { return displayableLocation; diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/RecursiveJar.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/RecursiveJar.java index d9f1acfd44b..0a2ee27ef24 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/RecursiveJar.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/RecursiveJar.java @@ -63,7 +63,8 @@ public class RecursiveJar extends Jar throw new BuildException("Base directory of fileset has to be a relative one."); } String subdir = path.substring(basePath.length()); - File subprojectDir = new File(new File(baseDir.getParentFile(), subProject), subdir); + File subprojectDir = + new File(new File(baseDir.getParentFile(), subProject), subdir); if (subprojectDir.exists()) { log("scan " + subprojectDir, Project.MSG_DEBUG); @@ -124,8 +125,8 @@ public class RecursiveJar extends Jar subprojectsAlreadySeen.add(subproject); jar.addFilesetPlain(new RelatedSubprojectFileSet(fileSet, subproject)); File subprojectDir = new File(subprojectsParent, subproject); - new SubprojectFileSetAppender(jar, fileSet, subprojectsParent, subprojectsAlreadySeen) - .execute(subprojectDir); + new SubprojectFileSetAppender(jar, fileSet, subprojectsParent, + subprojectsAlreadySeen).execute(subprojectDir); } } } @@ -142,7 +143,8 @@ public class RecursiveJar extends Jar { addFilesetPlain(set); File subprojectsParent = getProject().getBaseDir().getParentFile(); - SubprojectFileSetAppender appender = new SubprojectFileSetAppender(this, set, subprojectsParent); + SubprojectFileSetAppender appender = + new SubprojectFileSetAppender(this, set, subprojectsParent); appender.executeFor(this); } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTask.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTask.java index 8f1a9a334b8..32d56c9b01e 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTask.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTask.java @@ -64,10 +64,11 @@ public class SetEclipseClasspathTask extends Property } addProperty(propertyName, builder.toString()); } - + private final class ProjectHandler extends DummyProjectHandler { private final Set<File> files; + private final File projectBaseDir; ProjectHandler(Set<File> files, File projectBaseDir) @@ -75,7 +76,7 @@ public class SetEclipseClasspathTask extends Property this.files = files; this.projectBaseDir = projectBaseDir; } - + @Override public void handleEntry(EclipseClasspathEntry entry) { @@ -84,7 +85,7 @@ public class SetEclipseClasspathTask extends Property if (entry.getKind().equals(EclipseClasspathEntry.LIB_KIND)) { files.add(classpathElement); - } + } } @Override @@ -102,7 +103,8 @@ public class SetEclipseClasspathTask extends Property @Override public IEclipseClasspathLocation createLocation() { - File eclipseClasspathFile = new File(projectBaseDir, EclipseClasspathReader.CLASSPATH_FILE); + File eclipseClasspathFile = + new File(projectBaseDir, EclipseClasspathReader.CLASSPATH_FILE); if (eclipseClasspathFile.exists()) { return new FileBaseEclipseClasspathLocation(eclipseClasspathFile); diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subprojectbuilder/BuildJavaSubprojectsTask.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subprojectbuilder/BuildJavaSubprojectsTask.java index b6eb089cfb7..147f6aea48d 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subprojectbuilder/BuildJavaSubprojectsTask.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subprojectbuilder/BuildJavaSubprojectsTask.java @@ -38,7 +38,7 @@ public class BuildJavaSubprojectsTask extends Task @Override protected void handleAbsentsOfClasspathFile(File eclipseClasspathFile) { - log("No Eclipse " + EclipseClasspathReader.CLASSPATH_FILE + " file found in '" + log("No Eclipse " + EclipseClasspathReader.CLASSPATH_FILE + " file found in '" + eclipseClasspathFile.getParent() + "'."); } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/AntTaskSimpleLoggerAdapter.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/AntTaskSimpleLoggerAdapter.java index 61fe425110c..51268ee2e6e 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/AntTaskSimpleLoggerAdapter.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/AntTaskSimpleLoggerAdapter.java @@ -36,19 +36,20 @@ public class AntTaskSimpleLoggerAdapter implements ISimpleLogger { switch (level) { - case OFF: + case OFF: return Project.MSG_DEBUG; case TRACE: return Project.MSG_VERBOSE; - case DEBUG: + case DEBUG: return Project.MSG_DEBUG; - case INFO: + case INFO: return Project.MSG_INFO; - case WARN: + case WARN: return Project.MSG_WARN; - case ERROR: + case ERROR: return Project.MSG_ERR; - default: throw new IllegalArgumentException("Illegal log level " + level); + default: + throw new IllegalArgumentException("Illegal log level " + level); } } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTask.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTask.java index d78b42af0b2..bb0477f5b48 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTask.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTask.java @@ -109,7 +109,8 @@ public class GatherRevisionAndVersionTask extends Property } } } - checkFailure(versions, projectRevisions, dirtyProjects, minRevision, maxRevision, maxLastChangedRevision); + checkFailure(versions, projectRevisions, dirtyProjects, minRevision, maxRevision, + maxLastChangedRevision); setRevisionProperty(maxLastChangedRevision); setVersionProperty(versions); setCleanProperty(dirtyProjects); @@ -145,7 +146,8 @@ public class GatherRevisionAndVersionTask extends Property private Set<String> collectProjects(ISVNActions actions) { final ISVNProjectPathProvider pathProvider = createPathProvider(getProject().getBaseDir()); - return new SVNDependentProjectsCollector(pathProvider, actions).collectDependentProjectsFromClasspath(); + return new SVNDependentProjectsCollector(pathProvider, actions) + .collectDependentProjectsFromClasspath(); } private void setRevisionProperty(int maxLastChangedRevision) @@ -176,8 +178,8 @@ public class GatherRevisionAndVersionTask extends Property } } - private void checkFailure(HashSet<String> versions, StringBuilder projectRevisions, StringBuilder dirtyProjects, - int minRevision, int maxRevision, int lastChangedRevision) + private void checkFailure(HashSet<String> versions, StringBuilder projectRevisions, + StringBuilder dirtyProjects, int minRevision, int maxRevision, int lastChangedRevision) { if (failOnInconsistency && maxRevision != minRevision) { @@ -190,12 +192,13 @@ public class GatherRevisionAndVersionTask extends Property } if (failOnInconsistency && versions.size() > 1) { - throw new BuildException("Versions of local copies of the projects are inconsistent: " + versions); + throw new BuildException("Versions of local copies of the projects are inconsistent: " + + versions); } if (maxRevision < lastChangedRevision) { - throw new BuildException("Maximum revision < last changed revision: " + maxRevision + " < " - + lastChangedRevision); + throw new BuildException("Maximum revision < last changed revision: " + maxRevision + + " < " + lastChangedRevision); } } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNActions.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNActions.java index 274b3910ec9..bab27315872 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNActions.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNActions.java @@ -21,6 +21,7 @@ package ch.systemsx.cisd.ant.task.subversion; * * @author Bernd Rinn */ -interface ISVNActions extends ISVNCat, ISVNList, ISVNMkDir, ISVNCopy, ISVNInfo, ISVNStatus, ISVNMucc +interface ISVNActions extends ISVNCat, ISVNList, ISVNMkDir, ISVNCopy, ISVNInfo, ISVNStatus, + ISVNMucc { } \ No newline at end of file diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCheckout.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCheckout.java index 51b984110bf..e9847fba555 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCheckout.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCheckout.java @@ -34,7 +34,8 @@ interface ISVNCheckout * @param revision The revision in the repository to check out. * @throws SVNException If there is a problem with performing the <code>checkout</code> command. */ - public void checkout(String repositoryUrl, String projectName, String revision) throws SVNException; + public void checkout(String repositoryUrl, String projectName, String revision) + throws SVNException; /** * @return The directory where working copies are created by {@link #checkout(String,String,String)}. diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCopy.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCopy.java index 8b578cd50a0..7f9693e9605 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCopy.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNCopy.java @@ -35,7 +35,7 @@ interface ISVNCopy * @param logMessage The log message to set in the revision properties. * @throws SVNException If there is a problem with performing the <code>copy</code> command. */ - public void copy(String sourcePathOrUrl, String sourceRevision, String destinationPathOrUrl, String logMessage) - throws SVNException; + public void copy(String sourcePathOrUrl, String sourceRevision, String destinationPathOrUrl, + String logMessage) throws SVNException; } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNInfo.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNInfo.java index 916002631f0..1147f34e338 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNInfo.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNInfo.java @@ -19,8 +19,8 @@ package ch.systemsx.cisd.ant.task.subversion; /** * A role that performs an <code>info</code> query on a subversion working copy. * <p> - * This query works on a subversion working copy. - * + * This query works on a subversion working copy. + * * @author Bernd Rinn */ interface ISVNInfo diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNProjectPathProvider.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNProjectPathProvider.java index 43ea390fa30..19260f8b0cd 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNProjectPathProvider.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/ISVNProjectPathProvider.java @@ -55,12 +55,12 @@ interface ISVNProjectPathProvider * @return The name of the project that is path provider's context is based on. */ public String getProjectName(); - + /** * @return The revision of the project that is path provider's context is based on. */ public String getRevision(); - + /** * @return <code>true</code> if this provider represents a subversion repository path (rather than a working copy * path). diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNActions.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNActions.java index 757af77afba..4390200e883 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNActions.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNActions.java @@ -41,36 +41,40 @@ class SVNActions implements ISVNActions this.logger = logger; } - public String cat(String pathOrUrl) throws SVNException { assert pathOrUrl != null; - assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + "' is neither a URL nor an absolute path."; + assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + + "' is neither a URL nor an absolute path."; - final ProcessInfo subversionProcessInfo = SVNUtilities.subversionCommand(logger, false, "cat", pathOrUrl); + final ProcessInfo subversionProcessInfo = + SVNUtilities.subversionCommand(logger, false, "cat", pathOrUrl); return StringUtils.join(subversionProcessInfo.getLines(), OSUtilities.LINE_SEPARATOR); } public List<String> list(String pathOrUrl) throws SVNException { assert pathOrUrl != null; - assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + "' is neither a URL nor an absolute path."; + assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + + "' is neither a URL nor an absolute path."; - final ProcessInfo subversionProcessInfo = SVNUtilities.subversionCommand(logger, "list", pathOrUrl); + final ProcessInfo subversionProcessInfo = + SVNUtilities.subversionCommand(logger, "list", pathOrUrl); return subversionProcessInfo.getLines(); } public void mkdir(String pathOrUrl, String logMessage) throws SVNException { assert pathOrUrl != null; - assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + "' is neither a URL nor an absolute path."; + assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + + "' is neither a URL nor an absolute path."; SVNUtilities.subversionCommand(logger, "mkdir", "--message", logMessage, pathOrUrl); } - public void copy(String sourcePathOrUrl, String sourceRevision, String destinationPathOrUrl, String logMessage) - throws SVNException + public void copy(String sourcePathOrUrl, String sourceRevision, String destinationPathOrUrl, + String logMessage) throws SVNException { assert sourcePathOrUrl != null; assert checkUrlOrAbsolutePath(sourcePathOrUrl) : "'" + sourcePathOrUrl @@ -81,32 +85,36 @@ class SVNActions implements ISVNActions if (SVNUtilities.HEAD_REVISION.equals(sourceRevision)) { - SVNUtilities.subversionCommand(logger, "copy", "--message", logMessage, sourcePathOrUrl, - destinationPathOrUrl); + SVNUtilities.subversionCommand(logger, "copy", "--message", logMessage, + sourcePathOrUrl, destinationPathOrUrl); } else { - SVNUtilities.subversionCommand(logger, "copy", "--message", logMessage, "--revision", sourceRevision, - sourcePathOrUrl, destinationPathOrUrl); + SVNUtilities.subversionCommand(logger, "copy", "--message", logMessage, "--revision", + sourceRevision, sourcePathOrUrl, destinationPathOrUrl); } } public SVNInfoRecord info(String pathOrUrl) { assert pathOrUrl != null; - assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + "' is neither a URL nor an absolute path."; + assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + + "' is neither a URL nor an absolute path."; - final ProcessInfo subversionProcessInfo = SVNUtilities.subversionCommand(logger, "info", "-R", pathOrUrl); + final ProcessInfo subversionProcessInfo = + SVNUtilities.subversionCommand(logger, "info", "-R", pathOrUrl); final SVNInfoRecord infoRecord = new SVNInfoRecord(); new SVNInfoRecordExtractor().fillInfoRecord(infoRecord, subversionProcessInfo); return infoRecord; } - + public List<SVNItemStatus> status(String pathOrUrl) { assert pathOrUrl != null; - assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + "' is neither a URL nor an absolute path."; + assert checkUrlOrAbsolutePath(pathOrUrl) : "'" + pathOrUrl + + "' is neither a URL nor an absolute path."; - final ProcessInfo subversionProcessInfo = SVNUtilities.subversionCommand(logger, "status", pathOrUrl); + final ProcessInfo subversionProcessInfo = + SVNUtilities.subversionCommand(logger, "status", pathOrUrl); final List<SVNItemStatus> status = new ArrayList<SVNItemStatus>(); for (String line : subversionProcessInfo.getLines()) { @@ -128,18 +136,16 @@ class SVNActions implements ISVNActions return false; } - public boolean isMuccAvailable() { return SVNUtilities.isMuccAvailable(); } - public void mucc(String logMessage, String... args) throws SVNException { assert logMessage != null; assert args.length > 0; - + SVNUtilities.subversionMuccCommand(logger, logMessage, args); } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTask.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTask.java index e816b74f0d7..7b317b8c1cd 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTask.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTask.java @@ -40,7 +40,8 @@ public class SVNBranchAndTagTask extends Task final private SVNRepositoryProjectContext sourceContext = new SVNRepositoryProjectContext(); /** The destination context of the project in the subversion repository. */ - final private SVNRepositoryProjectContext destinationContext = new SVNRepositoryProjectContext(); + final private SVNRepositoryProjectContext destinationContext = + new SVNRepositoryProjectContext(); /** If set to <code>true</code>, both a branch will be created and a tag from this branch. */ private boolean branchIfNecessary = false; @@ -60,7 +61,8 @@ public class SVNBranchAndTagTask extends Task private final String tagRepositoryUrl; - SVNRepositoryProjectContextAntWrapper(SVNRepositoryProjectContext context) throws BuildException + SVNRepositoryProjectContextAntWrapper(SVNRepositoryProjectContext context) + throws BuildException { this(context, null); } @@ -94,14 +96,14 @@ public class SVNBranchAndTagTask extends Task } } - private static ISVNProjectPathProvider createPathProvider(SVNRepositoryProjectContext context) - throws UserFailureException + private static ISVNProjectPathProvider createPathProvider( + SVNRepositoryProjectContext context) throws UserFailureException { return context.getPathProvider(); } - private static void assign(SVNRepositoryProjectContext context, SVNRepositoryProjectContext contextToAssignFrom) - throws UserFailureException + private static void assign(SVNRepositoryProjectContext context, + SVNRepositoryProjectContext contextToAssignFrom) throws UserFailureException { context.setRepositoryRoot(contextToAssignFrom.getRepositoryRoot()); context.setGroup(contextToAssignFrom.getGroup()); @@ -150,14 +152,16 @@ public class SVNBranchAndTagTask extends Task throw new BuildException("No branch/tag name specified."); } final ISVNActions svn = createSVNActions(); - final SVNRepositoryProjectContextAntWrapper source = new SVNRepositoryProjectContextAntWrapper(sourceContext); + final SVNRepositoryProjectContextAntWrapper source = + new SVNRepositoryProjectContextAntWrapper(sourceContext); final SVNRepositoryProjectContextAntWrapper destination = new SVNRepositoryProjectContextAntWrapper(destinationContext, sourceContext); switch (versionTypeToCreate) { case RELEASE_TAG: - createTagInSvn(svn, source, createBranchContext(destinationContext), destination, branchIfNecessary); + createTagInSvn(svn, source, createBranchContext(destinationContext), destination, + branchIfNecessary); break; case RELEASE_BRANCH: case FEATURE_BRANCH: @@ -169,32 +173,38 @@ public class SVNBranchAndTagTask extends Task } - private static void createTagInSvn(final ISVNActions svn, final SVNRepositoryProjectContextAntWrapper source, - final SVNRepositoryProjectContextAntWrapper branch, final SVNRepositoryProjectContextAntWrapper tag, - boolean branchIfNecessary) throws BuildException + private static void createTagInSvn(final ISVNActions svn, + final SVNRepositoryProjectContextAntWrapper source, + final SVNRepositoryProjectContextAntWrapper branch, + final SVNRepositoryProjectContextAntWrapper tag, boolean branchIfNecessary) + throws BuildException { if (false == branchExists(svn, branch)) { if (branchIfNecessary) { - if (false == tag.getVersion().equals(SVNUtilities.getFirstTagForBranch(branch.getVersion()))) + if (false == tag.getVersion().equals( + SVNUtilities.getFirstTagForBranch(branch.getVersion()))) { - throw new BuildException("Supposed to create branch for tag but tag doesn't start a branch (tag='" - + tag.getVersion() + "')."); + throw new BuildException( + "Supposed to create branch for tag but tag doesn't start a branch (tag='" + + tag.getVersion() + "')."); } createBranchInSvn(svn, source, branch); } else { - throw new BuildException("Branch from which to tag is not yet defined. (" + branch.getVersion() + ")"); + throw new BuildException("Branch from which to tag is not yet defined. (" + + branch.getVersion() + ")"); } } final String tagName = tag.getVersion(); final String logMessage = "Create tag '" + tagName + "'"; - svn.copy(branch.getRepositoryUrl(), branch.getRevision(), tag.getRepositoryUrl(), logMessage); + svn.copy(branch.getRepositoryUrl(), branch.getRevision(), tag.getRepositoryUrl(), + logMessage); } - private static SVNRepositoryProjectContextAntWrapper createBranchContext(SVNRepositoryProjectContext tagContext) - throws BuildException + private static SVNRepositoryProjectContextAntWrapper createBranchContext( + SVNRepositoryProjectContext tagContext) throws BuildException { try { @@ -208,7 +218,8 @@ public class SVNBranchAndTagTask extends Task } } - private static void createBranchInSvn(final ISVNActions svn, final SVNRepositoryProjectContextAntWrapper source, + private static void createBranchInSvn(final ISVNActions svn, + final SVNRepositoryProjectContextAntWrapper source, final SVNRepositoryProjectContextAntWrapper destination) { final ISVNProjectPathProvider sourcePathProvider = source.getPathProvider(); @@ -235,8 +246,9 @@ public class SVNBranchAndTagTask extends Task } for (String subProjectName : dependentProjects) { - commandLine.addAll(Arrays.asList("cp", sourcePathProvider.getRevision(), sourcePathProvider - .getPath(subProjectName), destinationPathProvider.getPath(subProjectName))); + commandLine.addAll(Arrays.asList("cp", sourcePathProvider.getRevision(), + sourcePathProvider.getPath(subProjectName), destinationPathProvider + .getPath(subProjectName))); } svn.mucc(logMessage, commandLine.toArray(new String[commandLine.size()])); } else @@ -248,8 +260,9 @@ public class SVNBranchAndTagTask extends Task } for (String subProjectName : dependentProjects) { - svn.copy(sourcePathProvider.getPath(subProjectName), sourcePathProvider.getRevision(), - destinationPathProvider.getPath(subProjectName), logMessage); + svn.copy(sourcePathProvider.getPath(subProjectName), sourcePathProvider + .getRevision(), destinationPathProvider.getPath(subProjectName), + logMessage); } } } catch (SVNException ex) @@ -258,7 +271,8 @@ public class SVNBranchAndTagTask extends Task } } - private static boolean branchExists(final ISVNActions svn, final SVNRepositoryProjectContextAntWrapper branch) + private static boolean branchExists(final ISVNActions svn, + final SVNRepositoryProjectContextAntWrapper branch) { final String branchName = branch.getVersion(); final String branchUrl = branch.getRepositoryUrl(); @@ -300,7 +314,7 @@ public class SVNBranchAndTagTask extends Task throw new BuildException(ex); } } - + public void setGroup(String groupName) { try @@ -332,7 +346,8 @@ public class SVNBranchAndTagTask extends Task if (SVNProjectVersionType.TRUNK != destinationContext.getVersionType()) { - throw new BuildException(String.format("Version type has already been set (Version: '%s', Type: '%s').", + throw new BuildException(String.format( + "Version type has already been set (Version: '%s', Type: '%s').", destinationContext.getVersion(), destinationContext.getVersionType())); } @@ -354,7 +369,8 @@ public class SVNBranchAndTagTask extends Task if (SVNProjectVersionType.TRUNK != destinationContext.getVersionType()) { - throw new BuildException(String.format("Version type has already been set (Version: '%s', Type: '%s').", + throw new BuildException(String.format( + "Version type has already been set (Version: '%s', Type: '%s').", destinationContext.getVersion(), destinationContext.getVersionType())); } @@ -376,7 +392,8 @@ public class SVNBranchAndTagTask extends Task if (SVNProjectVersionType.TRUNK != destinationContext.getVersionType()) { - throw new BuildException(String.format("Version type has already been set (Version: '%s', Type: '%s').", + throw new BuildException(String.format( + "Version type has already been set (Version: '%s', Type: '%s').", destinationContext.getVersion(), destinationContext.getVersionType())); } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNCheckout.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNCheckout.java index d247d8940c0..1d66ac648de 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNCheckout.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNCheckout.java @@ -52,8 +52,8 @@ class SVNCheckout implements ISVNCheckout assert SVNUtilities.HEAD_REVISION.equals(revision) || Integer.parseInt(revision) >= 0; final String workingCopyPath = new File(directoryToCheckout, projectName).getAbsolutePath(); - SVNUtilities.subversionCommand(logger, "checkout", "--revision", revision, String.format("%s@%s", url, - revision), workingCopyPath); + SVNUtilities.subversionCommand(logger, "checkout", "--revision", revision, String.format( + "%s@%s", url, revision), workingCopyPath); } public String getDirectoryToCheckout() diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectsCollector.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectsCollector.java index a5dc0da16ac..3a6c50f880e 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectsCollector.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectsCollector.java @@ -72,7 +72,7 @@ class SVNDependentProjectsCollector private final Set<String> projects; private final String projectPath; - + private final Set<String> locationsAlreadyVisited; ProjectHandler(Set<String> projects, String projectPath) @@ -90,7 +90,8 @@ class SVNDependentProjectsCollector @Override public IEclipseClasspathLocation createLocation() { - final String displayableLocation = projectPath + "/" + EclipseClasspathReader.CLASSPATH_FILE; + final String displayableLocation = + projectPath + "/" + EclipseClasspathReader.CLASSPATH_FILE; if (locationsAlreadyVisited.contains(displayableLocation)) { return null; @@ -100,7 +101,7 @@ class SVNDependentProjectsCollector { final String eclipseClasspath = actions.cat(displayableLocation); // This is one of the possibilities what can happen if there is no .classpath file. - if (eclipseClasspath.length() == 0) + if (eclipseClasspath.length() == 0) { return null; } @@ -125,7 +126,8 @@ class SVNDependentProjectsCollector public IProjectHandler createHandler(EclipseClasspathEntry entry) { final String projectName = SVNUtilities.getTopLevelDirectory(entry.getPath()); - return new ProjectHandler(projects, pathProvider.getPath(projectName), locationsAlreadyVisited); + return new ProjectHandler(projects, pathProvider.getPath(projectName), + locationsAlreadyVisited); } } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNException.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNException.java index be9ee2df3c9..b89f63e400e 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNException.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNException.java @@ -20,7 +20,7 @@ import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException; /** * An exception indicating a problem performing a subversion command. - * + * * @author Bernd Rinn */ public class SVNException extends EnvironmentFailureException @@ -32,7 +32,7 @@ public class SVNException extends EnvironmentFailureException { super(message); } - + public SVNException(String messageTemplate, Throwable cause) { super(messageTemplate, cause); diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecord.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecord.java index f50c068777f..a040e21c598 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecord.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecord.java @@ -28,19 +28,28 @@ class SVNInfoRecord { FILE, DIRECTORY } - + /** The writing part of the interface. */ interface Updater { public void setWorkingCopyPath(String workingCopyPath); + public void setRepositoryUrl(String repositoryUrl); + public void setRepositoryRootUrl(String repositoryRootUrl); + public void setRepositoryUUID(String repositoryUUID); + public void setRevision(int revision); + public void setNodeKind(NodeKind nodeKind); + public void setSchedule(String schedule); + public void setLastChangedAuthor(String lastChangedAuthor); + public void setLastChangedRevision(int lastChangedRevision); + public void setLastChangedDate(String lastChangedDate); } @@ -60,65 +69,65 @@ class SVNInfoRecord private String lastChangedAuthor; - private int lastChangedRevision; + private int lastChangedRevision; private String lastChangedDate; private Updater updater = new Updater() - { - - public void setLastChangedAuthor(String lastChangedAuthor) - { - SVNInfoRecord.this.lastChangedAuthor = lastChangedAuthor; - } - - public void setLastChangedRevision(int lastChangedRevision) - { - SVNInfoRecord.this.lastChangedRevision = lastChangedRevision; - } - - public void setLastChangedDate(String lastChangedDate) - { - SVNInfoRecord.this.lastChangedDate = lastChangedDate; - } - - public void setNodeKind(NodeKind nodeKind) - { - SVNInfoRecord.this.nodeKind = nodeKind; - } - - public void setRepositoryRootUrl(String repositoryRootUrl) - { - SVNInfoRecord.this.repositoryRootUrl = repositoryRootUrl; - } - - public void setRepositoryUUID(String repositoryUUID) - { - SVNInfoRecord.this.repositoryUUID = repositoryUUID; - } - - public void setRepositoryUrl(String repositoryUrl) - { - SVNInfoRecord.this.repositoryUrl = repositoryUrl; - } - - public void setRevision(int revision) - { - SVNInfoRecord.this.revision = revision; - } - - public void setSchedule(String schedule) - { - SVNInfoRecord.this.schedule = schedule; - } - - public void setWorkingCopyPath(String workingCopyPath) - { - SVNInfoRecord.this.workingCopyPath = workingCopyPath; - } - - }; - + { + + public void setLastChangedAuthor(String lastChangedAuthor) + { + SVNInfoRecord.this.lastChangedAuthor = lastChangedAuthor; + } + + public void setLastChangedRevision(int lastChangedRevision) + { + SVNInfoRecord.this.lastChangedRevision = lastChangedRevision; + } + + public void setLastChangedDate(String lastChangedDate) + { + SVNInfoRecord.this.lastChangedDate = lastChangedDate; + } + + public void setNodeKind(NodeKind nodeKind) + { + SVNInfoRecord.this.nodeKind = nodeKind; + } + + public void setRepositoryRootUrl(String repositoryRootUrl) + { + SVNInfoRecord.this.repositoryRootUrl = repositoryRootUrl; + } + + public void setRepositoryUUID(String repositoryUUID) + { + SVNInfoRecord.this.repositoryUUID = repositoryUUID; + } + + public void setRepositoryUrl(String repositoryUrl) + { + SVNInfoRecord.this.repositoryUrl = repositoryUrl; + } + + public void setRevision(int revision) + { + SVNInfoRecord.this.revision = revision; + } + + public void setSchedule(String schedule) + { + SVNInfoRecord.this.schedule = schedule; + } + + public void setWorkingCopyPath(String workingCopyPath) + { + SVNInfoRecord.this.workingCopyPath = workingCopyPath; + } + + }; + public String getLastChangedAuthor() { return lastChangedAuthor; diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractor.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractor.java index 69bc2a83566..68b189b5b64 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractor.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractor.java @@ -24,8 +24,6 @@ import ch.systemsx.cisd.ant.task.subversion.SVNInfoRecord.Updater; import ch.systemsx.cisd.ant.task.subversion.SVNUtilities.ProcessInfo; /** - * - * * @author felmer */ class SVNInfoRecordExtractor @@ -34,7 +32,7 @@ class SVNInfoRecordExtractor { public void handle(SVNInfoRecord record, String value); } - + private static abstract class FirstValueHandler implements ValueHandler { private boolean first = true; @@ -47,10 +45,10 @@ class SVNInfoRecordExtractor first = false; } } - + protected abstract void update(Updater updater, String value); } - + private static final class PathHandler extends FirstValueHandler { @Override @@ -59,7 +57,7 @@ class SVNInfoRecordExtractor updater.setWorkingCopyPath(value); } } - + private static final class RepositoryUrlHandler extends FirstValueHandler { @Override @@ -68,7 +66,7 @@ class SVNInfoRecordExtractor updater.setRepositoryUrl(value); } } - + private static final class RepositoryRootHandler extends FirstValueHandler { @Override @@ -77,7 +75,7 @@ class SVNInfoRecordExtractor updater.setRepositoryRootUrl(value); } } - + private static final class RepositoryUUIDHandler extends FirstValueHandler { @Override @@ -86,7 +84,7 @@ class SVNInfoRecordExtractor updater.setRepositoryUUID(value); } } - + private static final class ScheduleHandler extends FirstValueHandler { @Override @@ -95,7 +93,7 @@ class SVNInfoRecordExtractor updater.setSchedule(value); } } - + private static final class LastChangedAuthorHandler extends FirstValueHandler { @Override @@ -104,7 +102,7 @@ class SVNInfoRecordExtractor updater.setLastChangedAuthor(value); } } - + private static final class LastChangedDateHandler extends FirstValueHandler { @Override @@ -113,7 +111,7 @@ class SVNInfoRecordExtractor updater.setLastChangedDate(value); } } - + private static final class NodeKindHandler extends FirstValueHandler { @Override @@ -127,11 +125,12 @@ class SVNInfoRecordExtractor updater.setNodeKind(NodeKind.FILE); } else { - throw SVNException.fromTemplate("Subversion reports invalid node kind '%s'.", value); + throw SVNException + .fromTemplate("Subversion reports invalid node kind '%s'.", value); } } } - + private static final class RevisionHandler implements ValueHandler { public void handle(SVNInfoRecord record, String value) @@ -142,7 +141,8 @@ class SVNInfoRecordExtractor updater.setRevision(Math.max(record.getRevision(), Integer.parseInt(value))); } catch (NumberFormatException ex) { - throw SVNException.fromTemplate("Subversion reports invalid revision number '%s'.", value); + throw SVNException.fromTemplate("Subversion reports invalid revision number '%s'.", + value); } } } @@ -154,10 +154,12 @@ class SVNInfoRecordExtractor try { Updater updater = record.getUpdater(); - updater.setLastChangedRevision(Math.max(record.getLastChangedRevision(), Integer.parseInt(value))); + updater.setLastChangedRevision(Math.max(record.getLastChangedRevision(), Integer + .parseInt(value))); } catch (NumberFormatException ex) { - throw SVNException.fromTemplate("Subversion reports invalid last changed revision number '%s'.", value); + throw SVNException.fromTemplate( + "Subversion reports invalid last changed revision number '%s'.", value); } } } @@ -178,7 +180,7 @@ class SVNInfoRecordExtractor valueHandlerMap.put("Last Changed Rev", new LastChangedRevisionHandler()); valueHandlerMap.put("Last Changed Date", new LastChangedDateHandler()); } - + void fillInfoRecord(final SVNInfoRecord record, final ProcessInfo subversionProcessInfo) { for (String line : subversionProcessInfo.getLines()) @@ -195,5 +197,4 @@ class SVNInfoRecordExtractor } } - } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNItemStatus.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNItemStatus.java index 4f7502c0cc7..56d76a76e60 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNItemStatus.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNItemStatus.java @@ -26,24 +26,15 @@ import java.util.Map; */ class SVNItemStatus { - + /** The possible status an item can have. */ public enum StatusFlag { - UPTODATE(' '), - ADDED('A'), - DELETED('D'), - MODIFIED('M'), - REPLACED('R'), - CONFLICTED('C'), - EXTERNALSRELATED('X'), - IGNORED('I'), - UNVERSIONED('?'), - MISSING('!'), - TYPECHANGED('~'); - + UPTODATE(' '), ADDED('A'), DELETED('D'), MODIFIED('M'), REPLACED('R'), CONFLICTED('C'), + EXTERNALSRELATED('X'), IGNORED('I'), UNVERSIONED('?'), MISSING('!'), TYPECHANGED('~'); + private final char statusCharacter; - + StatusFlag(char statusCharacter) { this.statusCharacter = statusCharacter; @@ -53,9 +44,9 @@ class SVNItemStatus { return statusCharacter; } - + } - + private static Map<Character, StatusFlag> characterToStatusMap; private static void ensureCharacterStatusMap() @@ -69,7 +60,7 @@ class SVNItemStatus } } } - + private static final Map<Character, StatusFlag> getCharacterToStatusMap() { ensureCharacterStatusMap(); @@ -84,10 +75,10 @@ class SVNItemStatus { assert path != null; ensureCharacterStatusMap(); - + this.flag = getCharacterToStatusMap().get(statusCharacter); this.path = path; - + assert flag != null; } diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTask.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTask.java index 98319c3410b..a95cf9900d1 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTask.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTask.java @@ -108,13 +108,16 @@ public class SVNRecursiveCheckoutTask extends Task final String projectToCheckOut = pathProvider.getPath(projectName); try { - checkoutCmd.checkout(projectToCheckOut, projectName, pathProvider.getRevision()); + checkoutCmd.checkout(projectToCheckOut, projectName, pathProvider + .getRevision()); } catch (SVNException ex) { throw new BuildException(ex.getMessage(), ex.getCause()); } - final File projectWorkingCopyDir = new File(checkoutCmd.getDirectoryToCheckout(), projectName); - new SVNCheckoutDependentExecutor(checkoutCmd).execute(projectWorkingCopyDir); + final File projectWorkingCopyDir = + new File(checkoutCmd.getDirectoryToCheckout(), projectName); + new SVNCheckoutDependentExecutor(checkoutCmd) + .execute(projectWorkingCopyDir); } } } @@ -148,12 +151,13 @@ public class SVNRecursiveCheckoutTask extends Task try { final ISVNCheckout checkoutCmd = createSVNCheckout(repositoryUrl, workingCopyDir); - checkoutCmd.checkout(pathProvider.getPath(), pathProvider.getProjectName(), pathProvider.getRevision()); + checkoutCmd.checkout(pathProvider.getPath(), pathProvider.getProjectName(), + pathProvider.getRevision()); // Always check out "build_resources", though it is not specified as dependency in .classpath. checkoutCmd.checkout(pathProvider.getPath(SVNUtilities.BUILD_RESOURCES_PROJECT), SVNUtilities.BUILD_RESOURCES_PROJECT, pathProvider.getRevision()); - new SVNCheckoutDependentExecutor(checkoutCmd).execute(new File(workingCopyDir, pathProvider - .getProjectName())); + new SVNCheckoutDependentExecutor(checkoutCmd).execute(new File(workingCopyDir, + pathProvider.getProjectName())); } catch (SVNException ex) { throw new BuildException(ex.getMessage(), ex.getCause()); diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContext.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContext.java index c26e45e11b8..82fb301d7ca 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContext.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContext.java @@ -30,10 +30,12 @@ import ch.systemsx.cisd.common.exceptions.UserFailureException; class SVNRepositoryProjectContext { /** A pattern that release branches must match. */ - private static final Pattern releaseBranchPattern = Pattern.compile(SVNUtilities.RELEASE_BRANCH_PATTERN_STRING); + private static final Pattern releaseBranchPattern = + Pattern.compile(SVNUtilities.RELEASE_BRANCH_PATTERN_STRING); /** A pattern that release tags must match. */ - private static final Pattern releaseTagPattern = Pattern.compile(SVNUtilities.RELEASE_TAG_PATTERN_STRING); + private static final Pattern releaseTagPattern = + Pattern.compile(SVNUtilities.RELEASE_TAG_PATTERN_STRING); /** The root of the repository url, including the protocol. */ private String repositoryRoot = SVNUtilities.DEFAULT_REPOSITORY_ROOT; @@ -135,7 +137,7 @@ class SVNRepositoryProjectContext this.versionType = SVNProjectVersionType.TRUNK; this.version = SVNUtilities.DEFAULT_VERSION; } - + /** * Sets the {@link SVNProjectVersionType} to {@link SVNProjectVersionType#RELEASE_BRANCH} and the version to * <var>branchName</var>. @@ -148,7 +150,8 @@ class SVNRepositoryProjectContext if (false == isReleaseBranch(branchName)) { - throw new UserFailureException("Branch name '" + branchName + "' does not match the pattern."); + throw new UserFailureException("Branch name '" + branchName + + "' does not match the pattern."); } this.versionType = SVNProjectVersionType.RELEASE_BRANCH; this.version = branchName; @@ -178,7 +181,8 @@ class SVNRepositoryProjectContext } if (version.indexOf('/') >= 0) { - throw new UserFailureException("Branch name '" + branchName + "' contains illegal charachter '/'."); + throw new UserFailureException("Branch name '" + branchName + + "' contains illegal charachter '/'."); } this.versionType = SVNProjectVersionType.FEATURE_BRANCH; this.version = branchName; @@ -265,15 +269,15 @@ class SVNRepositoryProjectContext case TRUNK: return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup()), "/"); case RELEASE_BRANCH: - return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup(), getProjectName(), - "branches/release", getVersion()), "/"); + return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup(), + getProjectName(), "branches/release", getVersion()), "/"); case RELEASE_TAG: final String branchName = SVNUtilities.getBranchForTag(getVersion()); - return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup(), getProjectName(), - "tags/release", branchName, getVersion()), "/"); + return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup(), + getProjectName(), "tags/release", branchName, getVersion()), "/"); case FEATURE_BRANCH: - return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup(), getProjectName(), - "branches/feature", getVersion()), "/"); + return StringUtils.join(Arrays.asList(getRepositoryRoot(), getGroup(), + getProjectName(), "branches/feature", getVersion()), "/"); default: throw new AssertionError("Unknown version type '" + versionType + "'."); } @@ -302,17 +306,18 @@ class SVNRepositoryProjectContext } if (subProjectName.indexOf('/') >= 0 || subProjectName.indexOf('\\') >= 0) { - throw UserFailureException.fromTemplate("Sub-project '%s' contains invalid characters.", - subProjectName); + throw UserFailureException.fromTemplate( + "Sub-project '%s' contains invalid characters.", subProjectName); } if (SVNProjectVersionType.TRUNK == versionType) { return StringUtils.join(Arrays.asList(getRepositoryUrl(), subProjectName, - SVNUtilities.DEFAULT_VERSION), "/"); + SVNUtilities.DEFAULT_VERSION), "/"); } else { - return StringUtils.join(Arrays.asList(getRepositoryUrl(), subProjectName), "/"); + return StringUtils.join(Arrays.asList(getRepositoryUrl(), subProjectName), + "/"); } } @@ -321,7 +326,8 @@ class SVNRepositoryProjectContext return getPath(SVNRepositoryProjectContext.this.getProjectName()); } - public String getPath(String subProjectName, String entityPath) throws UserFailureException + public String getPath(String subProjectName, String entityPath) + throws UserFailureException { assert subProjectName != null; assert entityPath != null; diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilities.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilities.java index 238dc055e05..e7323f17320 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilities.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilities.java @@ -108,6 +108,7 @@ class SVNUtilities private static final class StreamReaderGobbler { private final Semaphore waitForReadingFinishedSemaphore = new Semaphore(1); + private final List<String> lines = new ArrayList<String>(); StreamReaderGobbler(final InputStream stream) throws InterruptedException @@ -120,7 +121,8 @@ class SVNUtilities { try { - final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + final BufferedReader reader = + new BufferedReader(new InputStreamReader(stream)); String line; while ((line = reader.readLine()) != null) { @@ -128,7 +130,8 @@ class SVNUtilities } } catch (IOException ex) { - throw new EnvironmentFailureException("Couldn't gobble stream content", ex); + throw new EnvironmentFailureException("Couldn't gobble stream content", + ex); } finally { waitForReadingFinishedSemaphore.release(); @@ -247,17 +250,19 @@ class SVNUtilities } if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { - throw new UserFailureException(typeOfName + " name '" + name + "' contains illegal character."); + throw new UserFailureException(typeOfName + " name '" + name + + "' contains illegal character."); } } - static ProcessInfo subversionCommand(ISimpleLogger logger, final String command, final String... args) + static ProcessInfo subversionCommand(ISimpleLogger logger, final String command, + final String... args) { return subversionCommand(logger, true, command, args); } - static ProcessInfo subversionCommand(ISimpleLogger logger, final boolean redirectErrorStream, final String command, - final String... args) + static ProcessInfo subversionCommand(ISimpleLogger logger, final boolean redirectErrorStream, + final String command, final String... args) { final File svnExecutable = OSUtilities.findExecutable("svn"); if (svnExecutable == null) @@ -276,8 +281,10 @@ class SVNUtilities try { final Process process = builder.start(); - StreamReaderGobbler inputStreamGobbler = new StreamReaderGobbler(process.getInputStream()); - StreamReaderGobbler errorStreamGobbler = new StreamReaderGobbler(process.getErrorStream()); + StreamReaderGobbler inputStreamGobbler = + new StreamReaderGobbler(process.getInputStream()); + StreamReaderGobbler errorStreamGobbler = + new StreamReaderGobbler(process.getErrorStream()); final int exitValue = process.waitFor(); List<String> lines = inputStreamGobbler.getLines(); if (0 != exitValue) @@ -287,7 +294,8 @@ class SVNUtilities { SVNUtilities.logSvnOutput(logger, errorStreamGobbler.getLines()); } - throw SVNException.fromTemplate("Error while executing '%s' (exitValue=%d)", commandString, exitValue); + throw SVNException.fromTemplate("Error while executing '%s' (exitValue=%d)", + commandString, exitValue); } return new ProcessInfo(commandString, lines, exitValue); } catch (IOException ex) @@ -295,7 +303,8 @@ class SVNUtilities throw SVNException.fromTemplate(ex, "Error while executing '%s'", commandString); } catch (InterruptedException ex) { - throw SVNException.fromTemplate(ex, "Unexpectedly interrupted while executing '%s'", commandString); + throw SVNException.fromTemplate(ex, "Unexpectedly interrupted while executing '%s'", + commandString); } } @@ -303,8 +312,9 @@ class SVNUtilities { return (null != OSUtilities.findExecutable("svnmucc")); } - - static ProcessInfo subversionMuccCommand(ISimpleLogger logger, String logMessage, final String... args) + + static ProcessInfo subversionMuccCommand(ISimpleLogger logger, String logMessage, + final String... args) { final File svnExecutable = OSUtilities.findExecutable("svnmucc"); if (svnExecutable == null) @@ -323,13 +333,15 @@ class SVNUtilities try { final Process process = builder.start(); - StreamReaderGobbler inputStreamGobbler = new StreamReaderGobbler(process.getInputStream()); + StreamReaderGobbler inputStreamGobbler = + new StreamReaderGobbler(process.getInputStream()); final int exitValue = process.waitFor(); List<String> lines = inputStreamGobbler.getLines(); if (0 != exitValue) { SVNUtilities.logSvnOutput(logger, inputStreamGobbler.getLines()); - throw SVNException.fromTemplate("Error while executing '%s' (exitValue=%d)", commandString, exitValue); + throw SVNException.fromTemplate("Error while executing '%s' (exitValue=%d)", + commandString, exitValue); } return new ProcessInfo(commandString, lines, exitValue); } catch (IOException ex) @@ -337,7 +349,8 @@ class SVNUtilities throw SVNException.fromTemplate(ex, "Error while executing '%s'", commandString); } catch (InterruptedException ex) { - throw SVNException.fromTemplate(ex, "Unexpectedly interrupted while executing '%s'", commandString); + throw SVNException.fromTemplate(ex, "Unexpectedly interrupted while executing '%s'", + commandString); } } @@ -362,7 +375,8 @@ class SVNUtilities static String getFirstTagForBranch(String branchName) { - final Matcher branchMatcher = Pattern.compile(RELEASE_BRANCH_PATTERN_STRING).matcher(branchName); + final Matcher branchMatcher = + Pattern.compile(RELEASE_BRANCH_PATTERN_STRING).matcher(branchName); boolean matches = branchMatcher.matches(); assert matches; return String.format("%s.%s.0", branchMatcher.group(1), branchMatcher.group(2)); diff --git a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProvider.java b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProvider.java index 79619cc7b52..e6ed4bdbb66 100644 --- a/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProvider.java +++ b/ant_tasks/source/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProvider.java @@ -22,15 +22,16 @@ import ch.systemsx.cisd.common.exceptions.UserFailureException; /** * A {@link ISVNProjectPathProvider} that works on a subversion working directory. - * + * * @author Bernd Rinn */ class SVNWCProjectPathProvider implements ISVNProjectPathProvider { private final String baseDirectory; + private final String projectName; - + /** * @param projectDirectory The directory of the working copy. Is expected to exist and to be a directory. */ @@ -38,7 +39,7 @@ class SVNWCProjectPathProvider implements ISVNProjectPathProvider { assert projectDirectory != null; assert projectDirectory.isDirectory(); - + final String baseDirectoryPath = projectDirectory.getParentFile().getAbsolutePath(); final String thisProjectName = projectDirectory.getName(); if (baseDirectoryPath.endsWith("/.")) // Corresponds to baseDirectory = new File(".") @@ -50,7 +51,7 @@ class SVNWCProjectPathProvider implements ISVNProjectPathProvider } this.projectName = thisProjectName; } - + public String getPath() { return getPath(projectName); @@ -61,7 +62,7 @@ class SVNWCProjectPathProvider implements ISVNProjectPathProvider assert subProjectName != null; SVNUtilities.checkProjectName(subProjectName); - + return new File(baseDirectory, subProjectName).getAbsolutePath(); } @@ -69,7 +70,7 @@ class SVNWCProjectPathProvider implements ISVNProjectPathProvider { assert subProjectName != null; assert entityPath != null; - + if (entityPath.length() == 0) { throw new UserFailureException("Entity path must not be empty."); @@ -107,5 +108,5 @@ class SVNWCProjectPathProvider implements ISVNProjectPathProvider { return false; } - + } diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTaskTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTaskTest.java index 4a5145581f8..f3e2710b24b 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTaskTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/SetEclipseClasspathTaskTest.java @@ -76,8 +76,8 @@ public class SetEclipseClasspathTaskTest extends AssertJUnit printWriter.println("<classpath>"); for (EclipseClasspathEntry entry : entries) { - printWriter.printf(" <classpathentry kind=\"%s\" path=\"%s\"/>\n", entry.getKind(), entry - .getPath()); + printWriter.printf(" <classpathentry kind=\"%s\" path=\"%s\"/>\n", entry + .getKind(), entry.getPath()); } printWriter.println("</classpath>"); } catch (IOException ex) @@ -181,8 +181,10 @@ public class SetEclipseClasspathTaskTest extends AssertJUnit task.execute(); StringBuilder builder = new StringBuilder(); - builder.append(new File(PROJECT_A, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "a.jar").getAbsoluteFile()).append(File.pathSeparatorChar); + builder.append(new File(PROJECT_A, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "a.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); assertEquals(new String(builder), project.getProperty(PROPERTY_NAME)); } @@ -199,10 +201,14 @@ public class SetEclipseClasspathTaskTest extends AssertJUnit task.execute(); StringBuilder builder = new StringBuilder(); - builder.append(new File(PROJECT_B, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(PROJECT_A, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "a.jar").getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "b.jar").getAbsoluteFile()).append(File.pathSeparatorChar); + builder.append(new File(PROJECT_B, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(PROJECT_A, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "a.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "b.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); assertEquals(new String(builder), project.getProperty(PROPERTY_NAME)); } @@ -219,14 +225,22 @@ public class SetEclipseClasspathTaskTest extends AssertJUnit task.execute(); StringBuilder builder = new StringBuilder(); - builder.append(new File(PROJECT_D, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(PROJECT_B, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(PROJECT_A, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "a.jar").getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "b.jar").getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(PROJECT_C, TARGET_CLASSES).getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "c.jar").getAbsoluteFile()).append(File.pathSeparatorChar); - builder.append(new File(TEMP_WORKSPACE, "d.jar").getAbsoluteFile()).append(File.pathSeparatorChar); + builder.append(new File(PROJECT_D, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(PROJECT_B, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(PROJECT_A, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "a.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "b.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(PROJECT_C, TARGET_CLASSES).getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "c.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); + builder.append(new File(TEMP_WORKSPACE, "d.jar").getAbsoluteFile()).append( + File.pathSeparatorChar); assertEquals(new String(builder), project.getProperty(PROPERTY_NAME)); } } diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTaskTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTaskTest.java index 116516c265f..7e67cfa1f2c 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTaskTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/GatherRevisionAndVersionTaskTest.java @@ -56,7 +56,7 @@ public class GatherRevisionAndVersionTaskTest // // Mocks and helper classes // - + private static final class MockPathProvider implements ISVNProjectPathProvider { private final SVNProject project; @@ -65,48 +65,49 @@ public class GatherRevisionAndVersionTaskTest { this.project = project; } - + public boolean isRepositoryPath() { throw new UnsupportedOperationException(); } - + public String getRevision() { throw new UnsupportedOperationException(); } - + public String getProjectName() { return project.getName(); } - + public String getPath(String subProjectName, String entityPath) throws UserFailureException { throw new UnsupportedOperationException(); } - + public String getPath(String subProjectName) throws UserFailureException { return subProjectName; } - + public String getPath() { return getProjectName(); } } - + private static final class MockSVN implements ISVNActions { - private final Map<String, List<SVNItemStatus>> statusMap = new HashMap<String, List<SVNItemStatus>>(); + private final Map<String, List<SVNItemStatus>> statusMap = + new HashMap<String, List<SVNItemStatus>>(); private final Map<String, SVNInfoRecord> infoMap = new HashMap<String, SVNInfoRecord>(); private final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); private final Map<String, String> contentMap = new HashMap<String, String>(); - + SVNInfoRecord register(String path) { System.out.println("REGISTER - " + path); @@ -148,8 +149,8 @@ public class GatherRevisionAndVersionTaskTest return infoRecord; } - public void copy(String sourcePath, String sourceRevision, String destinationPath, String logMessage) - throws SVNException + public void copy(String sourcePath, String sourceRevision, String destinationPath, + String logMessage) throws SVNException { throw new AssertionError("Unexpected call copy"); } @@ -186,8 +187,8 @@ public class GatherRevisionAndVersionTaskTest } } - private GatherRevisionAndVersionTask createTask(final MockSVN mockSvn, final SVNProject svnProject, - final String reposURL) + private GatherRevisionAndVersionTask createTask(final MockSVN mockSvn, + final SVNProject svnProject, final String reposURL) { GatherRevisionAndVersionTask task = new GatherRevisionAndVersionTask() { @@ -259,7 +260,8 @@ public class GatherRevisionAndVersionTaskTest registerProject(svn, projectBaseDir, revision, lastChangedRevision); } - private void registerProject(MockSVN svn, String projectBaseDir, int revision, int lastChangedRevision) + private void registerProject(MockSVN svn, String projectBaseDir, int revision, + int lastChangedRevision) { SVNInfoRecord info = svn.register(".." + File.separator + name); Updater updater = info.getUpdater(); @@ -280,15 +282,19 @@ public class GatherRevisionAndVersionTaskTest { svn = new MockSVN(); project1 = new SVNProject("project1").addFiles("helloWorld.txt"); - project1.addClasspathFile("<classpath>\n" + "<classpathentry kind=\"src\" path=\"source/java\"/>\n" - + "<classpathentry kind=\"lib\" path=\"/libraries/activation/activation.jar\"/>\n" - + "<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" - + "<classpathentry kind=\"src\" path=\"/common\"/>\n" + "</classpath>\n"); + project1 + .addClasspathFile("<classpath>\n" + + "<classpathentry kind=\"src\" path=\"source/java\"/>\n" + + "<classpathentry kind=\"lib\" path=\"/libraries/activation/activation.jar\"/>\n" + + "<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" + + "<classpathentry kind=\"src\" path=\"/common\"/>\n" + "</classpath>\n"); libraries = new SVNProject("libraries").addFiles("lib1.jar"); common = new SVNProject("common").addFiles("build.xml"); - common.addClasspathFile("<classpath>\n" + "<classpathentry kind=\"src\" path=\"source/java\"/>\n" - + "<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" - + "</classpath>\n"); + common + .addClasspathFile("<classpath>\n" + + "<classpathentry kind=\"src\" path=\"source/java\"/>\n" + + "<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" + + "</classpath>\n"); buildResources = new SVNProject("build_resources"); } @@ -314,7 +320,8 @@ public class GatherRevisionAndVersionTaskTest libraries.registerAsTrunk(svn, 10, 6); common.registerAsTrunk(svn, 11, 7); buildResources.registerAsTrunk(svn, 10, 5); - svn.register(".").getUpdater().setRepositoryUrl(BASE_REPOSITORY_URL + "/" + project1.getName() + "/trunk"); + svn.register(".").getUpdater().setRepositoryUrl( + BASE_REPOSITORY_URL + "/" + project1.getName() + "/trunk"); GatherRevisionAndVersionTask task = createTask(svn, project1, BASE_REPOSITORY_URL); task.setRevision("myRevision"); @@ -323,7 +330,8 @@ public class GatherRevisionAndVersionTaskTest task.execute(); assertEquals("7", task.getProject().getProperty("myRevision")); - assertEquals(GatherRevisionAndVersionTask.TRUNK_VERSION, task.getProject().getProperty("myVersion")); + assertEquals(GatherRevisionAndVersionTask.TRUNK_VERSION, task.getProject().getProperty( + "myVersion")); } @Test @@ -335,9 +343,11 @@ public class GatherRevisionAndVersionTaskTest libraries.registerVersion(svn, version, 10, 6); common.registerVersion(svn, version, 11, 7); buildResources.registerVersion(svn, version, 10, 5); - svn.register(".").getUpdater().setRepositoryUrl(BASE_REPOSITORY_URL + "/" + version + "/" + project1.getName()); + svn.register(".").getUpdater().setRepositoryUrl( + BASE_REPOSITORY_URL + "/" + version + "/" + project1.getName()); - GatherRevisionAndVersionTask task = createTask(svn, project1, BASE_REPOSITORY_URL + "/" + version); + GatherRevisionAndVersionTask task = + createTask(svn, project1, BASE_REPOSITORY_URL + "/" + version); task.setRevision("myRevision"); task.setVersion("myVersion"); diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTaskTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTaskTest.java index 690f28f482d..51616c3d71a 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTaskTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNBranchAndTagTaskTest.java @@ -72,8 +72,10 @@ public class SVNBranchAndTagTaskTest return false; } CopyItem that = (CopyItem) obj; - return this.sourcePath.equals(that.sourcePath) && this.sourceRevision.equals(that.sourceRevision) - && this.destinationPath.equals(that.destinationPath) && this.logMessage.equals(that.logMessage); + return this.sourcePath.equals(that.sourcePath) + && this.sourceRevision.equals(that.sourceRevision) + && this.destinationPath.equals(that.destinationPath) + && this.logMessage.equals(that.logMessage); } @Override @@ -87,8 +89,10 @@ public class SVNBranchAndTagTaskTest @Override public String toString() { - return String.format("CopyItem: (sourcePath=%s, sourceRevision=%s, destinationPath=%s, logMessage=%s)", - sourcePath, sourceRevision, destinationPath, logMessage); + return String + .format( + "CopyItem: (sourcePath=%s, sourceRevision=%s, destinationPath=%s, logMessage=%s)", + sourcePath, sourceRevision, destinationPath, logMessage); } } @@ -141,7 +145,8 @@ public class SVNBranchAndTagTaskTest List<CopyItem> copyList = new ArrayList<CopyItem>(); - public MockSVNRepositoryActions(final Map<String, List<String>> listMap, final Map<String, String> catMap) + public MockSVNRepositoryActions(final Map<String, List<String>> listMap, + final Map<String, String> catMap) { super(); this.listMap = listMap; @@ -168,8 +173,8 @@ public class SVNBranchAndTagTaskTest mkdirList.add(new MkdirItem(path, logMessage)); } - public void copy(String sourcePath, String sourceRevision, String destinationPath, String logMessage) - throws SVNException + public void copy(String sourcePath, String sourceRevision, String destinationPath, + String logMessage) throws SVNException { copyList.add(new CopyItem(sourcePath, sourceRevision, destinationPath, logMessage)); } @@ -204,9 +209,11 @@ public class SVNBranchAndTagTaskTest final String branchName = "1.2.x"; final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); final String sourceUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "trunk"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "trunk"), + "/"); final String releaseBranchesUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release"), "/"); listMap.put(sourceUrl, Collections.<String> emptyList()); listMap.put(releaseBranchesUrl, Collections.<String> emptyList()); final Map<String, String> catMap = new HashMap<String, String>(); @@ -226,24 +233,27 @@ public class SVNBranchAndTagTaskTest task.setReleaseBranch(branchName); task.execute(); final String branchUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release", - branchName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release", branchName), "/"); final String tagBaseUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "tags/release", - branchName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "tags/release", branchName), "/"); final String logMessage = "Create branch '" + branchName + "'"; final List<MkdirItem> expectedMkDirList = - Arrays.asList(new MkdirItem(branchUrl, logMessage), new MkdirItem(tagBaseUrl, logMessage)); + Arrays.asList(new MkdirItem(branchUrl, logMessage), new MkdirItem(tagBaseUrl, + logMessage)); assertEquals(expectedMkDirList, svn.mkdirList); final String branchMainUrl = branchUrl + "/" + projectName; - final String branchBuildResourcesUrl = branchUrl + "/" + SVNUtilities.BUILD_RESOURCES_PROJECT; + final String branchBuildResourcesUrl = + branchUrl + "/" + SVNUtilities.BUILD_RESOURCES_PROJECT; final String sourceBuildResourcesUrl = StringUtils.join(Arrays.asList(repositoryRoot, groupName, - SVNUtilities.BUILD_RESOURCES_PROJECT, "trunk"), "/"); + SVNUtilities.BUILD_RESOURCES_PROJECT, "trunk"), "/"); final Set<CopyItem> expectedCopySet = - new HashSet<CopyItem>(Arrays.asList(new CopyItem(sourceBuildResourcesUrl, SVNUtilities.HEAD_REVISION, - branchBuildResourcesUrl, logMessage), new CopyItem(sourceUrl, SVNUtilities.HEAD_REVISION, - branchMainUrl, logMessage))); + new HashSet<CopyItem>(Arrays.asList(new CopyItem(sourceBuildResourcesUrl, + SVNUtilities.HEAD_REVISION, branchBuildResourcesUrl, logMessage), + new CopyItem(sourceUrl, SVNUtilities.HEAD_REVISION, branchMainUrl, + logMessage))); assertEquals(expectedCopySet, new HashSet<CopyItem>(svn.copyList)); } @@ -257,20 +267,24 @@ public class SVNBranchAndTagTaskTest final String branchName = "someFeature"; final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); final String sourceUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "trunk"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "trunk"), + "/"); final String sourceUrlDependent = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, dependentProjectName, "trunk"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, dependentProjectName, + "trunk"), "/"); final String featureBranchesUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/feature"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/feature"), "/"); listMap.put(sourceUrl, Collections.singletonList(".classpath")); listMap.put(sourceUrlDependent, Collections.<String> emptyList()); listMap.put(featureBranchesUrl, Collections.<String> emptyList()); final String classPathFileContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<classpath>\n" - + String.format( - " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/%s\"/>\n", - dependentProjectName) + "</classpath>\n"; + + String + .format( + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/%s\"/>\n", + dependentProjectName) + "</classpath>\n"; final Map<String, String> catMap = new HashMap<String, String>(); catMap.put(sourceUrl + "/.classpath", classPathFileContent); final MockSVNRepositoryActions svn = new MockSVNRepositoryActions(listMap, catMap); @@ -289,22 +303,25 @@ public class SVNBranchAndTagTaskTest task.setFeatureBranch(branchName); task.execute(); final String branchUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/feature", - branchName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/feature", branchName), "/"); final String logMessage = "Create branch '" + branchName + "'"; - final List<MkdirItem> expectedMkDirList = Arrays.asList(new MkdirItem(branchUrl, logMessage)); + final List<MkdirItem> expectedMkDirList = + Arrays.asList(new MkdirItem(branchUrl, logMessage)); assertEquals(expectedMkDirList, svn.mkdirList); final String branchMainUrl = branchUrl + "/" + projectName; - final String branchBuildResourcesUrl = branchUrl + "/" + SVNUtilities.BUILD_RESOURCES_PROJECT; + final String branchBuildResourcesUrl = + branchUrl + "/" + SVNUtilities.BUILD_RESOURCES_PROJECT; final String branchDependendUrl = branchUrl + "/" + dependentProjectName; final String sourceBuildResourcesUrl = StringUtils.join(Arrays.asList(repositoryRoot, groupName, - SVNUtilities.BUILD_RESOURCES_PROJECT, "trunk"), "/"); + SVNUtilities.BUILD_RESOURCES_PROJECT, "trunk"), "/"); final Set<CopyItem> expectedCopySet = - new HashSet<CopyItem>(Arrays.asList(new CopyItem(sourceBuildResourcesUrl, SVNUtilities.HEAD_REVISION, - branchBuildResourcesUrl, logMessage), new CopyItem(sourceUrl, SVNUtilities.HEAD_REVISION, - branchMainUrl, logMessage), new CopyItem(sourceUrlDependent, SVNUtilities.HEAD_REVISION, - branchDependendUrl, logMessage))); + new HashSet<CopyItem>(Arrays.asList(new CopyItem(sourceBuildResourcesUrl, + SVNUtilities.HEAD_REVISION, branchBuildResourcesUrl, logMessage), + new CopyItem(sourceUrl, SVNUtilities.HEAD_REVISION, branchMainUrl, + logMessage), new CopyItem(sourceUrlDependent, + SVNUtilities.HEAD_REVISION, branchDependendUrl, logMessage))); assertEquals(expectedCopySet, new HashSet<CopyItem>(svn.copyList)); } @@ -318,7 +335,8 @@ public class SVNBranchAndTagTaskTest final String branchName = "1.2.x"; final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); final String releaseBranchesUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release"), "/"); listMap.put(releaseBranchesUrl, Collections.singletonList(branchName + "/")); final Map<String, String> catMap = new HashMap<String, String>(); final MockSVNRepositoryActions svn = new MockSVNRepositoryActions(listMap, catMap); @@ -337,16 +355,16 @@ public class SVNBranchAndTagTaskTest task.setReleaseTag(tagName); task.execute(); final String tagUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "tags/release", - branchName, tagName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "tags/release", branchName, tagName), "/"); final String branchUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release", - branchName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release", branchName), "/"); final String logMessage = "Create tag '" + tagName + "'"; assertEquals(0, svn.mkdirList.size()); final Set<CopyItem> expectedCopySet = - new HashSet<CopyItem>(Collections.singletonList(new CopyItem(branchUrl, SVNUtilities.HEAD_REVISION, - tagUrl, logMessage))); + new HashSet<CopyItem>(Collections.singletonList(new CopyItem(branchUrl, + SVNUtilities.HEAD_REVISION, tagUrl, logMessage))); assertEquals(expectedCopySet, new HashSet<CopyItem>(svn.copyList)); } @@ -360,7 +378,8 @@ public class SVNBranchAndTagTaskTest final String tagName = "1.2.0"; final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); final String releaseBranchesUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release"), "/"); listMap.put(releaseBranchesUrl, Collections.<String> emptyList()); final Map<String, String> catMap = new HashMap<String, String>(); final MockSVNRepositoryActions svn = new MockSVNRepositoryActions(listMap, catMap); @@ -390,9 +409,11 @@ public class SVNBranchAndTagTaskTest final String branchName = "1.2.x"; final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); final String sourceUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "trunk"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "trunk"), + "/"); final String releaseBranchesUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release"), "/"); listMap.put(releaseBranchesUrl, Collections.<String> emptyList()); final Map<String, String> catMap = new HashMap<String, String>(); final MockSVNRepositoryActions svn = new MockSVNRepositoryActions(listMap, catMap); @@ -412,31 +433,34 @@ public class SVNBranchAndTagTaskTest task.setBranchIfNecessary(true); task.execute(); final String tagBaseUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "tags/release", - branchName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "tags/release", branchName), "/"); final String tagUrl = tagBaseUrl + "/" + tagName; final String branchUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release", - branchName), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release", branchName), "/"); final String logMessageBranch = "Create branch '" + branchName + "'"; final String logMessageTag = "Create tag '" + tagName + "'"; final List<MkdirItem> expectedMkDirList = - Arrays.asList(new MkdirItem(branchUrl, logMessageBranch), new MkdirItem(tagBaseUrl, logMessageBranch)); + Arrays.asList(new MkdirItem(branchUrl, logMessageBranch), new MkdirItem(tagBaseUrl, + logMessageBranch)); assertEquals(expectedMkDirList, svn.mkdirList); final String branchMainUrl = branchUrl + "/" + projectName; - final String branchBuildResourcesUrl = branchUrl + "/" + SVNUtilities.BUILD_RESOURCES_PROJECT; + final String branchBuildResourcesUrl = + branchUrl + "/" + SVNUtilities.BUILD_RESOURCES_PROJECT; final String sourceBuildResourcesUrl = StringUtils.join(Arrays.asList(repositoryRoot, groupName, - SVNUtilities.BUILD_RESOURCES_PROJECT, "trunk"), "/"); + SVNUtilities.BUILD_RESOURCES_PROJECT, "trunk"), "/"); final List<CopyItem> expectedCopyList = - Arrays.asList(new CopyItem(sourceUrl, SVNUtilities.HEAD_REVISION, branchMainUrl, logMessageBranch), - new CopyItem(sourceBuildResourcesUrl, SVNUtilities.HEAD_REVISION, branchBuildResourcesUrl, - logMessageBranch), new CopyItem(branchUrl, SVNUtilities.HEAD_REVISION, tagUrl, - logMessageTag)); + Arrays.asList(new CopyItem(sourceUrl, SVNUtilities.HEAD_REVISION, branchMainUrl, + logMessageBranch), new CopyItem(sourceBuildResourcesUrl, + SVNUtilities.HEAD_REVISION, branchBuildResourcesUrl, logMessageBranch), + new CopyItem(branchUrl, SVNUtilities.HEAD_REVISION, tagUrl, logMessageTag)); assertEquals(expectedCopyList, svn.copyList); } - @Test(expectedExceptions = { BuildException.class }) + @Test(expectedExceptions = + { BuildException.class }) public void testCreateReleaseTagWithBranchCreationButIllegalTag() { final String repositoryRoot = "http://host/repos"; @@ -445,7 +469,8 @@ public class SVNBranchAndTagTaskTest final String tagName = "1.2.1"; final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); final String releaseBranchesUrl = - StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, "branches/release"), "/"); + StringUtils.join(Arrays.asList(repositoryRoot, groupName, projectName, + "branches/release"), "/"); listMap.put(releaseBranchesUrl, Collections.<String> emptyList()); final Map<String, String> catMap = new HashMap<String, String>(); final MockSVNRepositoryActions svn = new MockSVNRepositoryActions(listMap, catMap); diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectCollectorTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectCollectorTest.java index 74b9806801d..4ffab5d0629 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectCollectorTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNDependentProjectCollectorTest.java @@ -41,9 +41,11 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; public class SVNDependentProjectCollectorTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "SVNDependentProjectCollector"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "SVNDependentProjectCollector"); @BeforeClass public void init() @@ -71,7 +73,8 @@ public class SVNDependentProjectCollectorTest final Map<String, String> pathMap; - public MockSVNRepositoryActions(final Map<String, List<String>> listMap, final Map<String, String> pathMap) + public MockSVNRepositoryActions(final Map<String, List<String>> listMap, + final Map<String, String> pathMap) { super(); this.listMap = listMap; @@ -98,8 +101,8 @@ public class SVNDependentProjectCollectorTest throw new AssertionError("Unexpected call mkdir()"); } - public void copy(String sourcePath, String sourceRevision, String destinationPath, String logMessage) - throws SVNException + public void copy(String sourcePath, String sourceRevision, String destinationPath, + String logMessage) throws SVNException { throw new AssertionError("Unexpected call copy()"); } @@ -125,11 +128,13 @@ public class SVNDependentProjectCollectorTest } } - private SVNDependentProjectsCollector createCollector(final ISVNProjectPathProvider pathProvider, - final Map<String, List<String>> listMap, final Map<String, String> catMap) + private SVNDependentProjectsCollector createCollector( + final ISVNProjectPathProvider pathProvider, final Map<String, List<String>> listMap, + final Map<String, String> catMap) { final SVNDependentProjectsCollector collector = - new SVNDependentProjectsCollector(pathProvider, new MockSVNRepositoryActions(listMap, catMap)); + new SVNDependentProjectsCollector(pathProvider, new MockSVNRepositoryActions( + listMap, catMap)); return collector; } @@ -148,26 +153,39 @@ public class SVNDependentProjectCollectorTest final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); listMap.put("http://host/repos/group/libraries/trunk", Arrays.asList("something")); listMap.put("http://host/repos/group/proj1/trunk", Arrays.asList(".classpath")); - listMap.put("http://host/repos/group/proj2/trunk", Arrays.asList("something/", ".classpath")); - listMap.put("http://host/repos/group/proj3/trunk", Arrays.asList("something/", "nothing there")); + listMap.put("http://host/repos/group/proj2/trunk", Arrays + .asList("something/", ".classpath")); + listMap.put("http://host/repos/group/proj3/trunk", Arrays.asList("something/", + "nothing there")); final Map<String, String> catMap = new HashMap<String, String>(); - catMap.put("http://host/repos/group/proj1/trunk/.classpath", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" - + "<classpath>\n" + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" - + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" - + " <classpathentry kind=\"lib\" path=\"/libraries/activation/activation.jar\"/>\n" - + " <classpathentry kind=\"lib\" path=\"/libraries/mail/mail.jar\"/>\n" - + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" - + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj2\"/>\n" - + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + "</classpath>\n" + ""); - catMap.put("http://host/repos/group/proj2/trunk/.classpath", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" - + "<classpath>\n" + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" - + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" - + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" - + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj3\"/>\n" - + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + "</classpath>\n" + ""); + catMap + .put( + "http://host/repos/group/proj1/trunk/.classpath", + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" + + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" + + " <classpathentry kind=\"lib\" path=\"/libraries/activation/activation.jar\"/>\n" + + " <classpathentry kind=\"lib\" path=\"/libraries/mail/mail.jar\"/>\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" + + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj2\"/>\n" + + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + + "</classpath>\n" + ""); + catMap + .put( + "http://host/repos/group/proj2/trunk/.classpath", + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" + + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" + + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj3\"/>\n" + + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + + "</classpath>\n" + ""); SVNDependentProjectsCollector collector = createCollector(pathProvider, listMap, catMap); final Set<String> projectsExpected = - new HashSet<String>(Arrays.asList("proj1", "proj2", "proj3", "libraries", "build_resources")); + new HashSet<String>(Arrays.asList("proj1", "proj2", "proj3", "libraries", + "build_resources")); final Set<String> projectsFound = collector.collectDependentProjectsFromClasspath(); assertEquals(projectsExpected, projectsFound); } @@ -182,34 +200,43 @@ public class SVNDependentProjectCollectorTest context.setProjectName("proj1"); final ISVNProjectPathProvider pathProvider = context.getPathProvider(); final Map<String, List<String>> listMap = new HashMap<String, List<String>>(); - listMap.put("http://host/repos/group/proj1/branches/feature/branch/libraries", Arrays.asList("something")); - listMap.put("http://host/repos/group/proj1/branches/feature/branch/proj1", Arrays.asList(".classpath")); - listMap.put("http://host/repos/group/proj1/branches/feature/branch/proj2", Arrays.asList("something/", - ".classpath")); - listMap.put("http://host/repos/group/proj1/branches/feature/branch/proj3", Arrays.asList("something/", - "nothing there")); + listMap.put("http://host/repos/group/proj1/branches/feature/branch/libraries", Arrays + .asList("something")); + listMap.put("http://host/repos/group/proj1/branches/feature/branch/proj1", Arrays + .asList(".classpath")); + listMap.put("http://host/repos/group/proj1/branches/feature/branch/proj2", Arrays.asList( + "something/", ".classpath")); + listMap.put("http://host/repos/group/proj1/branches/feature/branch/proj3", Arrays.asList( + "something/", "nothing there")); final Map<String, String> catMap = new HashMap<String, String>(); - catMap.put("http://host/repos/group/proj1/branches/feature/branch/proj1/.classpath", - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<classpath>\n" - + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" - + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" - + " <classpathentry kind=\"lib\" path=\"/libraries/activation/activation.jar\"/>\n" - + " <classpathentry kind=\"lib\" path=\"/libraries/mail/mail.jar\"/>\n" - + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" - + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj2\"/>\n" - + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + "</classpath>\n" - + ""); - catMap.put("http://host/repos/group/proj1/branches/feature/branch/proj2/.classpath", - "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<classpath>\n" - + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" - + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" - + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" - + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj3\"/>\n" - + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + "</classpath>\n" - + ""); + catMap + .put( + "http://host/repos/group/proj1/branches/feature/branch/proj1/.classpath", + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" + + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" + + " <classpathentry kind=\"lib\" path=\"/libraries/activation/activation.jar\"/>\n" + + " <classpathentry kind=\"lib\" path=\"/libraries/mail/mail.jar\"/>\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" + + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj2\"/>\n" + + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + + "</classpath>\n" + ""); + catMap + .put( + "http://host/repos/group/proj1/branches/feature/branch/proj2/.classpath", + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + + "<classpath>\n" + + " <classpathentry kind=\"src\" path=\"sourceTest/java\"/>\n" + + " <classpathentry kind=\"src\" path=\"source/java\"/>\n" + + " <classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>\n" + + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/proj3\"/>\n" + + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + + "</classpath>\n" + ""); SVNDependentProjectsCollector collector = createCollector(pathProvider, listMap, catMap); final Set<String> projectsExpected = - new HashSet<String>(Arrays.asList("proj1", "proj2", "proj3", "build_resources", "libraries")); + new HashSet<String>(Arrays.asList("proj1", "proj2", "proj3", "build_resources", + "libraries")); final Set<String> projectsFound = collector.collectDependentProjectsFromClasspath(); assertEquals(projectsExpected, projectsFound); } diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractorTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractorTest.java index 1169c438030..1dc9f02363a 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractorTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNInfoRecordExtractorTest.java @@ -15,6 +15,7 @@ */ package ch.systemsx.cisd.ant.task.subversion; + import static org.testng.AssertJUnit.assertEquals; import java.util.ArrayList; @@ -27,48 +28,45 @@ import org.testng.annotations.Test; import ch.systemsx.cisd.ant.task.subversion.SVNInfoRecord.NodeKind; /** - * - * * @author felmer */ public class SVNInfoRecordExtractorTest { - private static final List<String> INFO1 = Collections.unmodifiableList(Arrays.asList("Path: .", - "URL: svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk", - "Repository Root: svn+ssh://cisd-hal.ethz.ch/internal", - "Repository UUID: e2bb8bc7-4a29-0410-9445-bbee19c747d1", - "Revision: 290", - "Node Kind: directory", - "Schedule: add", - "Last Changed Author: felmer", - "Last Changed Rev: 255", - "Last Changed Date: 2007-05-07 16:27:11 +0200 (Mon, 07 May 2007)", - "")); - private static final List<String> INFO2 = Collections.unmodifiableList(Arrays.asList("Path: build", - "URL: svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build", - "Repository Root: svn+ssh://cisd-hal.ethz.ch/internal", - "Repository UUID: e2bb8bc7-4a29-0410-9445-bbee19c747d1", - "Revision: 290", - "Node Kind: directory", - "Schedule: normal", - "Last Changed Author: felmer", - "Last Changed Rev: 288", - "Last Changed Date: 2007-05-07 16:21:00 +0200 (Mon, 07 May 2007)", - "")); - private static final List<String> INFO3 = Collections.unmodifiableList(Arrays.asList("Path: build\\build.xml", - "Name: build.xml", - "URL: svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build/build.xml", - "Repository Root: svn+ssh://cisd-hal.ethz.ch/internal", - "Repository UUID: e2bb8bc7-4a29-0410-9445-bbee19c747d1", - "Revision: 291", - "Node Kind: file", - "Schedule: normal", - "Last Changed Author: fje", - "Last Changed Rev: 287", - "Last Changed Date: 2007-05-07 16:22:00 +0200 (Mon, 07 May 2007)", - "Text Last Updated: 2007-05-07 16:20:04 +0200 (Mon, 07 May 2007)", - "Checksum: 9236ea7a96fc9aa92c1b4ba8cabe1ae3", - "")); + private static final List<String> INFO1 = + Collections.unmodifiableList(Arrays.asList("Path: .", + "URL: svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk", + "Repository Root: svn+ssh://cisd-hal.ethz.ch/internal", + "Repository UUID: e2bb8bc7-4a29-0410-9445-bbee19c747d1", "Revision: 290", + "Node Kind: directory", "Schedule: add", "Last Changed Author: felmer", + "Last Changed Rev: 255", + "Last Changed Date: 2007-05-07 16:27:11 +0200 (Mon, 07 May 2007)", "")); + + private static final List<String> INFO2 = + Collections.unmodifiableList(Arrays.asList("Path: build", + "URL: svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build", + "Repository Root: svn+ssh://cisd-hal.ethz.ch/internal", + "Repository UUID: e2bb8bc7-4a29-0410-9445-bbee19c747d1", "Revision: 290", + "Node Kind: directory", "Schedule: normal", "Last Changed Author: felmer", + "Last Changed Rev: 288", + "Last Changed Date: 2007-05-07 16:21:00 +0200 (Mon, 07 May 2007)", "")); + + private static final List<String> INFO3 = + Collections + .unmodifiableList(Arrays + .asList( + "Path: build\\build.xml", + "Name: build.xml", + "URL: svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build/build.xml", + "Repository Root: svn+ssh://cisd-hal.ethz.ch/internal", + "Repository UUID: e2bb8bc7-4a29-0410-9445-bbee19c747d1", + "Revision: 291", + "Node Kind: file", + "Schedule: normal", + "Last Changed Author: fje", + "Last Changed Rev: 287", + "Last Changed Date: 2007-05-07 16:22:00 +0200 (Mon, 07 May 2007)", + "Text Last Updated: 2007-05-07 16:20:04 +0200 (Mon, 07 May 2007)", + "Checksum: 9236ea7a96fc9aa92c1b4ba8cabe1ae3", "")); @Test public void testExtractingOfInfo3() @@ -76,10 +74,10 @@ public class SVNInfoRecordExtractorTest ArrayList<String> lines = new ArrayList<String>(); lines.addAll(INFO3); SVNInfoRecord infoRecord = extract(lines); - + assertEquals("build\\build.xml", infoRecord.getWorkingCopyPath()); - assertEquals("svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build/build.xml", - infoRecord.getRepositoryUrl()); + assertEquals("svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build/build.xml", + infoRecord.getRepositoryUrl()); assertEquals("svn+ssh://cisd-hal.ethz.ch/internal", infoRecord.getRepositoryRootUrl()); assertEquals("e2bb8bc7-4a29-0410-9445-bbee19c747d1", infoRecord.getRepositoryUUID()); assertEquals(291, infoRecord.getRevision()); @@ -87,9 +85,10 @@ public class SVNInfoRecordExtractorTest assertEquals("normal", infoRecord.getSchedule()); assertEquals("fje", infoRecord.getLastChangedAuthor()); assertEquals(287, infoRecord.getLastChangedRevision()); - assertEquals("2007-05-07 16:22:00 +0200 (Mon, 07 May 2007)", infoRecord.getLastChangedDate()); + assertEquals("2007-05-07 16:22:00 +0200 (Mon, 07 May 2007)", infoRecord + .getLastChangedDate()); } - + @Test public void testExtractingOfInfo2Info3() { @@ -97,9 +96,10 @@ public class SVNInfoRecordExtractorTest lines.addAll(INFO2); lines.addAll(INFO3); SVNInfoRecord infoRecord = extract(lines); - + assertEquals("build", infoRecord.getWorkingCopyPath()); - assertEquals("svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build", infoRecord.getRepositoryUrl()); + assertEquals("svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk/build", infoRecord + .getRepositoryUrl()); assertEquals("svn+ssh://cisd-hal.ethz.ch/internal", infoRecord.getRepositoryRootUrl()); assertEquals("e2bb8bc7-4a29-0410-9445-bbee19c747d1", infoRecord.getRepositoryUUID()); assertEquals(291, infoRecord.getRevision()); @@ -107,10 +107,10 @@ public class SVNInfoRecordExtractorTest assertEquals("normal", infoRecord.getSchedule()); assertEquals("felmer", infoRecord.getLastChangedAuthor()); assertEquals(288, infoRecord.getLastChangedRevision()); - assertEquals("2007-05-07 16:21:00 +0200 (Mon, 07 May 2007)", infoRecord.getLastChangedDate()); + assertEquals("2007-05-07 16:21:00 +0200 (Mon, 07 May 2007)", infoRecord + .getLastChangedDate()); } - - + @Test public void testExtractingOfInfo1Info2Info3() { @@ -119,9 +119,10 @@ public class SVNInfoRecordExtractorTest lines.addAll(INFO2); lines.addAll(INFO3); SVNInfoRecord infoRecord = extract(lines); - + assertEquals(".", infoRecord.getWorkingCopyPath()); - assertEquals("svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk", infoRecord.getRepositoryUrl()); + assertEquals("svn+ssh://cisd-hal.ethz.ch/internal/cisd/ant_tasks/trunk", infoRecord + .getRepositoryUrl()); assertEquals("svn+ssh://cisd-hal.ethz.ch/internal", infoRecord.getRepositoryRootUrl()); assertEquals("e2bb8bc7-4a29-0410-9445-bbee19c747d1", infoRecord.getRepositoryUUID()); assertEquals(291, infoRecord.getRevision()); @@ -129,9 +130,10 @@ public class SVNInfoRecordExtractorTest assertEquals("add", infoRecord.getSchedule()); assertEquals("felmer", infoRecord.getLastChangedAuthor()); assertEquals(288, infoRecord.getLastChangedRevision()); - assertEquals("2007-05-07 16:27:11 +0200 (Mon, 07 May 2007)", infoRecord.getLastChangedDate()); + assertEquals("2007-05-07 16:27:11 +0200 (Mon, 07 May 2007)", infoRecord + .getLastChangedDate()); } - + private SVNInfoRecord extract(ArrayList<String> lines) { SVNUtilities.ProcessInfo processInfo = new SVNUtilities.ProcessInfo("info", lines, 0); diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTaskTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTaskTest.java index e34799c46b1..6feddc719db 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTaskTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRecursiveCheckoutTaskTest.java @@ -43,9 +43,11 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; public class SVNRecursiveCheckoutTaskTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "SVNRecursiveCheckoutTask"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "SVNRecursiveCheckoutTask"); @BeforeClass public void init() @@ -72,13 +74,13 @@ public class SVNRecursiveCheckoutTaskTest final String repositoryUrl; final String prefix; - + final String workingCopyDir; final List<String> checkedOutPaths; final List<String> checkedOutProjects; - + final List<String> checkedOutRevision; SVNCheckoutMock(String repositoryUrl, String workingCopyDir) @@ -94,7 +96,7 @@ public class SVNRecursiveCheckoutTaskTest public void checkout(String path, String projectName, String revision) throws SVNException { assert path.startsWith(prefix); - + checkedOutPaths.add(path.substring(prefix.length())); checkedOutProjects.add(projectName); checkedOutRevision.add(revision); @@ -130,7 +132,8 @@ public class SVNRecursiveCheckoutTaskTest dir.deleteOnExit(); assert dir.mkdir(); - final SVNRecursiveCheckoutTaskCheckoutMock task = new SVNRecursiveCheckoutTaskCheckoutMock(); + final SVNRecursiveCheckoutTaskCheckoutMock task = + new SVNRecursiveCheckoutTaskCheckoutMock(); task.setDir(dir.getAbsolutePath()); final String reposUrl = "http://somehost/somerepos"; final String projPath = "someproj"; @@ -173,13 +176,15 @@ public class SVNRecursiveCheckoutTaskTest + " <classpathentry kind=\"lib\" path=\"/libraries/mail/mail.jar\"/>\n" + " <classpathentry kind=\"lib\" path=\"/libraries/testng/testng-jdk15.jar\" sourcepath=\"/libraries/testng/src.zip\"/>\n" + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/common\"/>\n" - + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + "</classpath>\n"; + + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + + "</classpath>\n"; final File someProj = new File(workingDirectory, projPath); someProj.delete(); someProj.deleteOnExit(); assert someProj.mkdir(); - final SVNRecursiveCheckoutTaskCheckoutMock task = new SVNRecursiveCheckoutTaskCheckoutMock(); + final SVNRecursiveCheckoutTaskCheckoutMock task = + new SVNRecursiveCheckoutTaskCheckoutMock(); final File classPathFile = new File(someProj, ".classpath"); classPathFile.deleteOnExit(); CollectionIO.writeIterable(classPathFile, Collections.singleton(classPathFileContent)); @@ -196,15 +201,18 @@ public class SVNRecursiveCheckoutTaskTest final List<String> expectedPaths = isTrunk ? Arrays.asList(projPath + "/trunk", SVNUtilities.BUILD_RESOURCES_PROJECT + "/trunk", "libraries/trunk", "common/trunk") : Arrays.asList(projPath, - SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", "common"); + SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", "common"); assertEquals(expectedPaths, task.mock.checkedOutPaths); final List<String> expectedProjects = - Arrays.asList(projPath, SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", "common"); + Arrays + .asList(projPath, SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", + "common"); assertEquals(expectedProjects, task.mock.checkedOutProjects); assertEquals(task.mock.checkedOutProjects.size(), task.mock.checkedOutRevision.size()); for (int i = 0; i < task.mock.checkedOutRevision.size(); ++i) { - assertEquals("Entry " + i, SVNUtilities.HEAD_REVISION, task.mock.checkedOutRevision.get(i)); + assertEquals("Entry " + i, SVNUtilities.HEAD_REVISION, task.mock.checkedOutRevision + .get(i)); } } @@ -223,7 +231,8 @@ public class SVNRecursiveCheckoutTaskTest + " <classpathentry kind=\"lib\" path=\"/libraries/mail/mail.jar\"/>\n" + " <classpathentry kind=\"lib\" path=\"/libraries/testng/testng-jdk15.jar\" sourcepath=\"/libraries/testng/src.zip\"/>\n" + " <classpathentry combineaccessrules=\"false\" kind=\"src\" path=\"/common\"/>\n" - + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + "</classpath>\n"; + + " <classpathentry kind=\"output\" path=\"targets/classes\"/>\n" + + "</classpath>\n"; final String classPathFileContent2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<classpath>\n" @@ -248,7 +257,8 @@ public class SVNRecursiveCheckoutTaskTest someDependantProj.deleteOnExit(); assert someDependantProj.mkdir(); - final SVNRecursiveCheckoutTaskCheckoutMock task = new SVNRecursiveCheckoutTaskCheckoutMock(); + final SVNRecursiveCheckoutTaskCheckoutMock task = + new SVNRecursiveCheckoutTaskCheckoutMock(); final File classPathFile1 = new File(someProj, ".classpath"); classPathFile1.deleteOnExit(); CollectionIO.writeIterable(classPathFile1, Collections.singleton(classPathFileContent1)); @@ -269,12 +279,14 @@ public class SVNRecursiveCheckoutTaskTest final List<String> expectedPaths = isTrunk ? Arrays.asList(projPath + "/trunk", SVNUtilities.BUILD_RESOURCES_PROJECT - + "/trunk", "libraries/trunk", "common/trunk", "common2/trunk") : Arrays.asList(projPath, - SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", "common", "common2"); + + "/trunk", "libraries/trunk", "common/trunk", "common2/trunk") : Arrays + .asList(projPath, SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", + "common", "common2"); CollectionIO.writeIterable(System.out, task.mock.checkedOutPaths); assertEquals(expectedPaths, task.mock.checkedOutPaths); final List<String> expectedProjects = - Arrays.asList(projPath, SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", "common", "common2"); + Arrays.asList(projPath, SVNUtilities.BUILD_RESOURCES_PROJECT, "libraries", + "common", "common2"); assertEquals(expectedProjects, task.mock.checkedOutProjects); assertEquals(task.mock.checkedOutProjects.size(), task.mock.checkedOutRevision.size()); for (int i = 0; i < task.mock.checkedOutRevision.size(); ++i) @@ -282,7 +294,7 @@ public class SVNRecursiveCheckoutTaskTest assertEquals("Entry " + i, revision, task.mock.checkedOutRevision.get(i)); } } - + @Test(expectedExceptions = { BuildException.class }) public void testSetInvalidRevision() diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContextTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContextTest.java index df5b7be1d2d..02ed7acae19 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContextTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNRepositoryProjectContextTest.java @@ -84,8 +84,9 @@ public class SVNRepositoryProjectContextTest final String name = "someProject"; def.setProjectName(name); final String repositoryUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP; - final String projectPath = StringUtils.join(Arrays.asList(repositoryUrl, name, "trunk"), "/"); + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP; + final String projectPath = + StringUtils.join(Arrays.asList(repositoryUrl, name, "trunk"), "/"); assertEquals(repositoryUrl, def.getRepositoryUrl()); assertEquals(projectPath, def.getPathProvider().getPath()); } @@ -98,8 +99,9 @@ public class SVNRepositoryProjectContextTest final String subName = "someSubProject"; def.setProjectName(name); final String repositoryUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP; - final String projectPath = StringUtils.join(Arrays.asList(repositoryUrl, subName, "trunk"), "/"); + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP; + final String projectPath = + StringUtils.join(Arrays.asList(repositoryUrl, subName, "trunk"), "/"); assertEquals(projectPath, def.getPathProvider().getPath(subName)); } @@ -112,7 +114,7 @@ public class SVNRepositoryProjectContextTest final String pathEntry = ".classpath"; def.setProjectName(name); final String repositoryUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP; final String projectPath = StringUtils.join(Arrays.asList(repositoryUrl, subName, "trunk", pathEntry), "/"); assertEquals(projectPath, def.getPathProvider().getPath(subName, pathEntry)); @@ -127,8 +129,8 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setReleaseBranch(branchName); final String branchUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/branches/release/" + branchName; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/branches/release/" + branchName; final String projectPath = StringUtils.join(Arrays.asList(branchUrl, name), "/"); assertEquals(branchUrl, def.getRepositoryUrl()); assertEquals(projectPath, def.getPathProvider().getPath()); @@ -144,8 +146,8 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setReleaseBranch(branchName); final String branchUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/branches/release/" + branchName; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/branches/release/" + branchName; final String projectPath = StringUtils.join(Arrays.asList(branchUrl, subName), "/"); assertEquals(projectPath, def.getPathProvider().getPath(subName)); } @@ -161,9 +163,10 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setReleaseBranch(branchName); final String branchUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/branches/release/" + branchName; - final String projectPath = StringUtils.join(Arrays.asList(branchUrl, subName, pathEntry), "/"); + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/branches/release/" + branchName; + final String projectPath = + StringUtils.join(Arrays.asList(branchUrl, subName, pathEntry), "/"); assertEquals(projectPath, def.getPathProvider().getPath(subName, pathEntry)); } @@ -176,8 +179,8 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setFeatureBranch(branchName); final String branchUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/branches/feature/" + branchName; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/branches/feature/" + branchName; final String projectPath = StringUtils.join(Arrays.asList(branchUrl, name), "/"); assertEquals(branchUrl, def.getRepositoryUrl()); assertEquals(projectPath, def.getPathProvider().getPath()); @@ -193,8 +196,8 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setFeatureBranch(branchName); final String branchUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/branches/feature/" + branchName; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/branches/feature/" + branchName; final String projectPath = StringUtils.join(Arrays.asList(branchUrl, subName), "/"); assertEquals(projectPath, def.getPathProvider().getPath(subName)); } @@ -209,8 +212,8 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setReleaseTag(tagName); final String tagUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/tags/release/" + branchName + "/" + tagName; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/tags/release/" + branchName + "/" + tagName; final String projectPath = StringUtils.join(Arrays.asList(tagUrl, name), "/"); assertEquals(tagUrl, def.getRepositoryUrl()); assertEquals(projectPath, def.getPathProvider().getPath()); @@ -227,8 +230,8 @@ public class SVNRepositoryProjectContextTest def.setProjectName(name); def.setReleaseTag(tagName); final String tagUrl = - SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP - + "/" + name + "/tags/release/" + branchName + "/" + tagName; + SVNUtilities.DEFAULT_REPOSITORY_ROOT + "/" + SVNUtilities.DEFAULT_GROUP + "/" + + name + "/tags/release/" + branchName + "/" + tagName; final String projectPath = StringUtils.join(Arrays.asList(tagUrl, subName), "/"); assertEquals(tagUrl, def.getRepositoryUrl()); assertEquals(projectPath, def.getPathProvider().getPath(subName)); diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilitiesTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilitiesTest.java index 9b98a3ab110..45b5d71d6f0 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilitiesTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNUtilitiesTest.java @@ -22,7 +22,7 @@ import static org.testng.AssertJUnit.*; /** * Test cases for {@link SVNUtilities}. - * + * * @author Bernd Rinn */ public class SVNUtilitiesTest @@ -36,7 +36,7 @@ public class SVNUtilitiesTest final String normalizedHTTPUrl = "http://home/cisd/repos/test/trunk"; assertEquals(normalizedHTTPUrl, SVNUtilities.normalizeUrl(normalizedHTTPUrl)); } - + @Test public void testNormalizeUrlOnNonNormalizedURls() { @@ -47,7 +47,7 @@ public class SVNUtilitiesTest final String normalizedHTTPUrl = "http://home/cisd/repos/test/trunk"; assertEquals(normalizedHTTPUrl, SVNUtilities.normalizeUrl(nonNormalizedHTTPUrl)); } - + @Test public void testNormalizeUrlOnNonNormalizedProtocolUrl() { @@ -67,7 +67,7 @@ public class SVNUtilitiesTest final String normalizedSVNSSHUrl = "svn+ssh://home/cisd/repos/test/trunk"; assertEquals(normalizedSVNSSHUrl, SVNUtilities.normalizeUrl(nonNormalizedSVNSSHUrl)); } - + @Test public void testGetParent() { @@ -75,7 +75,7 @@ public class SVNUtilitiesTest final String url = parentUrl + "/trunk"; assertEquals(parentUrl, SVNUtilities.getParent(url)); } - + @Test public void testGetParentNonNormalized() { @@ -83,7 +83,7 @@ public class SVNUtilitiesTest final String url = parentUrl + "//trunk/"; assertEquals(parentUrl, SVNUtilities.getParent(url)); } - + @Test public void testGetTopLevelDirectory() { @@ -91,7 +91,7 @@ public class SVNUtilitiesTest assertEquals("one", SVNUtilities.getTopLevelDirectory("/one/")); assertEquals("one", SVNUtilities.getTopLevelDirectory("/one")); } - + @Test public void testGetBranchForTag() { diff --git a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProviderTest.java b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProviderTest.java index 75eb8fa16ef..53516137b33 100644 --- a/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProviderTest.java +++ b/ant_tasks/sourceTest/java/ch/systemsx/cisd/ant/task/subversion/SVNWCProjectPathProviderTest.java @@ -37,9 +37,11 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; public class SVNWCProjectPathProviderTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "SVNWCProjectPathProvider"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "SVNWCProjectPathProvider"); @BeforeClass public void init() @@ -82,15 +84,17 @@ public class SVNWCProjectPathProviderTest final ISVNProjectPathProvider provider = new SVNWCProjectPathProvider(workingCopyDirectory); String expectedPath; expectedPath = - StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), project), File.separator); + StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), project), + File.separator); assertEquals(expectedPath, provider.getPath()); expectedPath = - StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), - subProject), File.separator); + StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), subProject), + File.separator); assertEquals(expectedPath, provider.getPath(subProject)); expectedPath = - StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), - subProject, path), File.separator); + StringUtils.join(Arrays + .asList(workingDirectory.getAbsolutePath(), subProject, path), + File.separator); assertEquals(expectedPath, provider.getPath(subProject, path)); } @@ -106,10 +110,11 @@ public class SVNWCProjectPathProviderTest workingCopyDirectory.mkdir(); assert workingCopyDirectory.isDirectory(); workingDirectory.deleteOnExit(); - final ISVNProjectPathProvider provider = new SVNWCProjectPathProvider(workingCopyDirectory); + final ISVNProjectPathProvider provider = + new SVNWCProjectPathProvider(workingCopyDirectory); final String expectedPath = StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), subProject, - "somePath/two"), File.separator); + "somePath/two"), File.separator); assertEquals(expectedPath, provider.getPath(subProject, path)); } else { @@ -118,10 +123,11 @@ public class SVNWCProjectPathProviderTest final String path = "somePath/two"; final File workingCopyDirectory = new File(workingDirectory, project); workingCopyDirectory.mkdir(); - final ISVNProjectPathProvider provider = new SVNWCProjectPathProvider(workingCopyDirectory); + final ISVNProjectPathProvider provider = + new SVNWCProjectPathProvider(workingCopyDirectory); final String expectedPath = StringUtils.join(Arrays.asList(workingDirectory.getAbsolutePath(), subProject, - "somePath\\two"), File.separator); + "somePath\\two"), File.separator); assertEquals(expectedPath, provider.getPath(subProject, path)); } } diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/NullAuthenticationService.java b/authentication/source/java/ch/systemsx/cisd/authentication/NullAuthenticationService.java index ca92b492cc9..11a774f367e 100644 --- a/authentication/source/java/ch/systemsx/cisd/authentication/NullAuthenticationService.java +++ b/authentication/source/java/ch/systemsx/cisd/authentication/NullAuthenticationService.java @@ -20,8 +20,8 @@ import ch.systemsx.cisd.common.exceptions.ConfigurationFailureException; import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException; /** - * An implementation of {@link IAuthenticationService} which supports as a <code>null</code> object. - * + * An implementation of {@link IAuthenticationService} which supports as a <code>null</code> object. + * * @author Franz-Josef Elmer */ public class NullAuthenticationService implements IAuthenticationService diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/Principal.java b/authentication/source/java/ch/systemsx/cisd/authentication/Principal.java index f50e3e75fbc..d1106bb025a 100644 --- a/authentication/source/java/ch/systemsx/cisd/authentication/Principal.java +++ b/authentication/source/java/ch/systemsx/cisd/authentication/Principal.java @@ -50,11 +50,12 @@ public class Principal * @param lastName can not be <code>null</code>. * @param email can not be <code>null</code>. */ - public Principal(final String userId, final String firstName, final String lastName, final String email) + public Principal(final String userId, final String firstName, final String lastName, + final String email) { - this(userId, firstName, lastName, email, Collections.<String, String>emptyMap()); + this(userId, firstName, lastName, email, Collections.<String, String> emptyMap()); } - + /** * Standard constructor which accepts mandatory parameters and properties. * @@ -64,8 +65,8 @@ public class Principal * @param email can not be <code>null</code>. * @param properties can not be <code>null</code>. */ - public Principal(final String userId, final String firstName, final String lastName, final String email, - final Map<String, String> properties) + public Principal(final String userId, final String firstName, final String lastName, + final String email, final Map<String, String> properties) { assert userId != null; assert firstName != null; @@ -112,9 +113,8 @@ public class Principal return lastName; } - /** - * Returns the property for given <var>key</var>, or <code>null</code>, if no property exists for this - * <var>key</var>. + /** + * Returns the property for given <var>key</var>, or <code>null</code>, if no property exists for this <var>key</var>. */ public final String getProperty(String key) { diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationService.java b/authentication/source/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationService.java index b29b80f134f..bd9ea018ad8 100644 --- a/authentication/source/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationService.java +++ b/authentication/source/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationService.java @@ -41,6 +41,7 @@ import ch.systemsx.cisd.common.exceptions.ConfigurationFailureException; import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException; import ch.systemsx.cisd.common.logging.LogCategory; import ch.systemsx.cisd.common.logging.LogFactory; + /** * This <code>IAuthenticationService</code> implementation first registers the application on the <i>Crowd</i> * server, then authenticates the user. @@ -63,21 +64,26 @@ public class CrowdAuthenticationService implements IAuthenticationService LogFactory.getLogger(LogCategory.OPERATION, CrowdAuthenticationService.class); /** The template to authenticate the application. */ - //@Private + // @Private static final MessageFormat AUTHENTICATE_APPL = - new MessageFormat("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " - + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " - + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + " <soap:Body>\n" - + " <authenticateApplication xmlns=\"urn:SecurityServer\">\n" + " <in0>\n" - + " <credential xmlns=\"http://authentication.integration.crowd.atlassian.com\">\n" - + " <credential>{1}</credential>\n" + " </credential>\n" - + " <name xmlns=\"http://authentication.integration.crowd.atlassian.com\">{0}</name>\n" - + " <validationFactors xmlns=\"http://authentication.integration.crowd.atlassian.com\" " - + " xsi:nil=\"true\" />\n" + " </in0>\n" - + " </authenticateApplication>\n" + " </soap:Body>\n" + "</soap:Envelope>\n"); + new MessageFormat( + "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " + + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" + + " <soap:Body>\n" + + " <authenticateApplication xmlns=\"urn:SecurityServer\">\n" + + " <in0>\n" + + " <credential xmlns=\"http://authentication.integration.crowd.atlassian.com\">\n" + + " <credential>{1}</credential>\n" + + " </credential>\n" + + " <name xmlns=\"http://authentication.integration.crowd.atlassian.com\">{0}</name>\n" + + " <validationFactors xmlns=\"http://authentication.integration.crowd.atlassian.com\" " + + " xsi:nil=\"true\" />\n" + " </in0>\n" + + " </authenticateApplication>\n" + " </soap:Body>\n" + + "</soap:Envelope>\n"); /** The template to authenticate the user. */ - //@Private + // @Private static final MessageFormat AUTHENTICATE_USER = new MessageFormat( "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " @@ -100,7 +106,7 @@ public class CrowdAuthenticationService implements IAuthenticationService + "</soap:Envelope>\n"); /** The template to find a principal by token or by name. */ - //@Private + // @Private static final MessageFormat FIND_PRINCIPAL_BY_NAME = new MessageFormat( "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" @@ -112,8 +118,9 @@ public class CrowdAuthenticationService implements IAuthenticationService + " </in0>\n" + " <in1>{2}</in1>\n" + " </findPrincipalByName>\n" - + " </soap:Body>\n" + "</soap:Envelope>\n"); - + + " </soap:Body>\n" + + "</soap:Envelope>\n"); + private static IRequestExecutor createExecutor() { return new IRequestExecutor() @@ -129,7 +136,8 @@ public class CrowdAuthenticationService implements IAuthenticationService { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(serviceUrl); - StringRequestEntity entity = new StringRequestEntity(message, "application/soap+xml", "utf-8"); + StringRequestEntity entity = + new StringRequestEntity(message, "application/soap+xml", "utf-8"); post.setRequestEntity(entity); String response = null; try @@ -149,7 +157,7 @@ public class CrowdAuthenticationService implements IAuthenticationService }; } - + private final String url; private final String application; @@ -158,10 +166,11 @@ public class CrowdAuthenticationService implements IAuthenticationService private final IRequestExecutor requestExecutor; - public CrowdAuthenticationService(String host, int port, String application, String applicationPassword) + public CrowdAuthenticationService(String host, int port, String application, + String applicationPassword) { - this("https://" + host + ":" + port + "/crowd/services/SecurityServer", application, applicationPassword, - createExecutor()); + this("https://" + host + ":" + port + "/crowd/services/SecurityServer", application, + applicationPassword, createExecutor()); } public CrowdAuthenticationService(String url, String application, String applicationPassword, @@ -174,8 +183,8 @@ public class CrowdAuthenticationService implements IAuthenticationService if (operationLog.isDebugEnabled()) { final String msg = - "A new CrowdAuthenticationService instance has been created for [" + "url=" + url - + ", application=" + application + "]"; + "A new CrowdAuthenticationService instance has been created for [" + "url=" + + url + ", application=" + application + "]"; operationLog.debug(msg); } } @@ -191,8 +200,8 @@ public class CrowdAuthenticationService implements IAuthenticationService String response = execute(AUTHENTICATE_APPL, application, applicationPassword); if (pickElementContent(response, CrowdSoapElements.TOKEN) == null) { - throw new EnvironmentFailureException("Application '" + application + "' couldn't be authenticated: " - + response); + throw new EnvironmentFailureException("Application '" + application + + "' couldn't be authenticated: " + response); } } catch (EnvironmentFailureException ex) { @@ -209,8 +218,8 @@ public class CrowdAuthenticationService implements IAuthenticationService public final String authenticateApplication() { final String applicationToken = - StringEscapeUtils.unescapeXml(execute(CrowdSoapElements.TOKEN, AUTHENTICATE_APPL, application, - applicationPassword)); + StringEscapeUtils.unescapeXml(execute(CrowdSoapElements.TOKEN, AUTHENTICATE_APPL, + application, applicationPassword)); if (applicationToken == null) { operationLog.error("CROWD: application '" + application + "' failed to authenticate."); @@ -218,7 +227,8 @@ public class CrowdAuthenticationService implements IAuthenticationService { if (operationLog.isDebugEnabled()) { - operationLog.debug("CROWD: application '" + application + "' successfully authenticated."); + operationLog.debug("CROWD: application '" + application + + "' successfully authenticated."); } } return applicationToken; @@ -228,12 +238,15 @@ public class CrowdAuthenticationService implements IAuthenticationService { assert applicationToken != null; assert user != null; - - final String userToken = StringEscapeUtils.unescapeXml(execute(CrowdSoapElements.OUT, AUTHENTICATE_USER, - application, applicationToken, user, password)); + + final String userToken = + StringEscapeUtils.unescapeXml(execute(CrowdSoapElements.OUT, AUTHENTICATE_USER, + application, applicationToken, user, password)); if (operationLog.isInfoEnabled()) { - final String msg = "CROWD: authentication of user '" + user + "', application '" + application + "': "; + final String msg = + "CROWD: authentication of user '" + user + "', application '" + application + + "': "; operationLog.info(msg + (userToken == null ? "FAILED." : "SUCCESS.")); } return userToken != null; @@ -254,13 +267,14 @@ public class CrowdAuthenticationService implements IAuthenticationService { if (operationLog.isDebugEnabled()) { - operationLog.debug("No SOAPAttribute element could be found in the SOAP XML response."); + operationLog + .debug("No SOAPAttribute element could be found in the SOAP XML response."); } } if (principal == null) { - throw new EnvironmentFailureException("CROWD: Principal information for user '" + user - + "' could not be obtained."); + throw new EnvironmentFailureException("CROWD: Principal information for user '" + + user + "' could not be obtained."); } return principal; } catch (EnvironmentFailureException ex) @@ -292,8 +306,7 @@ public class CrowdAuthenticationService implements IAuthenticationService } /** Creates a <code>Principal</code> with found SOAP attributes. */ - private final static Principal createPrincipal(String user, - Map<String, String> soapAttributes) + private final static Principal createPrincipal(String user, Map<String, String> soapAttributes) { final String firstName = soapAttributes.get(FIRST_NAME_PROPERTY_KEY); final String lastName = soapAttributes.get(LAST_NAME_PROPERTY_KEY); @@ -335,8 +348,9 @@ public class CrowdAuthenticationService implements IAuthenticationService { if (xmlString == null) { - operationLog.error("Response of web service is invalid (null). We were looking for element '" + element - + "'."); + operationLog + .error("Response of web service is invalid (null). We were looking for element '" + + element + "'."); return null; } @@ -353,14 +367,16 @@ public class CrowdAuthenticationService implements IAuthenticationService index = xmlString.indexOf(">", index); if (index < 0) { - operationLog.error("Element '" + element + "' seems to be present but XML is invalid: '" + operationLog.error("Element '" + element + + "' seems to be present but XML is invalid: '" + StringUtils.abbreviate(xmlString, 50) + "'."); return null; } int endIndex = getIndex(xmlString, "</", element + ">", index); if (endIndex < 0) { - operationLog.error("Start tag of element '" + element + "' is present but end tag is missing: '" + operationLog.error("Start tag of element '" + element + + "' is present but end tag is missing: '" + StringUtils.abbreviate(xmlString, 50) + "'."); return null; } diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/crowd/IRequestExecutor.java b/authentication/source/java/ch/systemsx/cisd/authentication/crowd/IRequestExecutor.java index 8b7648c7389..69070005d2f 100644 --- a/authentication/source/java/ch/systemsx/cisd/authentication/crowd/IRequestExecutor.java +++ b/authentication/source/java/ch/systemsx/cisd/authentication/crowd/IRequestExecutor.java @@ -18,11 +18,11 @@ package ch.systemsx.cisd.authentication.crowd; /** * Interface of classes executing requests. - * + * * @author Franz-Josef Elmer */ interface IRequestExecutor -{ +{ /** * Executes the specified message at the specified service. */ diff --git a/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationServiceTest.java b/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationServiceTest.java index 4973d3c4f95..9724f008664 100644 --- a/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationServiceTest.java +++ b/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/CrowdAuthenticationServiceTest.java @@ -75,7 +75,8 @@ public class CrowdAuthenticationServiceTest { context = new Mockery(); executor = context.mock(IRequestExecutor.class); - authenticationService = new CrowdAuthenticationService(URL, APPLICATION, APPLICATION_PASSWORD, executor); + authenticationService = + new CrowdAuthenticationService(URL, APPLICATION, APPLICATION_PASSWORD, executor); logRecorder = new BufferedAppender("%-5p %c - %m%n", Level.DEBUG); } @@ -96,16 +97,18 @@ public class CrowdAuthenticationServiceTest { Object[] parameters = new Object[] { APPLICATION_ESCAPED, APPLICATION_PASSWORD_ESCAPED }; - String message = CrowdAuthenticationService.AUTHENTICATE_APPL.format(parameters); + String message = + CrowdAuthenticationService.AUTHENTICATE_APPL.format(parameters); one(executor).execute(URL, message); - will(returnValue(createXMLElement(CrowdSoapElements.TOKEN, APPLICATION_TOKEN_ESACPED))); + will(returnValue(createXMLElement(CrowdSoapElements.TOKEN, + APPLICATION_TOKEN_ESACPED))); } }); String result = authenticationService.authenticateApplication(); assertEquals(APPLICATION_TOKEN, result); - assertEquals(createDebugLogEntry("CROWD: application '" + APPLICATION + "' successfully authenticated."), - logRecorder.getLogContent()); + assertEquals(createDebugLogEntry("CROWD: application '" + APPLICATION + + "' successfully authenticated."), logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -118,17 +121,19 @@ public class CrowdAuthenticationServiceTest { Object[] parameters = new Object[] { APPLICATION_ESCAPED, APPLICATION_PASSWORD_ESCAPED }; - String message = CrowdAuthenticationService.AUTHENTICATE_APPL.format(parameters); + String message = + CrowdAuthenticationService.AUTHENTICATE_APPL.format(parameters); one(executor).execute(URL, message); will(returnValue("error")); } }); String result = authenticationService.authenticateApplication(); assertEquals(null, result); - assertEquals(createDebugLogEntry("Element '" + CrowdSoapElements.TOKEN + "' could not be found in 'error'.") + assertEquals(createDebugLogEntry("Element '" + CrowdSoapElements.TOKEN + + "' could not be found in 'error'.") + OSUtilities.LINE_SEPARATOR - + createErrorLogEntry("CROWD: application '" + APPLICATION + "' failed to authenticate."), logRecorder - .getLogContent()); + + createErrorLogEntry("CROWD: application '" + APPLICATION + + "' failed to authenticate."), logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -139,17 +144,22 @@ public class CrowdAuthenticationServiceTest context.checking(new Expectations() { { - Object[] parameters = new Object[] - { APPLICATION_ESCAPED, APPLICATION_TOKEN_ESACPED, USER_ESCAPED, USER_PASSWORD_ESCAPED }; - String message = CrowdAuthenticationService.AUTHENTICATE_USER.format(parameters); + Object[] parameters = + new Object[] + { APPLICATION_ESCAPED, APPLICATION_TOKEN_ESACPED, USER_ESCAPED, + USER_PASSWORD_ESCAPED }; + String message = + CrowdAuthenticationService.AUTHENTICATE_USER.format(parameters); one(executor).execute(URL, message); - will(returnValue(createXMLElement("n:" + CrowdSoapElements.OUT, APPLICATION_TOKEN_ESACPED))); + will(returnValue(createXMLElement("n:" + CrowdSoapElements.OUT, + APPLICATION_TOKEN_ESACPED))); } }); - boolean result = authenticationService.authenticateUser(APPLICATION_TOKEN, USER, USER_PASSWORD); + boolean result = + authenticationService.authenticateUser(APPLICATION_TOKEN, USER, USER_PASSWORD); assertEquals(true, result); - assertEquals(createInfoLogEntry("CROWD: authentication of user '" + USER + "', application '" + APPLICATION - + "': SUCCESS."), logRecorder.getLogContent()); + assertEquals(createInfoLogEntry("CROWD: authentication of user '" + USER + + "', application '" + APPLICATION + "': SUCCESS."), logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -160,19 +170,24 @@ public class CrowdAuthenticationServiceTest context.checking(new Expectations() { { - Object[] parameters = new Object[] - { APPLICATION_ESCAPED, APPLICATION_TOKEN_ESACPED, USER_ESCAPED, USER_PASSWORD_ESCAPED }; - String message = CrowdAuthenticationService.AUTHENTICATE_USER.format(parameters); + Object[] parameters = + new Object[] + { APPLICATION_ESCAPED, APPLICATION_TOKEN_ESACPED, USER_ESCAPED, + USER_PASSWORD_ESCAPED }; + String message = + CrowdAuthenticationService.AUTHENTICATE_USER.format(parameters); one(executor).execute(URL, message); will(returnValue("error")); } }); - boolean result = authenticationService.authenticateUser(APPLICATION_TOKEN, USER, USER_PASSWORD); + boolean result = + authenticationService.authenticateUser(APPLICATION_TOKEN, USER, USER_PASSWORD); assertEquals(false, result); - assertEquals(createDebugLogEntry("Element '" + CrowdSoapElements.OUT + "' could not be found in 'error'.") + assertEquals(createDebugLogEntry("Element '" + CrowdSoapElements.OUT + + "' could not be found in 'error'.") + OSUtilities.LINE_SEPARATOR - + createInfoLogEntry("CROWD: authentication of user '" + USER + "', application '" + APPLICATION - + "': FAILED."), logRecorder.getLogContent()); + + createInfoLogEntry("CROWD: authentication of user '" + USER + "', application '" + + APPLICATION + "': FAILED."), logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -185,7 +200,8 @@ public class CrowdAuthenticationServiceTest { Object[] parameters = new Object[] { APPLICATION_ESCAPED, APPLICATION_TOKEN_ESACPED, USER_ESCAPED }; - String message = CrowdAuthenticationService.FIND_PRINCIPAL_BY_NAME.format(parameters); + String message = + CrowdAuthenticationService.FIND_PRINCIPAL_BY_NAME.format(parameters); one(executor).execute(URL, message); String element = createSOAPAttribute("sn", "Stepka"); element += createSOAPAttribute("invalidPasswordAttempts", "0"); @@ -200,8 +216,8 @@ public class CrowdAuthenticationServiceTest private String createSOAPAttribute(String name, String value) { return "<SOAPAttribute><name>" + name - + "</name><values><ns1:string xmlns:ns1=\"urn:SecurityServer\">" + value - + "</ns1:string></values></SOAPAttribute>"; + + "</name><values><ns1:string xmlns:ns1=\"urn:SecurityServer\">" + + value + "</ns1:string></values></SOAPAttribute>"; } }); Principal result = authenticationService.getPrincipal(APPLICATION_TOKEN, USER); @@ -224,7 +240,8 @@ public class CrowdAuthenticationServiceTest { Object[] parameters = new Object[] { APPLICATION_ESCAPED, APPLICATION_TOKEN_ESACPED, USER_ESCAPED }; - String message = CrowdAuthenticationService.FIND_PRINCIPAL_BY_NAME.format(parameters); + String message = + CrowdAuthenticationService.FIND_PRINCIPAL_BY_NAME.format(parameters); one(executor).execute(URL, message); will(returnValue("<a></a>")); } @@ -235,10 +252,12 @@ public class CrowdAuthenticationServiceTest fail("EnvironmentFailureException expected"); } catch (EnvironmentFailureException e) { - assertEquals("CROWD: Principal information for user '" + USER + "' could not be obtained.", e.getMessage()); + assertEquals("CROWD: Principal information for user '" + USER + + "' could not be obtained.", e.getMessage()); } - assertEquals(createDebugLogEntry("No SOAPAttribute element could be found in the SOAP XML response."), + assertEquals( + createDebugLogEntry("No SOAPAttribute element could be found in the SOAP XML response."), logRecorder.getLogContent()); context.assertIsSatisfied(); diff --git a/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/RealCrowdAuthenticationTest.java b/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/RealCrowdAuthenticationTest.java index 43c643f0763..f4a15d8f222 100644 --- a/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/RealCrowdAuthenticationTest.java +++ b/authentication/sourceTest/java/ch/systemsx/cisd/authentication/crowd/RealCrowdAuthenticationTest.java @@ -44,18 +44,24 @@ public class RealCrowdAuthenticationTest { private static final int PORT_OF_AUTHENTICATION_SERVICE = 0; // FIX! + private static final String HOST_NAME_OF_AUTHENTICATION_SERVICE = null; // FIX! + private static final String NAME_OF_TEST_APPLICATION = "test"; + private static final String PASSWORD_OF_TEST_APPLICATION = null; // FIX! + private static final String NAME_OF_TEST_USER = "test"; + private static final String PASSWORD_OF_TEST_USER = null; // FIX! @Test(groups = "broken") public void testCrowdTestAccount() { final IAuthenticationService as = - new CrowdAuthenticationService(HOST_NAME_OF_AUTHENTICATION_SERVICE, PORT_OF_AUTHENTICATION_SERVICE, - NAME_OF_TEST_APPLICATION, PASSWORD_OF_TEST_APPLICATION); + new CrowdAuthenticationService(HOST_NAME_OF_AUTHENTICATION_SERVICE, + PORT_OF_AUTHENTICATION_SERVICE, NAME_OF_TEST_APPLICATION, + PASSWORD_OF_TEST_APPLICATION); final String token = as.authenticateApplication(); assertNotNull(token); assertTrue(as.authenticateUser(token, NAME_OF_TEST_USER, PASSWORD_OF_TEST_USER)); diff --git a/bds/source/java/ch/systemsx/cisd/bds/AbstractFormattedData.java b/bds/source/java/ch/systemsx/cisd/bds/AbstractFormattedData.java index 92a81d3f895..d7b402de81d 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/AbstractFormattedData.java +++ b/bds/source/java/ch/systemsx/cisd/bds/AbstractFormattedData.java @@ -53,14 +53,15 @@ public abstract class AbstractFormattedData implements IFormattedData final String formatCode = getFormat().getCode(); if (format.getCode().equals(formatCode) == false) { - throw new DataStructureException(String.format("Format codes do not match: '%s' versus '%s'.", format - .getCode(), formatCode)); + throw new DataStructureException(String.format( + "Format codes do not match: '%s' versus '%s'.", format.getCode(), formatCode)); } final Version formatVersion = getFormat().getVersion(); if (format.getVersion().isBackwardsCompatibleWith(formatVersion) == false) { throw new DataStructureException(String.format( - "Version '%s' is not backwards compatible with version '%s'.", format.getVersion(), formatVersion)); + "Version '%s' is not backwards compatible with version '%s'.", format + .getVersion(), formatVersion)); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/Constants.java b/bds/source/java/ch/systemsx/cisd/bds/Constants.java index ee53e2c4934..f2b532f50d1 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/Constants.java +++ b/bds/source/java/ch/systemsx/cisd/bds/Constants.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.bds; /** * Some constants used inside the <i>BDS</i> library - * + * * @author Christian Ribeaud */ public final class Constants diff --git a/bds/source/java/ch/systemsx/cisd/bds/DataStructureLoader.java b/bds/source/java/ch/systemsx/cisd/bds/DataStructureLoader.java index 764f2d26eb1..7a50e03c735 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/DataStructureLoader.java +++ b/bds/source/java/ch/systemsx/cisd/bds/DataStructureLoader.java @@ -50,7 +50,8 @@ public class DataStructureLoader final IStorage storage = createStorage(name); storage.mount(); final Version version = Version.loadFrom(storage.getRoot()); - final IDataStructure dataStructure = DataStructureFactory.createDataStructure(storage, version); + final IDataStructure dataStructure = + DataStructureFactory.createDataStructure(storage, version); dataStructure.open(); return dataStructure; } @@ -60,7 +61,8 @@ public class DataStructureLoader final File file = new File(baseDir, name); if (file.exists() == false) { - throw new DataStructureException("No container name '" + name + "' exists in " + baseDir.getAbsolutePath()); + throw new DataStructureException("No container name '" + name + "' exists in " + + baseDir.getAbsolutePath()); } if (file.isDirectory()) { @@ -71,8 +73,8 @@ public class DataStructureLoader { return new HDF5Storage(hdf5File); } - throw new DataStructureException("Couldn't found appropriate container named '" + name + "' in " - + baseDir.getAbsolutePath()); + throw new DataStructureException("Couldn't found appropriate container named '" + name + + "' in " + baseDir.getAbsolutePath()); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/DataStructureV1_0.java b/bds/source/java/ch/systemsx/cisd/bds/DataStructureV1_0.java index 0021df7caec..dabba575cc4 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/DataStructureV1_0.java +++ b/bds/source/java/ch/systemsx/cisd/bds/DataStructureV1_0.java @@ -32,7 +32,7 @@ import ch.systemsx.cisd.bds.storage.IStorage; public class DataStructureV1_0 extends AbstractDataStructure { public static final String DIR_METADATA = "metadata"; - + public static final String DIR_ANNOTATIONS = "annotations"; public static final String DIR_PARAMETERS = "parameters"; @@ -65,10 +65,11 @@ public class DataStructureV1_0 extends AbstractDataStructure private final void registerHandlers() { - mappingFileHandler = new MappingFileHandler(getMetaDataDirectory(), getStandardData(), getOriginalData()); + mappingFileHandler = + new MappingFileHandler(getMetaDataDirectory(), getStandardData(), getOriginalData()); registerHandler(mappingFileHandler); - registerHandler(new ChecksumHandler(getMetaDataDirectory().makeDirectory(ChecksumHandler.CHECKSUM_DIRECTORY), - getOriginalData())); + registerHandler(new ChecksumHandler(getMetaDataDirectory().makeDirectory( + ChecksumHandler.CHECKSUM_DIRECTORY), getOriginalData())); } /** @@ -106,7 +107,7 @@ public class DataStructureV1_0 extends AbstractDataStructure assertOpenOrCreated(); return Utilities.getOrCreateSubDirectory(root, DIR_ANNOTATIONS); } - + private IDirectory getParametersDirectory() { assertOpenOrCreated(); @@ -124,10 +125,11 @@ public class DataStructureV1_0 extends AbstractDataStructure assertOpenOrCreated(); if (format == null) { - throw new DataStructureException("Couldn't create formatted data because of unspecified format."); + throw new DataStructureException( + "Couldn't create formatted data because of unspecified format."); } - return FormattedDataFactory.createFormattedData(getDataDirectory(), format, UnknownFormatV1_0.UNKNOWN_1_0, - formatParameters); + return FormattedDataFactory.createFormattedData(getDataDirectory(), format, + UnknownFormatV1_0.UNKNOWN_1_0, formatParameters); } /** @@ -151,7 +153,7 @@ public class DataStructureV1_0 extends AbstractDataStructure assert formatParameter != null : "Unspecified format parameter."; formatParameters.addParameter(formatParameter); } - + public void setAnnotations(IAnnotations annotations) { this.annotations = annotations; diff --git a/bds/source/java/ch/systemsx/cisd/bds/ExperimentIdentifier.java b/bds/source/java/ch/systemsx/cisd/bds/ExperimentIdentifier.java index baa2d0bb1f0..d481a403c74 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/ExperimentIdentifier.java +++ b/bds/source/java/ch/systemsx/cisd/bds/ExperimentIdentifier.java @@ -75,7 +75,8 @@ public class ExperimentIdentifier implements IStorable /** * Returns the group code; */ - // TODO 2007-12-03, Tomasz Pylak review: should not we use the term organization as everywhere else instead of group? + // TODO 2007-12-03, Tomasz Pylak review: should not we use the term organization as everywhere else instead of + // group? public final String getGroupCode() { return groupCode; @@ -131,13 +132,15 @@ public class ExperimentIdentifier implements IStorable @Override public int hashCode() { - return (groupCode.hashCode() * 37 + projectCode.hashCode()) * 37 + experimentCode.hashCode(); + return (groupCode.hashCode() * 37 + projectCode.hashCode()) * 37 + + experimentCode.hashCode(); } @Override public String toString() { - return "[group:" + groupCode + ",project:" + projectCode + ",experiment:" + experimentCode + "]"; + return "[group:" + groupCode + ",project:" + projectCode + ",experiment:" + experimentCode + + "]"; } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/ExperimentRegistratorDate.java b/bds/source/java/ch/systemsx/cisd/bds/ExperimentRegistratorDate.java index eb56a34449c..930ef0eee2e 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/ExperimentRegistratorDate.java +++ b/bds/source/java/ch/systemsx/cisd/bds/ExperimentRegistratorDate.java @@ -32,7 +32,8 @@ public final class ExperimentRegistratorDate implements IStorable { static final String FILE_NAME = "experiment_registration_date"; - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); + private static final SimpleDateFormat DATE_FORMAT = + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); static ExperimentRegistratorDate loadFrom(IDirectory directory) { diff --git a/bds/source/java/ch/systemsx/cisd/bds/Factory.java b/bds/source/java/ch/systemsx/cisd/bds/Factory.java index cf7c5cdf25f..48b845ab923 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/Factory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/Factory.java @@ -26,12 +26,13 @@ import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException; /** * General purpose factory for versioned classes with one-argument constructors. - * + * * @author Franz-Josef Elmer */ class Factory<T> { - private final Map<Version, Class<? extends T>> repository = new HashMap<Version, Class<? extends T>>(); + private final Map<Version, Class<? extends T>> repository = + new HashMap<Version, Class<? extends T>>(); void register(Version version, Class<? extends T> clazz) { @@ -40,7 +41,7 @@ class Factory<T> Class<? extends T> getClassFor(Version version) { - + Version v = version; while (true) { @@ -63,22 +64,26 @@ class Factory<T> Constructor<? extends T> constructor; try { - constructor = clazz.getConstructor(new Class[] {argumentClass}); + constructor = clazz.getConstructor(new Class[] + { argumentClass }); } catch (Exception ex1) { - throw new EnvironmentFailureException(clazz + " has no constructor with argument of type " + throw new EnvironmentFailureException(clazz + + " has no constructor with argument of type " + argumentClass.getCanonicalName()); } try { - return constructor.newInstance(new Object[] {argument}); + return constructor.newInstance(new Object[] + { argument }); } catch (InvocationTargetException ex) { - throw new DataStructureException("Couldn't create instance of " + clazz + " for version " + version, ex - .getCause()); + throw new DataStructureException("Couldn't create instance of " + clazz + + " for version " + version, ex.getCause()); } catch (Exception ex) { - throw new DataStructureException("Couldn't create instance of " + clazz + " for version " + version, ex); + throw new DataStructureException("Couldn't create instance of " + clazz + + " for version " + version, ex); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/Format.java b/bds/source/java/ch/systemsx/cisd/bds/Format.java index 17319d4ab01..9491c02f8a4 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/Format.java +++ b/bds/source/java/ch/systemsx/cisd/bds/Format.java @@ -214,7 +214,8 @@ public class Format implements IStorable @Override public int hashCode() { - return (code.hashCode() * 37 + version.hashCode()) * 37 + (variant == null ? 0 : variant.hashCode()); + return (code.hashCode() * 37 + version.hashCode()) * 37 + + (variant == null ? 0 : variant.hashCode()); } @Override diff --git a/bds/source/java/ch/systemsx/cisd/bds/FormatParameters.java b/bds/source/java/ch/systemsx/cisd/bds/FormatParameters.java index 49b4b9e7902..3736db3c4d9 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/FormatParameters.java +++ b/bds/source/java/ch/systemsx/cisd/bds/FormatParameters.java @@ -30,7 +30,8 @@ import ch.systemsx.cisd.bds.storage.INode; */ final class FormatParameters implements IFormatParameters, IStorable { - private final Map<String, FormatParameter> parameters = new LinkedHashMap<String, FormatParameter>(); + private final Map<String, FormatParameter> parameters = + new LinkedHashMap<String, FormatParameter>(); /** * The <code>IFormatParameterFactory</code> implementation used here. @@ -38,14 +39,16 @@ final class FormatParameters implements IFormatParameters, IStorable * Initialized with the default implementation {@link IFormatParameterFactory#DEFAULT_FORMAT_PARAMETER_FACTORY}. * </p> */ - private IFormatParameterFactory formatParameterFactory = IFormatParameterFactory.DEFAULT_FORMAT_PARAMETER_FACTORY; + private IFormatParameterFactory formatParameterFactory = + IFormatParameterFactory.DEFAULT_FORMAT_PARAMETER_FACTORY; final void loadFrom(final IDirectory directory) { parameters.clear(); for (INode node : directory) { - final FormatParameter formatParameter = formatParameterFactory.createFormatParameter(node); + final FormatParameter formatParameter = + formatParameterFactory.createFormatParameter(node); if (formatParameter != null) { addParameter(formatParameter); @@ -90,7 +93,8 @@ final class FormatParameters implements IFormatParameters, IStorable final String parameterName = parameter.getName(); if (containsParameter(parameterName)) { - throw new IllegalArgumentException("There is already a parameter named '" + parameterName + "'."); + throw new IllegalArgumentException("There is already a parameter named '" + + parameterName + "'."); } parameters.put(parameterName, parameter); } diff --git a/bds/source/java/ch/systemsx/cisd/bds/FormatStore.java b/bds/source/java/ch/systemsx/cisd/bds/FormatStore.java index f3d1aed1ca9..bb64856c665 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/FormatStore.java +++ b/bds/source/java/ch/systemsx/cisd/bds/FormatStore.java @@ -52,7 +52,8 @@ public final class FormatStore } /** Constructs an unique key for given <var>formatCode</var>, <var>version</var> and <var>variant</var>. */ - private final static String getKey(final String formatCode, final Version version, final String variant) + private final static String getKey(final String formatCode, final Version version, + final String variant) { String key = formatCode + version.toString(); if (variant != null) @@ -65,8 +66,8 @@ public final class FormatStore /** * Returns corresponding <code>Format</code> for given format code, version and format variant. */ - public final static Format getFormat(final String formatCode, final Version version, final String formatVariant) - throws DataStructureException + public final static Format getFormat(final String formatCode, final Version version, + final String formatVariant) throws DataStructureException { return formats.get(getKey(formatCode, version, formatVariant)); } diff --git a/bds/source/java/ch/systemsx/cisd/bds/FormattedDataContext.java b/bds/source/java/ch/systemsx/cisd/bds/FormattedDataContext.java index a2a22c8ac53..6907f4c9e7b 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/FormattedDataContext.java +++ b/bds/source/java/ch/systemsx/cisd/bds/FormattedDataContext.java @@ -32,7 +32,8 @@ public final class FormattedDataContext private final IFormatParameters formatParameters; - FormattedDataContext(final IDirectory dataDirectory, final Format format, final IFormatParameters formatParameters) + FormattedDataContext(final IDirectory dataDirectory, final Format format, + final IFormatParameters formatParameters) { assert dataDirectory != null : "Unspecified data directory."; this.dataDirectory = dataDirectory; diff --git a/bds/source/java/ch/systemsx/cisd/bds/FormattedDataFactory.java b/bds/source/java/ch/systemsx/cisd/bds/FormattedDataFactory.java index 6fb42641ad8..7bb8120d707 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/FormattedDataFactory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/FormattedDataFactory.java @@ -45,7 +45,8 @@ public final class FormattedDataFactory // This class cannot be instantiated. } - private final static void register(final Format format, final Class<? extends IFormattedData> clazz) + private final static void register(final Format format, + final Class<? extends IFormattedData> clazz) { String code = format.getCode(); Factory<IFormattedData> factory = factories.get(code); @@ -58,22 +59,25 @@ public final class FormattedDataFactory } /** Uses this public method to create a new instance of <code>IFormattedData</code>. */ - public final static IFormattedData createFormattedData(final IDirectory dataDirectory, final Format format, - final Format defaultFormatOrNull, final IFormatParameters formatParameters) + public final static IFormattedData createFormattedData(final IDirectory dataDirectory, + final Format format, final Format defaultFormatOrNull, + final IFormatParameters formatParameters) { final Format supportedFormat = getSupportedFormat(format, defaultFormatOrNull); final Factory<IFormattedData> factory = factories.get(supportedFormat.getCode()); - final FormattedDataContext context = new FormattedDataContext(dataDirectory, supportedFormat, formatParameters); + final FormattedDataContext context = + new FormattedDataContext(dataDirectory, supportedFormat, formatParameters); return factory.create(FormattedDataContext.class, context, format.getVersion()); } - private final static Format getSupportedFormat(final Format format, final Format defaultFormatOrNull) + private final static Format getSupportedFormat(final Format format, + final Format defaultFormatOrNull) { assert format != null : "Unspecified format."; final String code = format.getCode(); assert code != null : "Unspecified format code."; assert format.getVersion() != null : "Unspecified version."; - + final Factory<IFormattedData> factory = factories.get(code); if (factory == null) { diff --git a/bds/source/java/ch/systemsx/cisd/bds/IAnnotations.java b/bds/source/java/ch/systemsx/cisd/bds/IAnnotations.java index cc2b7f3e98c..b1be631e61a 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/IAnnotations.java +++ b/bds/source/java/ch/systemsx/cisd/bds/IAnnotations.java @@ -19,8 +19,6 @@ package ch.systemsx.cisd.bds; import ch.systemsx.cisd.bds.exception.DataStructureException; /** - * - * * @author Franz-Josef Elmer */ public interface IAnnotations extends IStorable diff --git a/bds/source/java/ch/systemsx/cisd/bds/IDataStructure.java b/bds/source/java/ch/systemsx/cisd/bds/IDataStructure.java index 4b1972452fa..66f283851f6 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/IDataStructure.java +++ b/bds/source/java/ch/systemsx/cisd/bds/IDataStructure.java @@ -18,7 +18,6 @@ package ch.systemsx.cisd.bds; import ch.systemsx.cisd.bds.exception.DataStructureException; - /** * Common interface of all data structures. Implementations of this interface provide methods to manipulate a data * structure. These methods are specific for the version of the data structure. For each version there is a concrete @@ -36,7 +35,7 @@ public interface IDataStructure extends IHasVersion * Creates a new empty data structure. */ public void create(); - + /** * Opens an existing data structure and validates it. * diff --git a/bds/source/java/ch/systemsx/cisd/bds/IFormatParameterFactory.java b/bds/source/java/ch/systemsx/cisd/bds/IFormatParameterFactory.java index cb17797d40f..603abe155fe 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/IFormatParameterFactory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/IFormatParameterFactory.java @@ -28,28 +28,31 @@ import ch.systemsx.cisd.bds.storage.INode; public interface IFormatParameterFactory { - public final static IFormatParameterFactory DEFAULT_FORMAT_PARAMETER_FACTORY = new IFormatParameterFactory() - { + public final static IFormatParameterFactory DEFAULT_FORMAT_PARAMETER_FACTORY = + new IFormatParameterFactory() + { - // - // IFormatParameterFactory - // + // + // IFormatParameterFactory + // - public final FormatParameter createFormatParameter(final INode node) - { - if (node instanceof IFile) - { - final IFile file = (IFile) node; - return new FormatParameter(file.getName(), file.getStringContent().trim()); - } - return null; - } + public final FormatParameter createFormatParameter(final INode node) + { + if (node instanceof IFile) + { + final IFile file = (IFile) node; + return new FormatParameter(file.getName(), file.getStringContent() + .trim()); + } + return null; + } - public final FormatParameter createFormatParameter(final String name, final String value) - { - return new FormatParameter(name, value); - } - }; + public final FormatParameter createFormatParameter(final String name, + final String value) + { + return new FormatParameter(name, value); + } + }; /** * Creates a <code>FormatParameter</code> from given <var>node</var>. diff --git a/bds/source/java/ch/systemsx/cisd/bds/IFormattedData.java b/bds/source/java/ch/systemsx/cisd/bds/IFormattedData.java index 87806c27167..6503067379b 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/IFormattedData.java +++ b/bds/source/java/ch/systemsx/cisd/bds/IFormattedData.java @@ -16,10 +16,9 @@ package ch.systemsx.cisd.bds; - /** * Interface common for all classes handling formatted data. - * + * * @author Franz-Josef Elmer */ public interface IFormattedData @@ -28,7 +27,7 @@ public interface IFormattedData * Returns the format of data. */ public Format getFormat(); - + /** * Returns the parameters of the data format. */ diff --git a/bds/source/java/ch/systemsx/cisd/bds/IHasVersion.java b/bds/source/java/ch/systemsx/cisd/bds/IHasVersion.java index de266518297..e3f15a0ebc1 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/IHasVersion.java +++ b/bds/source/java/ch/systemsx/cisd/bds/IHasVersion.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.bds; /** * Role to be having a {@link Version}. - * + * * @author Franz-Josef Elmer */ public interface IHasVersion diff --git a/bds/source/java/ch/systemsx/cisd/bds/MeasurementEntity.java b/bds/source/java/ch/systemsx/cisd/bds/MeasurementEntity.java index eb8faa09d15..2e6850cec6f 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/MeasurementEntity.java +++ b/bds/source/java/ch/systemsx/cisd/bds/MeasurementEntity.java @@ -105,7 +105,8 @@ public final class MeasurementEntity implements IStorable return false; } MeasurementEntity entity = (MeasurementEntity) obj; - return entity.entityTypeDescription.equals(entityTypeDescription) && entity.entityCode.equals(entityCode); + return entity.entityTypeDescription.equals(entityTypeDescription) + && entity.entityCode.equals(entityCode); } @Override diff --git a/bds/source/java/ch/systemsx/cisd/bds/UnknownFormatV1_0.java b/bds/source/java/ch/systemsx/cisd/bds/UnknownFormatV1_0.java index 3f9a4e7be76..5fca7a2bc7e 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/UnknownFormatV1_0.java +++ b/bds/source/java/ch/systemsx/cisd/bds/UnknownFormatV1_0.java @@ -18,12 +18,13 @@ package ch.systemsx.cisd.bds; /** * Unknown Format V1.0. - * + * * @author Franz-Josef Elmer */ public final class UnknownFormatV1_0 extends Format { public static final String FORMAT_CODE = "UNKNOWN"; + /** * The one and only one instance. */ @@ -34,5 +35,4 @@ public final class UnknownFormatV1_0 extends Format super(FORMAT_CODE, new Version(1, 0), null); } - } diff --git a/bds/source/java/ch/systemsx/cisd/bds/Utilities.java b/bds/source/java/ch/systemsx/cisd/bds/Utilities.java index beda0d1501b..cba6cc60b49 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/Utilities.java +++ b/bds/source/java/ch/systemsx/cisd/bds/Utilities.java @@ -49,8 +49,8 @@ public class Utilities { return (IDirectory) node; } - throw new DataStructureException("There is already a node named '" + name + "' but which isn't a directory (" - + node + ")."); + throw new DataStructureException("There is already a node named '" + name + + "' but which isn't a directory (" + node + ")."); } /** @@ -66,8 +66,8 @@ public class Utilities INode node = directory.tryGetNode(name); if (node == null) { - throw new DataStructureException(String.format("No directory named '%s' found in directory '%s'.", name, - directory)); + throw new DataStructureException(String.format( + "No directory named '%s' found in directory '%s'.", name, directory)); } if (node instanceof IDirectory == false) { @@ -142,14 +142,16 @@ public class Utilities return Integer.parseInt(value); } catch (NumberFormatException ex) { - throw new DataStructureException("Value of '" + name + "' version file is not a number: " + value); + throw new DataStructureException("Value of '" + name + + "' version file is not a number: " + value); } } /** * Recursively lists nodes in given <var>directory</var>. */ - public final static List<String> listNodes(final IDirectory diretory, final INodeFilter nodeFilterOrNull) + public final static List<String> listNodes(final IDirectory diretory, + final INodeFilter nodeFilterOrNull) { assert diretory != null : "Given node can not be null."; final INodeFilter nodeFilter; diff --git a/bds/source/java/ch/systemsx/cisd/bds/Version.java b/bds/source/java/ch/systemsx/cisd/bds/Version.java index 80c19700b43..93527193708 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/Version.java +++ b/bds/source/java/ch/systemsx/cisd/bds/Version.java @@ -38,7 +38,8 @@ public final class Version implements IStorable static Version loadFrom(IDirectory directory) { IDirectory versionFolder = Utilities.getSubDirectory(directory, VERSION); - return new Version(Utilities.getNumber(versionFolder, MAJOR), Utilities.getNumber(versionFolder, MINOR)); + return new Version(Utilities.getNumber(versionFolder, MAJOR), Utilities.getNumber( + versionFolder, MINOR)); } /** diff --git a/bds/source/java/ch/systemsx/cisd/bds/exception/DataStructureException.java b/bds/source/java/ch/systemsx/cisd/bds/exception/DataStructureException.java index ee81cc3c8aa..32e8798364b 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/exception/DataStructureException.java +++ b/bds/source/java/ch/systemsx/cisd/bds/exception/DataStructureException.java @@ -16,18 +16,17 @@ package ch.systemsx.cisd.bds.exception; - /** * Exception thrown by manipulations of BDS data structures which can not be classified as {@link StorageException}. - * + * * @author Franz-Josef Elmer */ public class DataStructureException extends RuntimeException { private static final long serialVersionUID = 1L; - + /** - * Creates an instance with the specified message. + * Creates an instance with the specified message. */ public DataStructureException(String message) { diff --git a/bds/source/java/ch/systemsx/cisd/bds/handler/ChecksumHandler.java b/bds/source/java/ch/systemsx/cisd/bds/handler/ChecksumHandler.java index fc97d6c8fe6..6c2a970874c 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/handler/ChecksumHandler.java +++ b/bds/source/java/ch/systemsx/cisd/bds/handler/ChecksumHandler.java @@ -55,7 +55,8 @@ public final class ChecksumHandler implements IDataStructureHandler private final IDirectory originalDataDirectory; - public ChecksumHandler(final IDirectory checksumDirectory, final IDirectory originalDataDirectory) + public ChecksumHandler(final IDirectory checksumDirectory, + final IDirectory originalDataDirectory) { this.checksumDirectory = checksumDirectory; this.originalDataDirectory = originalDataDirectory; @@ -70,7 +71,8 @@ public final class ChecksumHandler implements IDataStructureHandler return checksums; } - private void addChecksums(final List<Checksum> checksums, final String nodePath, final IDirectory directory) + private void addChecksums(final List<Checksum> checksums, final String nodePath, + final IDirectory directory) { final List<INode> children = new ArrayList<INode>(); for (final INode child : directory) @@ -84,21 +86,26 @@ public final class ChecksumHandler implements IDataStructureHandler } } - private final void addChecksum(final List<Checksum> checksums, final String path, final INode node) + private final void addChecksum(final List<Checksum> checksums, final String path, + final INode node) { - final String nodePath = (path == null ? "" : path + Constants.PATH_SEPARATOR) + node.getName(); + final String nodePath = + (path == null ? "" : path + Constants.PATH_SEPARATOR) + node.getName(); if (node instanceof IFile) { IFile file = (IFile) node; final InputStream inputStream = file.getInputStream(); try { - final Checksum checksum = new Checksum(checksumCalculator.calculateChecksum(inputStream), nodePath); - assert checksums.contains(checksum) == false : String.format("Checksum '%s' is not unique.", checksum); + final Checksum checksum = + new Checksum(checksumCalculator.calculateChecksum(inputStream), nodePath); + assert checksums.contains(checksum) == false : String.format( + "Checksum '%s' is not unique.", checksum); checksums.add(checksum); } catch (IOException ex) { - throw new EnvironmentFailureException("Couldn't calculate checksum for file '" + nodePath + "'"); + throw new EnvironmentFailureException("Couldn't calculate checksum for file '" + + nodePath + "'"); } finally { IOUtils.closeQuietly(inputStream); @@ -123,14 +130,16 @@ public final class ChecksumHandler implements IDataStructureHandler final Checksum checkum = CHECKSUM_CONVERTER.fromString(value); if (actual.remove(checkum) == false) { - throw new DataStructureException(String.format("Given checksum '%s' not found in directory '%s'", - checkum, originalDataDirectory)); + throw new DataStructureException(String.format( + "Given checksum '%s' not found in directory '%s'", checkum, + originalDataDirectory)); } } if (actual.size() > 0) { throw new DataStructureException(String.format( - "Following checksums '%s' are not present in the checksum file '%s'.", actual, checksumFile)); + "Following checksums '%s' are not present in the checksum file '%s'.", actual, + checksumFile)); } } @@ -199,7 +208,8 @@ public final class ChecksumHandler implements IDataStructureHandler } } - final static class ChecksumConverter implements IToStringConverter<Checksum>, IFromStringConverter<Checksum> + final static class ChecksumConverter implements IToStringConverter<Checksum>, + IFromStringConverter<Checksum> { private static final String SEPARATOR = " "; diff --git a/bds/source/java/ch/systemsx/cisd/bds/handler/MD5ChecksumCalculator.java b/bds/source/java/ch/systemsx/cisd/bds/handler/MD5ChecksumCalculator.java index d03f7a0687a..c0316b50675 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/handler/MD5ChecksumCalculator.java +++ b/bds/source/java/ch/systemsx/cisd/bds/handler/MD5ChecksumCalculator.java @@ -22,7 +22,6 @@ import java.io.InputStream; import com.twmacinta.util.MD5; import com.twmacinta.util.MD5InputStream; - /** * A {@link IChecksumCalculator} implementation based on <i>MD5</i>. * diff --git a/bds/source/java/ch/systemsx/cisd/bds/handler/MappingFileHandler.java b/bds/source/java/ch/systemsx/cisd/bds/handler/MappingFileHandler.java index 19fbacdb9b1..55edb31a332 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/handler/MappingFileHandler.java +++ b/bds/source/java/ch/systemsx/cisd/bds/handler/MappingFileHandler.java @@ -89,7 +89,8 @@ public final class MappingFileHandler implements IDataStructureHandler assert reference != null : "Unspecified reference."; if (references.contains(reference)) { - throw new DataStructureException("There is already a reference for file '" + reference + "'."); + throw new DataStructureException("There is already a reference for file '" + reference + + "'."); } references.add(reference); } @@ -104,17 +105,18 @@ public final class MappingFileHandler implements IDataStructureHandler int i1 = referenceDefinition.indexOf('\t'); if (i1 < 0) { - throw new DataStructureException("Error in standard-original mapping line " + (i + 1) - + ": missing first tab character: " + referenceDefinition); + throw new DataStructureException("Error in standard-original mapping line " + + (i + 1) + ": missing first tab character: " + referenceDefinition); } String path = referenceDefinition.substring(0, i1); int i2 = referenceDefinition.indexOf('\t', i1 + 1); if (i2 < 0) { - throw new DataStructureException("Error in standard-original mapping line " + (i + 1) - + ": missing second tab character: " + referenceDefinition); + throw new DataStructureException("Error in standard-original mapping line " + + (i + 1) + ": missing second tab character: " + referenceDefinition); } - final ReferenceType type = ReferenceType.resolveByShortName(referenceDefinition.substring(i1 + 1, i2)); + final ReferenceType type = + ReferenceType.resolveByShortName(referenceDefinition.substring(i1 + 1, i2)); references.add(new Reference(path, referenceDefinition.substring(i2 + 1), type)); } } @@ -143,7 +145,8 @@ public final class MappingFileHandler implements IDataStructureHandler final String originalPath = reference.getOriginalPath(); if (originalPathRoot.tryGetNode(originalPath) == null) { - throw new DataStructureException(String.format(errMsg, originalPath, originalPathRoot)); + throw new DataStructureException(String.format(errMsg, originalPath, + originalPathRoot)); } } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/Channel.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/Channel.java index f2c619e5eae..9ac28dd7110 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/Channel.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/Channel.java @@ -71,7 +71,8 @@ public final class Channel implements IStorable return Integer.parseInt(name.substring(CHANNEL.length())); } catch (NumberFormatException ex) { - throw new DataStructureException(String.format("Could not parse the channel number in '%s'", name), ex); + throw new DataStructureException(String.format( + "Could not parse the channel number in '%s'", name), ex); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/ChannelList.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/ChannelList.java index 3028c701aa3..055086ae98f 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/ChannelList.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/ChannelList.java @@ -49,7 +49,8 @@ public final class ChannelList implements IStorable, Iterable<Channel> assert channels != null && channels.size() > 0 : "At least one channel must be specified."; if (new HashSet<Channel>(channels).size() != channels.size()) { - throw new DataStructureException(String.format("Some duplicate channels in '%s'.", channels)); + throw new DataStructureException(String.format("Some duplicate channels in '%s'.", + channels)); } this.channels = channels; } diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/FormatParameterFactory.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/FormatParameterFactory.java index 66b4518da5e..d5cd23201ec 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/FormatParameterFactory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/FormatParameterFactory.java @@ -99,6 +99,7 @@ public final class FormatParameterFactory implements IFormatParameterFactory { return new FormatParameter(name, Boolean.valueOf(value)); } - return IFormatParameterFactory.DEFAULT_FORMAT_PARAMETER_FACTORY.createFormatParameter(name, value); + return IFormatParameterFactory.DEFAULT_FORMAT_PARAMETER_FACTORY.createFormatParameter(name, + value); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/Geometry.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/Geometry.java index 27c5c82365b..0fec2afd36d 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/Geometry.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/Geometry.java @@ -108,7 +108,8 @@ public class Geometry implements IStorable assert directory != null : "Given directory can not be null."; assert directory.getName().startsWith(geometryDirectoryName) : "Given directory name must start with given '" + geometryDirectoryName + "'."; - return new Geometry(Utilities.getNumber(directory, ROWS), Utilities.getNumber(directory, COLUMNS)); + return new Geometry(Utilities.getNumber(directory, ROWS), Utilities.getNumber(directory, + COLUMNS)); } // diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageAnnotations.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageAnnotations.java index 98fb9e12798..bfa82a9f1af 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageAnnotations.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageAnnotations.java @@ -31,19 +31,18 @@ import ch.systemsx.cisd.bds.exception.DataStructureException; import ch.systemsx.cisd.bds.storage.IDirectory; /** - * - * * @author Franz-Josef Elmer */ public class HCSImageAnnotations implements IAnnotations { private static final Set<Format> FORMATS = - Collections.unmodifiableSet(new HashSet<Format>(Arrays.asList(HCSImageFormatV1_0.HCS_IMAGE_1_0))); - + Collections.unmodifiableSet(new HashSet<Format>(Arrays + .asList(HCSImageFormatV1_0.HCS_IMAGE_1_0))); + private String deviceID; - + private List<Channel> channels = new ArrayList<Channel>(); - + public void addChannels(Iterable<Channel> channelIterable) { for (Channel channel : channelIterable) @@ -51,12 +50,12 @@ public class HCSImageAnnotations implements IAnnotations addChannel(channel); } } - + public void addChannel(Channel channel) { channels.add(channel); } - + public List<Channel> getChannels() { return Collections.unmodifiableList(channels); @@ -77,8 +76,8 @@ public class HCSImageAnnotations implements IAnnotations Format format = formattedData.getFormat(); if (FORMATS.contains(format) == false) { - throw new DataStructureException("One of the following formats expected instead of '" + format + "': " - + FORMATS); + throw new DataStructureException("One of the following formats expected instead of '" + + format + "': " + FORMATS); } // TODO 2008-01-15, Franz-Josef Elmer also checks number of channels } diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormatV1_0.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormatV1_0.java index c938138ad32..2449990cc8e 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormatV1_0.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormatV1_0.java @@ -50,8 +50,8 @@ public final class HCSImageFormatV1_0 extends Format */ private final static String[] FORMAT_PARAMETERS = new String[] - { PlateGeometry.PLATE_GEOMETRY, WellGeometry.WELL_GEOMETRY, ChannelList.NUMBER_OF_CHANNELS, - CONTAINS_ORIGINAL_DATA }; + { PlateGeometry.PLATE_GEOMETRY, WellGeometry.WELL_GEOMETRY, + ChannelList.NUMBER_OF_CHANNELS, CONTAINS_ORIGINAL_DATA }; /** * The one and only one instance. diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedData.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedData.java index d15d52437c1..ac48fa1058f 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedData.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedData.java @@ -39,7 +39,8 @@ import ch.systemsx.cisd.bds.storage.INode; * * @author Christian Ribeaud */ -public final class HCSImageFormattedData extends AbstractFormattedData implements IHCSImageFormattedData +public final class HCSImageFormattedData extends AbstractFormattedData implements + IHCSImageFormattedData { /** The <i>column</i> (or <i>x</i>) coordinate. */ @@ -82,8 +83,8 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement { if (geometry.contains(location) == false) { - throw new IllegalArgumentException(String.format("Given geometry '%s' does not contain location '%s'", - geometry, location)); + throw new IllegalArgumentException(String.format( + "Given geometry '%s' does not contain location '%s'", geometry, location)); } } @@ -92,12 +93,14 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement { if (channel < 1) { - throw new IndexOutOfBoundsException(String.format("Channel index must start at 1 (given value is %d).", channel)); + throw new IndexOutOfBoundsException(String.format( + "Channel index must start at 1 (given value is %d).", channel)); } final int channelCount = getChannelCount(); if (channel > channelCount) { - throw new IndexOutOfBoundsException(String.format("Channel index %d exceeds the number of channels %d", channel, channelCount)); + throw new IndexOutOfBoundsException(String.format( + "Channel index %d exceeds the number of channels %d", channel, channelCount)); } } @@ -133,7 +136,8 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement return Channel.CHANNEL + channel; } - private void checkCoordinates(final int channel, final Location plateLocation, final Location wellLocation) + private void checkCoordinates(final int channel, final Location plateLocation, + final Location wellLocation) { checkChannel(channel); assert plateLocation != null : "Plate location can not be null."; @@ -155,7 +159,8 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement if (imageRootNode == null) { throw new DataStructureException(String.format( - "No image root directory named '%s' could be found in the original directory.", imageRootDirName)); + "No image root directory named '%s' could be found in the original directory.", + imageRootDirName)); } assert imageRootNode instanceof IDirectory : "Image root node must be a directory."; return (IDirectory) imageRootNode; @@ -165,15 +170,19 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement // IHCSFormattedData // - public final INode tryGetStandardNodeAt(final int channel, final Location plateLocation, final Location wellLocation) + public final INode tryGetStandardNodeAt(final int channel, final Location plateLocation, + final Location wellLocation) { checkCoordinates(channel, plateLocation, wellLocation); try { final IDirectory standardDir = getStandardDataDirectory(); - final IDirectory channelDir = Utilities.getSubDirectory(standardDir, getChannelName(channel)); - final IDirectory plateRowDir = Utilities.getSubDirectory(channelDir, getPlateRowDirName(plateLocation)); - final IDirectory plateColumnDir = Utilities.getSubDirectory(plateRowDir, getPlateColumnDir(plateLocation)); + final IDirectory channelDir = + Utilities.getSubDirectory(standardDir, getChannelName(channel)); + final IDirectory plateRowDir = + Utilities.getSubDirectory(channelDir, getPlateRowDirName(plateLocation)); + final IDirectory plateColumnDir = + Utilities.getSubDirectory(plateRowDir, getPlateColumnDir(plateLocation)); return plateColumnDir.tryGetNode(createWellFileName(wellLocation)); } catch (final DataStructureException e) { @@ -181,21 +190,26 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement } } - public final NodePath addStandardNode(final File imageRootDirectory, final String imageRelativePath, - final int channel, final Location plateLocation, final Location wellLocation) throws DataStructureException + public final NodePath addStandardNode(final File imageRootDirectory, + final String imageRelativePath, final int channel, final Location plateLocation, + final Location wellLocation) throws DataStructureException { assert imageRootDirectory != null : "Given image root directory can not be null."; assert imageRelativePath != null : "Given image relative path can not be null."; INode node = tryGetStandardNodeAt(channel, plateLocation, wellLocation); if (node != null) { - throw new DataStructureException(String.format( - "A node already exists at channel %d, plate location '%s' and well location '%s'.", channel, - plateLocation, wellLocation)); + throw new DataStructureException( + String + .format( + "A node already exists at channel %d, plate location '%s' and well location '%s'.", + channel, plateLocation, wellLocation)); } final IDirectory standardDir = getStandardDataDirectory(); - final IDirectory channelDir = Utilities.getOrCreateSubDirectory(standardDir, getChannelName(channel)); - final IDirectory plateRowDir = Utilities.getOrCreateSubDirectory(channelDir, getPlateRowDirName(plateLocation)); + final IDirectory channelDir = + Utilities.getOrCreateSubDirectory(standardDir, getChannelName(channel)); + final IDirectory plateRowDir = + Utilities.getOrCreateSubDirectory(channelDir, getPlateRowDirName(plateLocation)); final IDirectory plateColumnDir = Utilities.getOrCreateSubDirectory(plateRowDir, getPlateColumnDir(plateLocation)); final String wellFileName = createWellFileName(wellLocation); @@ -206,13 +220,16 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement if (imageNode == null) { throw new DataStructureException(String.format( - "No image node with path '%s' could be found in the original directory.", imageRelativePath)); + "No image node with path '%s' could be found in the original directory.", + imageRelativePath)); } node = plateColumnDir.tryAddLink(wellFileName, imageNode); } else { // Copies the file. So we are able to undo the operation. - node = plateColumnDir.addFile(new File(imageRootDirectory, imageRelativePath), wellFileName, false); + node = + plateColumnDir.addFile(new File(imageRootDirectory, imageRelativePath), + wellFileName, false); } if (node == null) { @@ -224,8 +241,8 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement } final char sep = Constants.PATH_SEPARATOR; final String standardNodePath = - channelDir.getName() + sep + plateRowDir.getName() + sep + plateColumnDir.getName() + sep - + wellFileName; + channelDir.getName() + sep + plateRowDir.getName() + sep + plateColumnDir.getName() + + sep + wellFileName; return new NodePath(node, standardNodePath); } @@ -254,7 +271,8 @@ public final class HCSImageFormattedData extends AbstractFormattedData implement if (notPresent.isEmpty() == false) { throw new DataStructureException(String.format( - "Following format parameters '%s' could not be found in the structure.", notPresent)); + "Following format parameters '%s' could not be found in the structure.", + notPresent)); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/IHCSImageFormattedData.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/IHCSImageFormattedData.java index 3af684d35e5..398d5216dc5 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/IHCSImageFormattedData.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/IHCSImageFormattedData.java @@ -39,7 +39,8 @@ public interface IHCSImageFormattedData extends IFormattedData * @return this could be, for instance, a {@link ILink} pointing to the <code>data/original</code> directory or a * {@link IFile} that can be extracted somewhere. Might return <code>null</code>. */ - public INode tryGetStandardNodeAt(final int channel, final Location plateLocation, final Location wellLocation); + public INode tryGetStandardNodeAt(final int channel, final Location plateLocation, + final Location wellLocation); /** * Adds a new image file at given coordinates. @@ -52,8 +53,9 @@ public interface IHCSImageFormattedData extends IFormattedData * in the <code>standard</code> directory. Never returns <code>null</code>. * @throws DataStructureException if a node already exists at given coordinates. */ - public NodePath addStandardNode(final File imageRootDirectory, final String imageRelativePath, final int channel, - final Location plateLocation, final Location wellLocation) throws DataStructureException; + public NodePath addStandardNode(final File imageRootDirectory, final String imageRelativePath, + final int channel, final Location plateLocation, final Location wellLocation) + throws DataStructureException; // // Helper classes diff --git a/bds/source/java/ch/systemsx/cisd/bds/hcs/Location.java b/bds/source/java/ch/systemsx/cisd/bds/hcs/Location.java index 648248d1593..564ac25ea18 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/hcs/Location.java +++ b/bds/source/java/ch/systemsx/cisd/bds/hcs/Location.java @@ -51,7 +51,8 @@ public final class Location * * @return <code>null</code> if position is out of range. */ - public static final Location tryCreateLocationFromPosition(final int position, final Geometry geometry) + public static final Location tryCreateLocationFromPosition(final int position, + final Geometry geometry) { assert geometry != null : "Given geometry can not be null."; final int columns = geometry.getColumns(); diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/IDirectory.java b/bds/source/java/ch/systemsx/cisd/bds/storage/IDirectory.java index e9eaa7fae97..4deac1f415b 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/IDirectory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/IDirectory.java @@ -44,7 +44,8 @@ public interface IDirectory extends INode, Iterable<INode> * Adds the specified real file to this directory. The content of <code>file</code> will be copied. If it is a * folder also its complete content including all subfolders will be copied. * - * @param nameOrNull the name of the returned node. If <code>null</code>, then given <var>file</var> name is taken. + * @param nameOrNull the name of the returned node. If <code>null</code>, then given <var>file</var> name is + * taken. * @param move whether given <var>file</var> should be copied or moved. * @return the new node. It will be a {@link ILink} if <code>file</code> is a symbolic link, a {@link IDirectory} * if <code>file</code> is a folder, or {@link IFile} if <code>file</code> is a plain file. diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/ILink.java b/bds/source/java/ch/systemsx/cisd/bds/storage/ILink.java index ee0f5074e9a..9ff767dbe8c 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/ILink.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/ILink.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.bds.storage; /** * Node representing a symbolic link. - * + * * @author Franz-Josef Elmer */ public interface ILink extends INode diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/IStorage.java b/bds/source/java/ch/systemsx/cisd/bds/storage/IStorage.java index 841eae10582..249bf935f22 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/IStorage.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/IStorage.java @@ -18,10 +18,9 @@ package ch.systemsx.cisd.bds.storage; import ch.systemsx.cisd.bds.exception.StorageException; - /** * Abstraction of a hierarchical storage. - * + * * @author Franz-Josef Elmer */ public interface IStorage @@ -30,14 +29,14 @@ public interface IStorage * Mounts this storage. May perform some initializations. Should be called before calling {@link #getRoot()}. */ public void mount(); - + /** - * Returns root directory of this storage. + * Returns root directory of this storage. * * @throws StorageException if invoked before {@link #mount()} or after {@link #unmount()}. */ public IDirectory getRoot(); - + /** * Unmounts this storage. May perform some finalization (e.g. make cached data persistent). */ diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/NodeFilters.java b/bds/source/java/ch/systemsx/cisd/bds/storage/NodeFilters.java index 966673912ec..4232d9e3f5f 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/NodeFilters.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/NodeFilters.java @@ -46,7 +46,8 @@ public final class NodeFilters /** * Creates filter nodes based on the extension (what the filename ends with). */ - public final static INodeFilter createExtensionNodeFilter(final boolean ignoreCase, final String... extensions) + public final static INodeFilter createExtensionNodeFilter(final boolean ignoreCase, + final String... extensions) { assert extensions != null : "Given extensions can not be null."; return new SuffixNodeFilter(ignoreCase, toSuffixes(extensions)); @@ -103,12 +104,12 @@ public final class NodeFilters { if (ignoreCase) { - return s.toLowerCase(); + return s.toLowerCase(); } else { return s; } } } - + } diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/AbstractNode.java b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/AbstractNode.java index 87091b93a08..c79cf19f0ec 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/AbstractNode.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/AbstractNode.java @@ -30,8 +30,8 @@ import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException; */ abstract class AbstractNode implements INode { - protected final static File moveFileToDirectory(final File source, final File directory, final String nameOrNull) - throws EnvironmentFailureException + protected final static File moveFileToDirectory(final File source, final File directory, + final String nameOrNull) throws EnvironmentFailureException { assert source != null; assert directory != null && directory.isDirectory(); @@ -49,8 +49,9 @@ abstract class AbstractNode implements INode final boolean successful = source.renameTo(destination); if (successful == false) { - throw EnvironmentFailureException.fromTemplate("Couldn't not move file '%s' to directory '%s'.", source - .getAbsolutePath(), directory.getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate( + "Couldn't not move file '%s' to directory '%s'.", source.getAbsolutePath(), + directory.getAbsolutePath()); } } return destination; @@ -72,7 +73,8 @@ abstract class AbstractNode implements INode } if (file.exists() == false) { - throw new StorageException(String.format("Non existing file '%s'.", file.getAbsolutePath())); + throw new StorageException(String.format("Non existing file '%s'.", file + .getAbsolutePath())); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Directory.java b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Directory.java index 791543b517d..50fb5acf7fc 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Directory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Directory.java @@ -43,7 +43,8 @@ final class Directory extends AbstractNode implements IDirectory super(directory); if (directory.isDirectory() == false) { - throw new StorageException(String.format("Not a directory '%s'.", directory.getAbsolutePath())); + throw new StorageException(String.format("Not a directory '%s'.", directory + .getAbsolutePath())); } } @@ -90,15 +91,16 @@ final class Directory extends AbstractNode implements IDirectory { if (dir.isDirectory() == false) { - throw new StorageException("There already exists a file named '" + name + "' in directory " + this); + throw new StorageException("There already exists a file named '" + name + + "' in directory " + this); } return new Directory(dir); } boolean successful = dir.mkdir(); if (successful == false) { - throw new EnvironmentFailureException("Couldn't create directory " + dir.getAbsolutePath() - + " for some unknown reason."); + throw new EnvironmentFailureException("Couldn't create directory " + + dir.getAbsolutePath() + " for some unknown reason."); } return new Directory(dir); } @@ -140,8 +142,9 @@ final class Directory extends AbstractNode implements IDirectory } } catch (IOException ex) { - throw EnvironmentFailureException.fromTemplate(ex, "Couldn't not copy file '%s' to directory '%s'.", - file, nodeFile.getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate(ex, + "Couldn't not copy file '%s' to directory '%s'.", file, nodeFile + .getAbsolutePath()); } } return NodeFactory.createNode(newFile); @@ -152,7 +155,8 @@ final class Directory extends AbstractNode implements IDirectory assert node != null : "Node can not be null."; assert name != null : "Name can not be null."; final java.io.File file = getNodeFile(node); - final java.io.File fileLink = LinkMakerProvider.getLinkMaker().tryCopy(file, nodeFile, name); + final java.io.File fileLink = + LinkMakerProvider.getLinkMaker().tryCopy(file, nodeFile, name); if (fileLink != null) { final Link link = (Link) NodeFactory.createLinkNode(name, file); @@ -200,8 +204,9 @@ final class Directory extends AbstractNode implements IDirectory FileUtils.copyDirectoryToDirectory(nodeFile, directory); } catch (IOException ex) { - throw EnvironmentFailureException.fromTemplate(ex, "Couldn't copy directory '%s' to directory '%s'.", - nodeFile.getAbsolutePath(), directory.getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate(ex, + "Couldn't copy directory '%s' to directory '%s'.", nodeFile.getAbsolutePath(), + directory.getAbsolutePath()); } } @@ -213,14 +218,15 @@ final class Directory extends AbstractNode implements IDirectory { if (FileUtilities.deleteRecursively(file, null) == false) { - throw EnvironmentFailureException.fromTemplate("Couldn't remove directory '%s'.", file - .getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate("Couldn't remove directory '%s'.", + file.getAbsolutePath()); } } else if (file.isFile()) { if (file.delete() == false) { - throw EnvironmentFailureException.fromTemplate("Couldn't remove file '%s'.", file.getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate("Couldn't remove file '%s'.", file + .getAbsolutePath()); } } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/File.java b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/File.java index 7f9b7aa7601..8bde99e3f57 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/File.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/File.java @@ -54,7 +54,8 @@ final class File extends AbstractNode implements IFile return IOUtils.toByteArray(inputStream); } catch (IOException ex) { - throw new EnvironmentFailureException("Couldn't get data from file " + nodeFile.getAbsolutePath(), ex); + throw new EnvironmentFailureException("Couldn't get data from file " + + nodeFile.getAbsolutePath(), ex); } finally { IOUtils.closeQuietly(inputStream); @@ -68,7 +69,8 @@ final class File extends AbstractNode implements IFile return new FileInputStream(nodeFile); } catch (FileNotFoundException ex) { - throw new EnvironmentFailureException("Couldn't open input stream for file " + nodeFile.getAbsolutePath()); + throw new EnvironmentFailureException("Couldn't open input stream for file " + + nodeFile.getAbsolutePath()); } } @@ -90,8 +92,9 @@ final class File extends AbstractNode implements IFile FileUtils.copyFileToDirectory(nodeFile, directory); } catch (IOException ex) { - throw EnvironmentFailureException.fromTemplate(ex, "Couldn't not copy file '%s' to directory '%s'.", - nodeFile.getAbsolutePath(), directory.getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate(ex, + "Couldn't not copy file '%s' to directory '%s'.", nodeFile.getAbsolutePath(), + directory.getAbsolutePath()); } } diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/FileStorage.java b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/FileStorage.java index 52c97f329e3..09ff0a5e842 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/FileStorage.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/FileStorage.java @@ -24,13 +24,13 @@ import ch.systemsx.cisd.bds.storage.IStorage; /** * Implementation of {@link IStorage} based on the file system. - * + * * @author Franz-Josef Elmer */ public class FileStorage implements IStorage { private final Directory root; - + private boolean mounted; /** @@ -42,7 +42,7 @@ public class FileStorage implements IStorage { root = new Directory(folder); } - + public IDirectory getRoot() { if (mounted == false) diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Link.java b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Link.java index e44ee8283c0..b632c04ae7b 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Link.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/Link.java @@ -40,7 +40,8 @@ final class Link implements ILink { assert name != null : "A name must be specified."; assert reference != null : "Reference can not be null."; - assert reference instanceof IFile : "Given reference must be of type IFile: " + reference.getClass().getName(); + assert reference instanceof IFile : "Given reference must be of type IFile: " + + reference.getClass().getName(); assert reference.isValid() : "Given reference must be valid: " + reference; this.name = name; this.reference = reference; diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactory.java b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactory.java index cac88fa1ff0..293fabd241b 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactory.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactory.java @@ -67,8 +67,8 @@ public final class NodeFactory return file.getCanonicalPath(); } catch (IOException ex) { - throw new EnvironmentFailureException("Couldn't get canonical path of file '" + file.getAbsolutePath() - + "'", ex); + throw new EnvironmentFailureException("Couldn't get canonical path of file '" + + file.getAbsolutePath() + "'", ex); } } @@ -89,12 +89,14 @@ public final class NodeFactory * This only works for <i>symbolic</i> links and not for <i>hard</i> links. * </p> */ - public final static ILink createLinkNode(final java.io.File file) throws EnvironmentFailureException + public final static ILink createLinkNode(final java.io.File file) + throws EnvironmentFailureException { final String canonicalPath = getCanonicalPath(file); final String absolutePath = file.getAbsolutePath(); assert absolutePath.equals(canonicalPath) == false : String.format( - "Given file must be a link [absolute=%s,canonical=%s].", absolutePath, canonicalPath); + "Given file must be a link [absolute=%s,canonical=%s].", absolutePath, + canonicalPath); return new Link(file.getName(), createNode(new java.io.File(canonicalPath))); } diff --git a/bds/source/java/ch/systemsx/cisd/bds/storage/hdf5/HDF5Storage.java b/bds/source/java/ch/systemsx/cisd/bds/storage/hdf5/HDF5Storage.java index 6a2a29b8444..d560cc27357 100644 --- a/bds/source/java/ch/systemsx/cisd/bds/storage/hdf5/HDF5Storage.java +++ b/bds/source/java/ch/systemsx/cisd/bds/storage/hdf5/HDF5Storage.java @@ -24,7 +24,7 @@ import ch.systemsx.cisd.common.exceptions.NotImplementedException; /** * Storage based on HDF5. - * + * * @author Franz-Josef Elmer */ public class HDF5Storage implements IStorage @@ -33,7 +33,7 @@ public class HDF5Storage implements IStorage { assert hdf5File != null : "Unspecified HDF5 file."; } - + public IDirectory getRoot() { throw new NotImplementedException(); diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureFactoryTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureFactoryTest.java index 84890cef0b9..3a1d488ac42 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureFactoryTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureFactoryTest.java @@ -48,8 +48,10 @@ public class DataStructureFactoryTest @Test public void testGetDataStructureClassFor() { - assertEquals(DataStructureV1_0.class, DataStructureFactory.getDataStructureClassFor(new Version(1, 0))); - assertEquals(DataStructureV1_0.class, DataStructureFactory.getDataStructureClassFor(new Version(1, 1))); + assertEquals(DataStructureV1_0.class, DataStructureFactory + .getDataStructureClassFor(new Version(1, 0))); + assertEquals(DataStructureV1_0.class, DataStructureFactory + .getDataStructureClassFor(new Version(1, 1))); } @Test @@ -76,7 +78,8 @@ public class DataStructureFactoryTest } }); - IDataStructure dataStructure = DataStructureFactory.createDataStructure(storage, new Version(1, 0)); + IDataStructure dataStructure = + DataStructureFactory.createDataStructure(storage, new Version(1, 0)); assertEquals(DataStructureV1_0.class, dataStructure.getClass()); } } diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureLoaderTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureLoaderTest.java index 5212ea8a796..d22ac7c21b1 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureLoaderTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureLoaderTest.java @@ -45,7 +45,8 @@ public final class DataStructureLoaderTest extends AbstractFileSystemTestCase dataStructure.setFormat(UnknownFormatV1_0.UNKNOWN_1_0); ExperimentIdentifier experimentIdentifier = new ExperimentIdentifier("g", "p", "e"); dataStructure.setExperimentIdentifier(experimentIdentifier); - ExperimentRegistrator experimentRegistrator = new ExperimentRegistrator("john", "doe", "j@doe"); + ExperimentRegistrator experimentRegistrator = + new ExperimentRegistrator("john", "doe", "j@doe"); dataStructure.setExperimentRegistrator(experimentRegistrator); dataStructure.setExperimentRegistrationDate(new ExperimentRegistratorDate(new Date(0))); dataStructure.setMeasurementEntity(new MeasurementEntity("a", "b")); diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureTestV1_0.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureTestV1_0.java index 9f347c32fec..87a0b7916b1 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureTestV1_0.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/DataStructureTestV1_0.java @@ -97,7 +97,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase fail("DataStructureException expected."); } catch (DataStructureException e) { - assertEquals("Couldn't create formatted data because of unspecified format.", e.getMessage()); + assertEquals("Couldn't create formatted data because of unspecified format.", e + .getMessage()); } } @@ -108,7 +109,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase dataStructure.setProcessingType(ProcessingType.COMPUTED_DATA); IDirectory root = storage.getRoot(); IDirectory metaData = Utilities.getSubDirectory(root, DataStructureV1_0.DIR_METADATA); - assertEquals("COMPUTED_DATA\n", Utilities.getString(metaData, ProcessingType.PROCESSING_TYPE)); + assertEquals("COMPUTED_DATA\n", Utilities.getString(metaData, + ProcessingType.PROCESSING_TYPE)); } @Test @@ -119,7 +121,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase dataStructure.setProcessingType(ProcessingType.COMPUTED_DATA); IDirectory root = storage.getRoot(); IDirectory metaData = Utilities.getSubDirectory(root, DataStructureV1_0.DIR_METADATA); - assertEquals("COMPUTED_DATA\n", Utilities.getString(metaData, ProcessingType.PROCESSING_TYPE)); + assertEquals("COMPUTED_DATA\n", Utilities.getString(metaData, + ProcessingType.PROCESSING_TYPE)); } @Test @@ -355,10 +358,12 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase dataStructure.setFormat(UnknownFormatV1_0.UNKNOWN_1_0); ExperimentIdentifier experimentIdentifier = new ExperimentIdentifier("g", "p", "e"); dataStructure.setExperimentIdentifier(experimentIdentifier); - ExperimentRegistratorDate experimentRegistratorDate = new ExperimentRegistratorDate(new Date(4711L * 4711000L)); + ExperimentRegistratorDate experimentRegistratorDate = + new ExperimentRegistratorDate(new Date(4711L * 4711000L)); System.out.println(experimentRegistratorDate); dataStructure.setExperimentRegistrationDate(experimentRegistratorDate); - ExperimentRegistrator experimentRegistrator = new ExperimentRegistrator("john", "doe", "j@doe"); + ExperimentRegistrator experimentRegistrator = + new ExperimentRegistrator("john", "doe", "j@doe"); dataStructure.setExperimentRegistrator(experimentRegistrator); MeasurementEntity measurementEntity = new MeasurementEntity("cp001", "plate"); dataStructure.setMeasurementEntity(measurementEntity); @@ -384,7 +389,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase reloadedDataStructure.open(); assertEquals("42\n", Utilities.getString(reloadedDataStructure.getOriginalData(), "answer")); assertEquals(experimentIdentifier, reloadedDataStructure.getExperimentIdentifier()); - assertEquals(experimentRegistratorDate, reloadedDataStructure.getExperimentRegistratorDate()); + assertEquals(experimentRegistratorDate, reloadedDataStructure + .getExperimentRegistratorDate()); assertEquals(experimentRegistrator, reloadedDataStructure.getExperimentRegistrator()); assertEquals(measurementEntity, reloadedDataStructure.getMeasurementEntity()); assertEquals(ProcessingType.RAW_DATA, reloadedDataStructure.getProcessingType()); @@ -393,8 +399,10 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase checkFormattedData(reloadedDataStructure.getFormattedData()); IDirectory metaDataDir = Utilities.getSubDirectory(root, DIR_METADATA); - IDirectory checksumDir = Utilities.getSubDirectory(metaDataDir, ChecksumHandler.CHECKSUM_DIRECTORY); - assertEquals("a1d0c6e83f027327d8461063f4ac58a6 answer\n" + "d41d8cd98f00b204e9800998ecf8427e origFile1\n" + IDirectory checksumDir = + Utilities.getSubDirectory(metaDataDir, ChecksumHandler.CHECKSUM_DIRECTORY); + assertEquals("a1d0c6e83f027327d8461063f4ac58a6 answer\n" + + "d41d8cd98f00b204e9800998ecf8427e origFile1\n" + "d41d8cd98f00b204e9800998ecf8427e origFile2\n", Utilities.getString(checksumDir, DataStructureV1_0.DIR_ORIGINAL)); } @@ -468,8 +476,9 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase fail("DataStructureException expected."); } catch (DataStructureException e) { - assertEquals("Version of loaded data structure is V2.0 which is not backward compatible with V1.0", e - .getMessage()); + assertEquals( + "Version of loaded data structure is V2.0 which is not backward compatible with V1.0", + e.getMessage()); } } @@ -480,7 +489,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase storage.mount(); IDirectory root = storage.getRoot(); IDirectory metaData = Utilities.getSubDirectory(root, DataStructureV1_0.DIR_METADATA); - new Format(UnknownFormatV1_0.UNKNOWN_1_0.getCode(), new Version(1, 1), null).saveTo(metaData); + new Format(UnknownFormatV1_0.UNKNOWN_1_0.getCode(), new Version(1, 1), null) + .saveTo(metaData); storage.unmount(); dataStructure.open(); assertEquals(UnknownFormatV1_0.UNKNOWN_1_0, dataStructure.getFormattedData().getFormat()); @@ -493,7 +503,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase storage.mount(); IDirectory root = storage.getRoot(); IDirectory metaData = Utilities.getSubDirectory(root, DataStructureV1_0.DIR_METADATA); - new Format(UnknownFormatV1_0.UNKNOWN_1_0.getCode(), new Version(2, 0), null).saveTo(metaData); + new Format(UnknownFormatV1_0.UNKNOWN_1_0.getCode(), new Version(2, 0), null) + .saveTo(metaData); storage.unmount(); dataStructure.open(); try @@ -533,7 +544,8 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase IDirectory originalDataDir = data.makeDirectory(DataStructureV1_0.DIR_ORIGINAL); originalDataDir.addKeyValuePair("file1", "This is my first file."); IDirectory metaData = root.makeDirectory(DataStructureV1_0.DIR_METADATA); - new Format(UnknownFormatV1_0.UNKNOWN_1_0.getCode(), new Version(2, 0), null).saveTo(metaData); + new Format(UnknownFormatV1_0.UNKNOWN_1_0.getCode(), new Version(2, 0), null) + .saveTo(metaData); new ExperimentIdentifier("g", "p", "e").saveTo(metaData); new ExperimentRegistratorDate(new Date(0)).saveTo(metaData); new ExperimentRegistrator("john", "doe", "j@doe").saveTo(metaData); @@ -547,6 +559,7 @@ public final class DataStructureTestV1_0 extends AbstractFileSystemTestCase private final static void createExampleChecksum(final IDirectory metaData) { final IDirectory checksumDir = metaData.makeDirectory(ChecksumHandler.CHECKSUM_DIRECTORY); - checksumDir.addKeyValuePair(DataStructureV1_0.DIR_ORIGINAL, "23b447be20a6ddfe875a8b59ceae83ff file1"); + checksumDir.addKeyValuePair(DataStructureV1_0.DIR_ORIGINAL, + "23b447be20a6ddfe875a8b59ceae83ff file1"); } } diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/UtilitiesTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/UtilitiesTest.java index 8dd0c018f28..8f9c0bfb726 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/UtilitiesTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/UtilitiesTest.java @@ -97,7 +97,8 @@ public class UtilitiesTest extends AbstractFileSystemTestCase dir2.mkdir(); createFile(dir1, "file2"); createFile(dir2, "file3"); - final List<String> nodes = Utilities.listNodes(NodeFactory.createDirectoryNode(workingDirectory), null); + final List<String> nodes = + Utilities.listNodes(NodeFactory.createDirectoryNode(workingDirectory), null); assertEquals(3, nodes.size()); Collections.sort(nodes); assertEquals("dir1/file2", nodes.get(0)); diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/handler/MappingFileHandlerTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/handler/MappingFileHandlerTest.java index 56e092ff44a..d43a3bf36e6 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/handler/MappingFileHandlerTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/handler/MappingFileHandlerTest.java @@ -43,7 +43,8 @@ public final class MappingFileHandlerTest extends AbstractFileSystemTestCase { private final static String MAPPING_FILE_CONTENT = - "row1/row2_column1.tiff\tI\toriginal1.tiff\n" + "row2/row3_column2.tiff\tI\toriginal2.tiff\n"; + "row1/row2_column1.tiff\tI\toriginal1.tiff\n" + + "row2/row3_column2.tiff\tI\toriginal2.tiff\n"; private MappingFileHandler handler; @@ -85,9 +86,9 @@ public final class MappingFileHandlerTest extends AbstractFileSystemTestCase @Override @BeforeMethod - public void setup() throws IOException + public void setUp() throws IOException { - super.setup(); + super.setUp(); prepareMappingFileHandler(); } @@ -124,8 +125,10 @@ public final class MappingFileHandlerTest extends AbstractFileSystemTestCase @Test public final void testPerformClosing() throws IOException { - handler.addReference(new Reference("row1/row2_column1.tiff", "original1.tiff", ReferenceType.IDENTICAL)); - handler.addReference(new Reference("row2/row3_column2.tiff", "original2.tiff", ReferenceType.IDENTICAL)); + handler.addReference(new Reference("row1/row2_column1.tiff", "original1.tiff", + ReferenceType.IDENTICAL)); + handler.addReference(new Reference("row2/row3_column2.tiff", "original2.tiff", + ReferenceType.IDENTICAL)); handler.performClosing(); final File mappingFile = new File(workingDirectory, MappingFileHandler.MAPPING_FILE); assertTrue(mappingFile.exists()); diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSDataStructureTestV1_0.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSDataStructureTestV1_0.java index d0b8b6bc044..b08b007999a 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSDataStructureTestV1_0.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSDataStructureTestV1_0.java @@ -62,10 +62,14 @@ public final class HCSDataStructureTestV1_0 extends AbstractFileSystemTestCase { dataStructure.setFormat(HCSImageFormatV1_0.HCS_IMAGE_1_0); dataStructure.addFormatParameter(new FormatParameter(HCSImageFormatV1_0.DEVICE_ID, "M1")); - dataStructure.addFormatParameter(new FormatParameter(HCSImageFormatV1_0.CONTAINS_ORIGINAL_DATA, Boolean.TRUE)); - dataStructure.addFormatParameter(new FormatParameter(ChannelList.NUMBER_OF_CHANNELS, createChannelList())); - dataStructure.addFormatParameter(new FormatParameter(PlateGeometry.PLATE_GEOMETRY, new PlateGeometry(2, 3))); - dataStructure.addFormatParameter(new FormatParameter(WellGeometry.WELL_GEOMETRY, new WellGeometry(7, 5))); + dataStructure.addFormatParameter(new FormatParameter( + HCSImageFormatV1_0.CONTAINS_ORIGINAL_DATA, Boolean.TRUE)); + dataStructure.addFormatParameter(new FormatParameter(ChannelList.NUMBER_OF_CHANNELS, + createChannelList())); + dataStructure.addFormatParameter(new FormatParameter(PlateGeometry.PLATE_GEOMETRY, + new PlateGeometry(2, 3))); + dataStructure.addFormatParameter(new FormatParameter(WellGeometry.WELL_GEOMETRY, + new WellGeometry(7, 5))); } // @@ -109,7 +113,9 @@ public final class HCSDataStructureTestV1_0 extends AbstractFileSystemTestCase setFormatAndFormatParameters(); dataStructure.close(); // And loading... - final IDataStructure ds = new DataStructureLoader(workingDirectory.getParentFile()).load(getClass().getName()); + final IDataStructure ds = + new DataStructureLoader(workingDirectory.getParentFile()) + .load(getClass().getName()); assertNotNull(ds); } } \ No newline at end of file diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedDataTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedDataTest.java index e868022dd46..2d3c376f9e2 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedDataTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/HCSImageFormattedDataTest.java @@ -94,8 +94,8 @@ public class HCSImageFormattedDataTest extends AbstractFileSystemTestCase } }); formattedData = - (HCSImageFormattedData) FormattedDataFactory.createFormattedData(directory, format, null, - formatParameters); + (HCSImageFormattedData) FormattedDataFactory.createFormattedData(directory, format, + null, formatParameters); } private final void prepareStandardNode() @@ -213,8 +213,8 @@ public class HCSImageFormattedDataTest extends AbstractFileSystemTestCase } }); final NodePath nodePath = - formattedData.addStandardNode(imageRootDirectory, ORIGINAL_TIFF, channelIndex, PLATE_LOCATION, - WELL_LOCATION); + formattedData.addStandardNode(imageRootDirectory, ORIGINAL_TIFF, channelIndex, + PLATE_LOCATION, WELL_LOCATION); final String standardFileName = "row2_column1.tiff"; assertNotNull(nodePath); assertTrue(nodePath.getNode() instanceof ILink); @@ -225,7 +225,8 @@ public class HCSImageFormattedDataTest extends AbstractFileSystemTestCase assertTrue(standardFile instanceof IFile); assertEquals(standardFileName, standardFile.getName()); // Node should still be in the 'original' directory. - assertNotNull(((IDirectory) originalNode.tryGetNode(IMAGE_ROOT_DIRECTORY_NAME)).tryGetNode(ORIGINAL_TIFF)); + assertNotNull(((IDirectory) originalNode.tryGetNode(IMAGE_ROOT_DIRECTORY_NAME)) + .tryGetNode(ORIGINAL_TIFF)); context.assertIsSatisfied(); } @@ -247,8 +248,8 @@ public class HCSImageFormattedDataTest extends AbstractFileSystemTestCase } }); final NodePath nodePath = - formattedData.addStandardNode(imageRootDirectory, ORIGINAL_TIFF, channelIndex, PLATE_LOCATION, - WELL_LOCATION); + formattedData.addStandardNode(imageRootDirectory, ORIGINAL_TIFF, channelIndex, + PLATE_LOCATION, WELL_LOCATION); final String standardFileName = "row2_column1.tiff"; assertNotNull(nodePath); assertTrue(nodePath.getNode() instanceof IFile); @@ -277,7 +278,8 @@ public class HCSImageFormattedDataTest extends AbstractFileSystemTestCase will(returnValue(standardNode)); } }); - final INode node = formattedData.tryGetStandardNodeAt(channelIndex, PLATE_LOCATION, WELL_LOCATION); + final INode node = + formattedData.tryGetStandardNodeAt(channelIndex, PLATE_LOCATION, WELL_LOCATION); assertNull(node); context.assertIsSatisfied(); } @@ -298,7 +300,8 @@ public class HCSImageFormattedDataTest extends AbstractFileSystemTestCase will(returnValue(standardNode)); } }); - final INode node = formattedData.tryGetStandardNodeAt(channelIndex, PLATE_LOCATION, WELL_LOCATION); + final INode node = + formattedData.tryGetStandardNodeAt(channelIndex, PLATE_LOCATION, WELL_LOCATION); assertNotNull(node); context.assertIsSatisfied(); } diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/PlateGeometryTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/PlateGeometryTest.java index 9485681f345..4bd1ee2702e 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/PlateGeometryTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/PlateGeometryTest.java @@ -84,7 +84,8 @@ public final class PlateGeometryTest extends AbstractFileSystemTestCase { testSaveTo(); final IDirectory dir = NodeFactory.createDirectoryNode(workingDirectory); - final IDirectory geoDir = Utilities.getOrCreateSubDirectory(dir, PlateGeometry.PLATE_GEOMETRY); + final IDirectory geoDir = + Utilities.getOrCreateSubDirectory(dir, PlateGeometry.PLATE_GEOMETRY); final Geometry loaded = PlateGeometry.loadFrom(geoDir); assertNotNull(loaded); assertTrue(loaded.getRows() == 2); diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/WellGeometryTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/WellGeometryTest.java index 179ef192b9b..34331fd9b5e 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/WellGeometryTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/hcs/WellGeometryTest.java @@ -84,7 +84,8 @@ public final class WellGeometryTest extends AbstractFileSystemTestCase { testSaveTo(); final IDirectory dir = NodeFactory.createDirectoryNode(workingDirectory); - final IDirectory geoDir = Utilities.getOrCreateSubDirectory(dir, WellGeometry.WELL_GEOMETRY); + final IDirectory geoDir = + Utilities.getOrCreateSubDirectory(dir, WellGeometry.WELL_GEOMETRY); final Geometry loaded = WellGeometry.loadFrom(geoDir); assertNotNull(loaded); assertTrue(loaded.getRows() == 2); diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/FileTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/FileTest.java index e834a0f16b9..c948f34ab3b 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/FileTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/FileTest.java @@ -59,7 +59,8 @@ public final class FileTest extends AbstractFileSystemTestCase java.io.File subdir = new java.io.File(workingDirectory, "subdir"); subdir.mkdir(); stringFile.extractTo(subdir); - assertEquals("Hello\nworld!\n", FileUtilities.loadToString(new java.io.File(subdir, stringFile.getName()))); + assertEquals("Hello\nworld!\n", FileUtilities.loadToString(new java.io.File(subdir, + stringFile.getName()))); } @Test @@ -73,7 +74,8 @@ public final class FileTest extends AbstractFileSystemTestCase file.moveTo(workingDirectory); assertEquals(false, directory.iterator().hasNext()); - assertEquals("property 1", FileUtilities.loadToString(new java.io.File(workingDirectory, "p1")).trim()); + assertEquals("property 1", FileUtilities.loadToString( + new java.io.File(workingDirectory, "p1")).trim()); } @Test diff --git a/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactoryTest.java b/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactoryTest.java index 330335e396a..e5bed9cffe9 100644 --- a/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactoryTest.java +++ b/bds/sourceTest/java/ch/systemsx/cisd/bds/storage/filesystem/NodeFactoryTest.java @@ -29,7 +29,7 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; /** * Test cases for corresponding {@link NodeFactory} class. - * + * * @author Franz-Josef Elmer */ public class NodeFactoryTest extends AbstractFileSystemTestCase @@ -43,7 +43,7 @@ public class NodeFactoryTest extends AbstractFileSystemTestCase assertTrue(node instanceof IFile); assertEquals("text.txt", node.getName()); } - + @Test public void testCreateDirectoryNode() { diff --git a/common/source/java/ch/systemsx/cisd/common/Constants.java b/common/source/java/ch/systemsx/cisd/common/Constants.java index 1306a277a0d..7b2e82f670e 100644 --- a/common/source/java/ch/systemsx/cisd/common/Constants.java +++ b/common/source/java/ch/systemsx/cisd/common/Constants.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common; /** * Constants common to more than one CISD project. - * + * * @author Bernd Rinn */ public class Constants @@ -26,11 +26,12 @@ public class Constants /** String that indicates a marker file */ public static final String MARKER_PREFIX = ".MARKER_"; - + /** The prefix of marker files that indicate that the processing of some path is finished. */ public static final String IS_FINISHED_PREFIX = MARKER_PREFIX + "is_finished_"; /** The prefix of marker files that indicate that the processing of some path is finished. */ - public static final String DELETION_IN_PROGRESS_PREFIX = MARKER_PREFIX + "deletion_in_progress_"; + public static final String DELETION_IN_PROGRESS_PREFIX = + MARKER_PREFIX + "deletion_in_progress_"; } diff --git a/common/source/java/ch/systemsx/cisd/common/Script.java b/common/source/java/ch/systemsx/cisd/common/Script.java index a15ecd91584..734bfccdfb9 100644 --- a/common/source/java/ch/systemsx/cisd/common/Script.java +++ b/common/source/java/ch/systemsx/cisd/common/Script.java @@ -20,14 +20,16 @@ import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; /** - * Bean class for a script. Holds script name and code. - * + * Bean class for a script. Holds script name and code. + * * @author Franz-Josef Elmer */ public class Script { private final String name; + private final String code; + private final String version; /** @@ -37,7 +39,7 @@ public class Script { this(name, code, "-"); } - + /** * Creates an instance for the specified script name, code and version. */ @@ -86,5 +88,5 @@ public class Script { return HashCodeBuilder.reflectionHashCode(this); } - + } diff --git a/common/source/java/ch/systemsx/cisd/common/collections/AbstractCollectionDecorator.java b/common/source/java/ch/systemsx/cisd/common/collections/AbstractCollectionDecorator.java index 85094d8e048..24bf50f28c4 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/AbstractCollectionDecorator.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/AbstractCollectionDecorator.java @@ -124,7 +124,7 @@ public abstract class AbstractCollectionDecorator<E> implements Collection<E> { return collection.retainAll(coll); } - + // // Object // diff --git a/common/source/java/ch/systemsx/cisd/common/collections/CollectionIO.java b/common/source/java/ch/systemsx/cisd/common/collections/CollectionIO.java index 7bd8d4a76d3..222eeb502e9 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/CollectionIO.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/CollectionIO.java @@ -49,7 +49,8 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; public class CollectionIO { - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, FileUtilities.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, FileUtilities.class); /** * Reads a collection of {@link String}s from a <var>resource</var>. One line in the resource corresponds to one @@ -61,7 +62,8 @@ public class CollectionIO */ public static boolean readCollectionFromResource(String resource, Collection<String> collection) { - return readCollectionFromResource(resource, collection, FromStringIdentityConverter.getInstance()); + return readCollectionFromResource(resource, collection, FromStringIdentityConverter + .getInstance()); } /** @@ -82,7 +84,8 @@ public class CollectionIO machineLog.error(String.format("Resource '%s' not found.", resource)); return false; } - return readCollection(resourceStream, collection, converter, String.format("<resource '%s'>", resource)); + return readCollection(resourceStream, collection, converter, String.format( + "<resource '%s'>", resource)); } /** @@ -106,12 +109,13 @@ public class CollectionIO * @param converter The converter to use in order to convert each line in the file. * @return <code>true</code> if the collection was read successfully, or <code>false</code> otherwise. */ - public static <T> boolean readCollection(File file, Collection<T> collection, IFromStringConverter<T> converter) + public static <T> boolean readCollection(File file, Collection<T> collection, + IFromStringConverter<T> converter) { try { - return readCollection(new FileInputStream(file), collection, converter, String.format("<file '%s'>", file - .getPath())); + return readCollection(new FileInputStream(file), collection, converter, String.format( + "<file '%s'>", file.getPath())); } catch (FileNotFoundException e) { machineLog.error(String.format("File '%s' is not accessible.", file.getPath()), e); @@ -205,7 +209,7 @@ public class CollectionIO } return true; } - + /** * Reads a list of {@link String}s from a <var>resource</var>. One line in the resource corresponds to one entry * in the list. @@ -227,7 +231,8 @@ public class CollectionIO * @return A new {@link ArrayList} containing the entries from the <var>file</var>, or <code>null</code> if there * is an error when reading the <var>file</var>. */ - public static <T> List<T> readListFromResource(String resource, IFromStringConverter<T> converter) + public static <T> List<T> readListFromResource(String resource, + IFromStringConverter<T> converter) { assert resource != null; assert converter != null; @@ -370,7 +375,8 @@ public class CollectionIO * @param converter The {@link IToStringConverter} to use to convert a <var>T</var> value into a {@link String}. * @return <code>true</code> if the collection was written successfully, or <code>false</code> otherwise. */ - public static <T> boolean writeIterable(File file, Iterable<T> iterable, IToStringConverter<? super T> converter) + public static <T> boolean writeIterable(File file, Iterable<T> iterable, + IToStringConverter<? super T> converter) { FileOutputStream fos = null; try @@ -486,8 +492,8 @@ public class CollectionIO * @param iterable The iterable to write to the writer. * @return <code>true</code> if the collection was written successfully, or <code>false</code> otherwise. */ - public final static <T> boolean writeIterable(final PrintWriter writer, final Iterable<T> iterable, - final IToStringConverter<? super T> converterOrNull) + public final static <T> boolean writeIterable(final PrintWriter writer, + final Iterable<T> iterable, final IToStringConverter<? super T> converterOrNull) { assert writer != null : "Given PrintWriter can not be null"; assert iterable != null : "Given Iterable can not be null"; diff --git a/common/source/java/ch/systemsx/cisd/common/collections/CollectionStyle.java b/common/source/java/ch/systemsx/cisd/common/collections/CollectionStyle.java index 5155e4792f2..35783b9113a 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/CollectionStyle.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/CollectionStyle.java @@ -24,8 +24,8 @@ package ch.systemsx.cisd.common.collections; public enum CollectionStyle { /** Default <code>CollectionStyle</code>. */ - DEFAULT_COLLECTION_STYLE("[", "]", ", "), NO_BOUNDARY_COLLECTION_STYLE("", "", ", "), NICE_COLLECTION_STYLE("'", - "'", "', '"); + DEFAULT_COLLECTION_STYLE("[", "]", ", "), NO_BOUNDARY_COLLECTION_STYLE("", "", ", "), + NICE_COLLECTION_STYLE("'", "'", "', '"); private final String collectionStart; diff --git a/common/source/java/ch/systemsx/cisd/common/collections/CollectionUtils.java b/common/source/java/ch/systemsx/cisd/common/collections/CollectionUtils.java index 78586100752..f0f326bd62f 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/CollectionUtils.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/CollectionUtils.java @@ -71,7 +71,8 @@ public final class CollectionUtils * @param maxLength the maximum number of items that should be shown. If <code>-1</code> then all items will be * displayed. */ - public final static <T> String abbreviate(final T[] objects, final int maxLength, final CollectionStyle style) + public final static <T> String abbreviate(final T[] objects, final int maxLength, + final CollectionStyle style) { return abbreviate(objects, maxLength, true, ToStringDefaultConverter.getInstance(), style); } @@ -103,7 +104,8 @@ public final class CollectionUtils public final static <T> String abbreviate(final Collection<T> collection, final int maxLength, final IToStringConverter<? super T> converter) { - return abbreviate(collection, maxLength, converter, CollectionStyle.DEFAULT_COLLECTION_STYLE); + return abbreviate(collection, maxLength, converter, + CollectionStyle.DEFAULT_COLLECTION_STYLE); } /** @@ -130,7 +132,8 @@ public final class CollectionUtils * @param maxLength the maximum number of items that should be shown. If <code>-1</code> then all items will be * displayed. */ - public final static <T> String abbreviate(final T[] objects, final int maxLength, final boolean showLeft) + public final static <T> String abbreviate(final T[] objects, final int maxLength, + final boolean showLeft) { return abbreviate(objects, maxLength, showLeft, ToStringDefaultConverter.getInstance()); } @@ -159,10 +162,11 @@ public final class CollectionUtils * @param maxLength the maximum number of items that should be shown. If <code>-1</code> then all items will be * displayed. */ - public final static <T> String abbreviate(final T[] objects, final int maxLength, final boolean showLeft, - final IToStringConverter<? super T> converter) + public final static <T> String abbreviate(final T[] objects, final int maxLength, + final boolean showLeft, final IToStringConverter<? super T> converter) { - return abbreviate(objects, maxLength, showLeft, converter, CollectionStyle.DEFAULT_COLLECTION_STYLE); + return abbreviate(objects, maxLength, showLeft, converter, + CollectionStyle.DEFAULT_COLLECTION_STYLE); } /** @@ -171,7 +175,8 @@ public final class CollectionUtils * {@link CollectionStyle#DEFAULT_COLLECTION_STYLE} is used and all items is displayed. * </p> */ - public final static <T> String abbreviate(final T[] objects, final IToStringConverter<? super T> converter) + public final static <T> String abbreviate(final T[] objects, + final IToStringConverter<? super T> converter) { return abbreviate(objects, -1, false, converter, CollectionStyle.DEFAULT_COLLECTION_STYLE); } @@ -188,7 +193,8 @@ public final class CollectionUtils public final static <T> String abbreviate(final Collection<T> collection, final int maxLength, final boolean showLeft, final IToStringConverter<? super T> converter) { - return abbreviate(collection, maxLength, showLeft, converter, CollectionStyle.DEFAULT_COLLECTION_STYLE); + return abbreviate(collection, maxLength, showLeft, converter, + CollectionStyle.DEFAULT_COLLECTION_STYLE); } /** @@ -205,8 +211,9 @@ public final class CollectionUtils * relevant if you limit the number of items displayed. * @param style the style that should be applied to the output. */ - public final static <T> String abbreviate(final T[] objects, final int maxLength, final boolean showLeft, - final IToStringConverter<? super T> converter, final CollectionStyle style) + public final static <T> String abbreviate(final T[] objects, final int maxLength, + final boolean showLeft, final IToStringConverter<? super T> converter, + final CollectionStyle style) { assert objects != null : "Given objects can not be null."; return abbreviate(Arrays.asList(objects), maxLength, showLeft, converter, style); @@ -222,7 +229,8 @@ public final class CollectionUtils * @param style the style that should be applied to the output. */ public final static <T> String abbreviate(final Collection<T> collection, final int maxLength, - final boolean showLeft, final IToStringConverter<? super T> converter, final CollectionStyle style) + final boolean showLeft, final IToStringConverter<? super T> converter, + final CollectionStyle style) { assert collection != null : "Given collection can not be null."; assert converter != null : "Given converter can not be null."; diff --git a/common/source/java/ch/systemsx/cisd/common/collections/FilteredCollection.java b/common/source/java/ch/systemsx/cisd/common/collections/FilteredCollection.java index 804f7b97b8a..b8a18e7c13e 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/FilteredCollection.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/FilteredCollection.java @@ -70,7 +70,8 @@ public class FilteredCollection<E> extends AbstractCollectionDecorator<E> * </p> */ @SuppressWarnings("unchecked") - protected final static <E> Collection<E> filterCollection(Collection<? extends E> collection, Validator<E> validator) + protected final static <E> Collection<E> filterCollection(Collection<? extends E> collection, + Validator<E> validator) { if (collection == null) { diff --git a/common/source/java/ch/systemsx/cisd/common/collections/IKeyExtractor.java b/common/source/java/ch/systemsx/cisd/common/collections/IKeyExtractor.java index ce880e12d94..83fa9fdff8b 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/IKeyExtractor.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/IKeyExtractor.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.collections; /** * Interface defining the role of a key extractor. - * + * * @author Franz-Josef Elmer */ public interface IKeyExtractor<K, E> diff --git a/common/source/java/ch/systemsx/cisd/common/collections/TableMap.java b/common/source/java/ch/systemsx/cisd/common/collections/TableMap.java index 18ffe8b79bf..32303c63d3d 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/TableMap.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/TableMap.java @@ -109,12 +109,14 @@ public class TableMap<K, E> implements Iterable<E> public final void add(final E row) throws UniqueKeyViolationException { final K key = extractor.getKey(row); - if (uniqueKeyViolationStrategy == UniqueKeyViolationStrategy.KEEP_LAST || map.get(key) == null) + if (uniqueKeyViolationStrategy == UniqueKeyViolationStrategy.KEEP_LAST + || map.get(key) == null) { map.put(key, row); } else if (uniqueKeyViolationStrategy == UniqueKeyViolationStrategy.ERROR) { - throw new UniqueKeyViolationException("Key '" + key.toString() + "' already in the map."); + throw new UniqueKeyViolationException("Key '" + key.toString() + + "' already in the map."); } } diff --git a/common/source/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKey.java b/common/source/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKey.java index 4ca38e698c9..a82efcc2128 100644 --- a/common/source/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKey.java +++ b/common/source/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKey.java @@ -125,13 +125,14 @@ public class TableMapNonUniqueKey<K, E> implements Iterable<E> set.add(row); } else if (uniqueValueViolationStrategy == UniqueValueViolationStrategy.ERROR) { - throw new UniqueValueViolationException("Row '" + row.toString() + "' already stored in the map."); + throw new UniqueValueViolationException("Row '" + row.toString() + + "' already stored in the map."); } } /** * Gets the row set for the specified <var>key</var>. - * + * * @return The set, given in the order of addition, or <code>null</code> if the <var>key</var> is not found. */ public final Set<E> tryGet(final K key) diff --git a/common/source/java/ch/systemsx/cisd/common/compression/file/CompressionWorker.java b/common/source/java/ch/systemsx/cisd/common/compression/file/CompressionWorker.java index f341dbc15ab..47481b7c0f6 100644 --- a/common/source/java/ch/systemsx/cisd/common/compression/file/CompressionWorker.java +++ b/common/source/java/ch/systemsx/cisd/common/compression/file/CompressionWorker.java @@ -43,23 +43,26 @@ class CompressionWorker implements Runnable static final String COMPRESSING_MSG_TEMPLATE = "Compressing '%s'."; // @Private - static final String EXCEPTION_COMPRESSING_MSG_TEMPLATE = "Exceptional condition when trying to compress '%s'."; - + static final String EXCEPTION_COMPRESSING_MSG_TEMPLATE = + "Exceptional condition when trying to compress '%s'."; + // @Private static final String INTERRPTED_MSG = "Thread has been interrupted - exiting worker."; // @Private static final String EXITING_MSG = "No more files to compress - exiting worker."; - private final static Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, CompressionWorker.class); + private final static Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, CompressionWorker.class); private final Queue<File> workerQueue; - + private final Collection<FailureRecord> failures; private final ICompressionMethod compressor; - CompressionWorker(Queue<File> incommingQueue, Collection<FailureRecord> failures, ICompressionMethod compressor) + CompressionWorker(Queue<File> incommingQueue, Collection<FailureRecord> failures, + ICompressionMethod compressor) { assert incommingQueue != null; assert failures != null; @@ -101,12 +104,14 @@ class CompressionWorker implements Runnable status = compressor.compress(fileToCompressOrNull); } catch (Throwable th) { - operationLog.error(String.format(EXCEPTION_COMPRESSING_MSG_TEMPLATE, fileToCompressOrNull), th); + operationLog.error(String.format(EXCEPTION_COMPRESSING_MSG_TEMPLATE, + fileToCompressOrNull), th); failures.add(new FailureRecord(fileToCompressOrNull, th)); status = null; break; } - } while (StatusFlag.RETRIABLE_ERROR.equals(status.getFlag()) && ++count < MAX_RETRY_OF_FAILED_COMPRESSIONS); + } while (StatusFlag.RETRIABLE_ERROR.equals(status.getFlag()) + && ++count < MAX_RETRY_OF_FAILED_COMPRESSIONS); if (status != null && Status.OK.equals(status) == false) { failures.add(new FailureRecord(fileToCompressOrNull, status)); diff --git a/common/source/java/ch/systemsx/cisd/common/compression/file/Compressor.java b/common/source/java/ch/systemsx/cisd/common/compression/file/Compressor.java index 59293c83a54..7ba9948c196 100644 --- a/common/source/java/ch/systemsx/cisd/common/compression/file/Compressor.java +++ b/common/source/java/ch/systemsx/cisd/common/compression/file/Compressor.java @@ -47,9 +47,11 @@ public class Compressor LogInitializer.init(); } - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, Compressor.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, Compressor.class); - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, Compressor.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, Compressor.class); private static final int NUMBER_OF_WORKERS = Runtime.getRuntime().availableProcessors(); @@ -70,17 +72,20 @@ public class Compressor } if (operationLog.isInfoEnabled()) { - operationLog.info(String.format("Found %d files to compress.", filesToCompressOrNull.length)); + operationLog.info(String.format("Found %d files to compress.", + filesToCompressOrNull.length)); } - return new ArrayBlockingQueue<File>(filesToCompressOrNull.length, false, Arrays.asList(filesToCompressOrNull)); + return new ArrayBlockingQueue<File>(filesToCompressOrNull.length, false, Arrays + .asList(filesToCompressOrNull)); } - private static void startUpWorkerThreads(Queue<File> workerQueue, Collection<FailureRecord> failed, - ICompressionMethod compressor) + private static void startUpWorkerThreads(Queue<File> workerQueue, + Collection<FailureRecord> failed, ICompressionMethod compressor) { for (int i = 0; i < NUMBER_OF_WORKERS; ++i) { - new Thread(new CompressionWorker(workerQueue, failed, compressor), "Compressor " + i).start(); + new Thread(new CompressionWorker(workerQueue, failed, compressor), "Compressor " + i) + .start(); } if (operationLog.isInfoEnabled()) { @@ -88,14 +93,17 @@ public class Compressor } } - public static Collection<FailureRecord> start(String directoryName, ICompressionMethod compressionMethod) + public static Collection<FailureRecord> start(String directoryName, + ICompressionMethod compressionMethod) { if (compressionMethod instanceof ISelfTestable) { ((ISelfTestable) compressionMethod).check(); } - final Queue<File> workerQueue = fillWorkerQueueOrExit(new File(directoryName), compressionMethod); - final Collection<FailureRecord> failed = Collections.synchronizedCollection(new ArrayList<FailureRecord>()); + final Queue<File> workerQueue = + fillWorkerQueueOrExit(new File(directoryName), compressionMethod); + final Collection<FailureRecord> failed = + Collections.synchronizedCollection(new ArrayList<FailureRecord>()); startUpWorkerThreads(workerQueue, failed, compressionMethod); return failed; } diff --git a/common/source/java/ch/systemsx/cisd/common/compression/file/ICompressionMethod.java b/common/source/java/ch/systemsx/cisd/common/compression/file/ICompressionMethod.java index fb4b1a12125..7bc8b3c36a0 100644 --- a/common/source/java/ch/systemsx/cisd/common/compression/file/ICompressionMethod.java +++ b/common/source/java/ch/systemsx/cisd/common/compression/file/ICompressionMethod.java @@ -32,7 +32,7 @@ public interface ICompressionMethod extends FileFilter /** * Compress the <var>fileToCompress</var> - * + * * @return {@link Status#OK} if the operation was successful, a status indicating the kind of problem otherwise. */ public Status compress(File fileToCompress); diff --git a/common/source/java/ch/systemsx/cisd/common/compression/file/InPlaceCompressionMethod.java b/common/source/java/ch/systemsx/cisd/common/compression/file/InPlaceCompressionMethod.java index a3a8ac385e2..b8da33aab31 100644 --- a/common/source/java/ch/systemsx/cisd/common/compression/file/InPlaceCompressionMethod.java +++ b/common/source/java/ch/systemsx/cisd/common/compression/file/InPlaceCompressionMethod.java @@ -142,13 +142,13 @@ public abstract class InPlaceCompressionMethod implements ICompressionMethod, IS final boolean ok = fileToCompress.delete(); if (ok) { - operationLog.warn(String.format("Clean up: deleting left-over file '%s'", fileToCompress - .getAbsolutePath())); + operationLog.warn(String.format("Clean up: deleting left-over file '%s'", + fileToCompress.getAbsolutePath())); return Status.OK; } else { - return createStatusAndLog("Clean up: Unable to delete left-over file '%s'", fileToCompress - .getAbsolutePath()); + return createStatusAndLog("Clean up: Unable to delete left-over file '%s'", + fileToCompress.getAbsolutePath()); } } if (isCompressedFile(fileToCompress)) @@ -160,7 +160,8 @@ public abstract class InPlaceCompressionMethod implements ICompressionMethod, IS final boolean ok = originalFile.delete(); if (ok == false) { - return createStatusAndLog("Clean up: Unable to delete uncompressed file '%s'", originalFile); + return createStatusAndLog("Clean up: Unable to delete uncompressed file '%s'", + originalFile); } } if (fileToCompress.renameTo(originalFile)) @@ -168,15 +169,16 @@ public abstract class InPlaceCompressionMethod implements ICompressionMethod, IS return Status.OK; } else { - return createStatusAndLog("Renaming compressed file '%s' to original name '%s' failed.", + return createStatusAndLog( + "Renaming compressed file '%s' to original name '%s' failed.", fileToCompress, originalFile); } } final File inProgressFile = prefixInProgress(fileToCompress); final File compressionFinishedFile = prefixCompressed(fileToCompress); final boolean runOK = - ProcessExecutionHelper.runAndLog(createCommandLine(fileToCompress, inProgressFile), operationLog, - machineLog); + ProcessExecutionHelper.runAndLog(createCommandLine(fileToCompress, inProgressFile), + operationLog, machineLog); if (runOK == false) { return createStatusAndLog("Unable to compress '%s'.", fileToCompress.getAbsolutePath()); @@ -184,19 +186,20 @@ public abstract class InPlaceCompressionMethod implements ICompressionMethod, IS final boolean firstRenameOK = inProgressFile.renameTo(compressionFinishedFile); if (firstRenameOK == false) { - return createStatusAndLog("Unable to rename '%s' to '%s'.", inProgressFile.getAbsolutePath(), - compressionFinishedFile.getAbsolutePath()); + return createStatusAndLog("Unable to rename '%s' to '%s'.", inProgressFile + .getAbsolutePath(), compressionFinishedFile.getAbsolutePath()); } final boolean removalOfOriginalOK = fileToCompress.delete(); if (removalOfOriginalOK == false) { - return createStatusAndLog("Unable to delete original file '%s'", fileToCompress.getAbsolutePath()); + return createStatusAndLog("Unable to delete original file '%s'", fileToCompress + .getAbsolutePath()); } final boolean secondRenameOK = compressionFinishedFile.renameTo(fileToCompress); if (secondRenameOK == false) { - return createStatusAndLog("Unable to rename '%s' to '%s'.", compressionFinishedFile.getAbsolutePath(), - fileToCompress.getAbsolutePath()); + return createStatusAndLog("Unable to rename '%s' to '%s'.", compressionFinishedFile + .getAbsolutePath(), fileToCompress.getAbsolutePath()); } return Status.OK; } diff --git a/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffCompressor.java b/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffCompressor.java index b6cb1f7f24e..ad6e60609ed 100644 --- a/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffCompressor.java +++ b/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffCompressor.java @@ -43,7 +43,8 @@ public class TiffCompressor extends Compressor } for (FailureRecord r : failed) { - System.err.printf("%s (%s)\n", r.getFailedFile().getName(), r.getFailureStatus().getMessage()); + System.err.printf("%s (%s)\n", r.getFailedFile().getName(), r.getFailureStatus() + .getMessage()); } } diff --git a/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffZipCompressionMethod.java b/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffZipCompressionMethod.java index 90271e47f2e..0f32b9d2238 100644 --- a/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffZipCompressionMethod.java +++ b/common/source/java/ch/systemsx/cisd/common/compression/tiff/TiffZipCompressionMethod.java @@ -20,7 +20,6 @@ import java.io.File; import java.util.Arrays; import java.util.List; - import ch.systemsx.cisd.common.compression.file.InPlaceCompressionMethod; import ch.systemsx.cisd.common.exceptions.ConfigurationFailureException; import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException; @@ -75,10 +74,11 @@ public class TiffZipCompressionMethod extends InPlaceCompressionMethod assert fileToCompress.isFile(); assert inProgressFile != null; assert inProgressFile.exists() == false; - + final List<String> parameters = - Arrays.asList(convertExecutable.getAbsolutePath(), fileToCompress.getAbsolutePath(), "-compress", - "Zip", inProgressFile.getAbsolutePath()); + Arrays.asList(convertExecutable.getAbsolutePath(), + fileToCompress.getAbsolutePath(), "-compress", "Zip", inProgressFile + .getAbsolutePath()); return parameters; } @@ -87,15 +87,17 @@ public class TiffZipCompressionMethod extends InPlaceCompressionMethod { return Arrays.asList(".tif", ".tiff"); } - + @Override public void check() throws EnvironmentFailureException, ConfigurationFailureException { if (convertExecutable == null) { - throw new ConfigurationFailureException("Cannot find executable of the convert utility."); + throw new ConfigurationFailureException( + "Cannot find executable of the convert utility."); } - final String imageMagickVersionOrNull = getImageMagickVersion(convertExecutable.getAbsolutePath()); + final String imageMagickVersionOrNull = + getImageMagickVersion(convertExecutable.getAbsolutePath()); if (imageMagickVersionOrNull == null) { throw new ConfigurationFailureException("Invalid convert utility"); @@ -110,12 +112,13 @@ public class TiffZipCompressionMethod extends InPlaceCompressionMethod if (imageMagickMajorVersion < 6 || imageMagickMinorVersion < 2) { throw ConfigurationFailureException.fromTemplate( - "Convert utility is too old (expected: v6.2 or newer, found: v%s)", imageMagickVersionOrNull); + "Convert utility is too old (expected: v6.2 or newer, found: v%s)", + imageMagickVersionOrNull); } if (machineLog.isInfoEnabled()) { - machineLog.info(String.format("Using convert executable '%s', ImageMagick version %s", convertExecutable, - imageMagickVersionOrNull)); + machineLog.info(String.format("Using convert executable '%s', ImageMagick version %s", + convertExecutable, imageMagickVersionOrNull)); } } diff --git a/common/source/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilities.java b/common/source/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilities.java index 82188978dee..5bfb9170c19 100644 --- a/common/source/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilities.java +++ b/common/source/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilities.java @@ -44,7 +44,8 @@ public final class ConcurrencyUtilities * @param corePoolSize The number of threads that should be kept running even if less theads are needed. * @param maximumPoolSize The number of threads that this executor service is maximally allowed to spawn. */ - public static ExecutorService newNamedPool(final String name, int corePoolSize, int maximumPoolSize) + public static ExecutorService newNamedPool(final String name, int corePoolSize, + int maximumPoolSize) { return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() @@ -79,8 +80,8 @@ public final class ConcurrencyUtilities * @return The result of the future, or <code>null</code>, if the result does not become available within * <var>timeoutMillis</var> ms or if the waiting thread gets interrupted. */ - public static <T> T tryGetResult(Future<T> future, long timeoutMillis, ISimpleLogger loggerOrNull, - String operationNameOrNull) + public static <T> T tryGetResult(Future<T> future, long timeoutMillis, + ISimpleLogger loggerOrNull, String operationNameOrNull) { try { @@ -90,10 +91,10 @@ public final class ConcurrencyUtilities future.cancel(true); if (loggerOrNull != null) { - loggerOrNull - .log(LogLevel.DEBUG, String.format("%s took longer than %f s, cancelled.", - operationNameOrNull == null ? "UNKNOWN OPERATION" : operationNameOrNull, - timeoutMillis / 1000f)); + loggerOrNull.log(LogLevel.DEBUG, String.format( + "%s took longer than %f s, cancelled.", + operationNameOrNull == null ? "UNKNOWN OPERATION" : operationNameOrNull, + timeoutMillis / 1000f)); } return null; } catch (InterruptedException ex) @@ -111,8 +112,9 @@ public final class ConcurrencyUtilities if (loggerOrNull != null) { loggerOrNull.log(LogLevel.ERROR, String.format("%s has caused an exception: %s", - operationNameOrNull == null ? "UNKNOWN OPERATION" : operationNameOrNull, cause.getClass() - .getSimpleName(), cause.getMessage() != null ? cause.getMessage() : "<no message>")); + operationNameOrNull == null ? "UNKNOWN OPERATION" : operationNameOrNull, + cause.getClass().getSimpleName(), cause.getMessage() != null ? cause + .getMessage() : "<no message>")); } if (cause instanceof Error) { diff --git a/common/source/java/ch/systemsx/cisd/common/converter/ConverterPool.java b/common/source/java/ch/systemsx/cisd/common/converter/ConverterPool.java index 0b63d2a97ca..b815ae834c4 100644 --- a/common/source/java/ch/systemsx/cisd/common/converter/ConverterPool.java +++ b/common/source/java/ch/systemsx/cisd/common/converter/ConverterPool.java @@ -95,7 +95,8 @@ public final class ConverterPool { return (T) Boolean.valueOf(value); } - throw new IllegalArgumentException("No converter for type '" + type.getCanonicalName() + "'."); + throw new IllegalArgumentException("No converter for type '" + type.getCanonicalName() + + "'."); } /** diff --git a/common/source/java/ch/systemsx/cisd/common/db/DBRestrictionParser.java b/common/source/java/ch/systemsx/cisd/common/db/DBRestrictionParser.java index f30b28fdbeb..7bdfc67c389 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/DBRestrictionParser.java +++ b/common/source/java/ch/systemsx/cisd/common/db/DBRestrictionParser.java @@ -40,7 +40,8 @@ public class DBRestrictionParser { private static final String CREATE_DOMAIN_PREFIX = "create domain "; - private static final Pattern VARCHAR_PATTERN = Pattern.compile("(varchar|character varying)\\(([0-9]+)\\).*"); + private static final Pattern VARCHAR_PATTERN = + Pattern.compile("(varchar|character varying)\\(([0-9]+)\\).*"); /** The prefix each <code>create table</code> statement starts with. */ private static final String CREATE_TABLE_PREFIX = "create table "; @@ -50,18 +51,21 @@ public class DBRestrictionParser private static final Pattern NOT_NULL_TABLE_PATTERN = Pattern.compile("\\w+ ((default .+ not null)|(not null)|(not null .+ default.+))"); - + /** The prefix each <code>alter table</code> statement starts with (to add a constraint). */ private static final String ALTER_TABLE_PREFIX = "alter table "; private static final Pattern CHECK_CONSTRAINT_PATTERN = - Pattern.compile(ALTER_TABLE_PREFIX - + "([a-z,0-9,_]+) add constraint [a-z,0-9,_]+ check \\(([a-z,0-9,_]+) in \\((.+)\\)\\)"); + Pattern + .compile(ALTER_TABLE_PREFIX + + "([a-z,0-9,_]+) add constraint [a-z,0-9,_]+ check \\(([a-z,0-9,_]+) in \\((.+)\\)\\)"); - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, DBRestrictionParser.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, DBRestrictionParser.class); // @Private - final Map<String, DBTableRestrictions> tableRestrictionMap = new HashMap<String, DBTableRestrictions>(); + final Map<String, DBTableRestrictions> tableRestrictionMap = + new HashMap<String, DBTableRestrictions>(); public DBRestrictionParser(String ddlScript) { @@ -135,8 +139,8 @@ public class DBRestrictionParser } } - private void parseColumnDefinition(String columnDefinition, final String tableName, Map<String, Integer> domains) - throws NumberFormatException + private void parseColumnDefinition(String columnDefinition, final String tableName, + Map<String, Integer> domains) throws NumberFormatException { if (columnDefinition.startsWith("constraint ")) { @@ -145,7 +149,8 @@ public class DBRestrictionParser int indexOfFirstSpace = columnDefinition.indexOf(' '); if (indexOfFirstSpace < 0) { - operationLog.warn("Invalid column definition \"" + columnDefinition + "\" for table " + tableName); + operationLog.warn("Invalid column definition \"" + columnDefinition + "\" for table " + + tableName); return; } String columnName = columnDefinition.substring(0, indexOfFirstSpace).trim(); @@ -157,8 +162,8 @@ public class DBRestrictionParser final Matcher varCharMatcher = VARCHAR_PATTERN.matcher(typeDefinition); if (varCharMatcher.matches()) { - getTableRestrictions(tableName).columnLengthMap.put(columnName, Integer.parseInt(varCharMatcher - .group(2))); + getTableRestrictions(tableName).columnLengthMap.put(columnName, Integer + .parseInt(varCharMatcher.group(2))); } else { final Integer domainLength = domains.get(StringUtils.split(typeDefinition, ' ')[0]); @@ -167,7 +172,7 @@ public class DBRestrictionParser getTableRestrictions(tableName).columnLengthMap.put(columnName, domainLength); } } - + if (NOT_NULL_TABLE_PATTERN.matcher(typeDefinition).matches()) { getTableRestrictions(tableName).notNullSet.add(columnName); @@ -188,15 +193,17 @@ public class DBRestrictionParser final Set<String> alternativeSet = new HashSet<String>(); for (String alternative : alternatives) { - if (alternative.charAt(0) != '\'' || alternative.charAt(alternative.length() - 1) != '\'') + if (alternative.charAt(0) != '\'' + || alternative.charAt(alternative.length() - 1) != '\'') { - operationLog.warn("Invalid alternatives definition \"" + alternative + "\" for column " - + columnName + " of table " + tableName); + operationLog.warn("Invalid alternatives definition \"" + alternative + + "\" for column " + columnName + " of table " + tableName); continue; } alternativeSet.add(alternative.substring(1, alternative.length() - 1)); } - getTableRestrictions(tableName).checkedConstraintsMap.put(columnName, alternativeSet); + getTableRestrictions(tableName).checkedConstraintsMap.put(columnName, + alternativeSet); } } } @@ -220,5 +227,5 @@ public class DBRestrictionParser { return Collections.unmodifiableMap(tableRestrictionMap); } - + } diff --git a/common/source/java/ch/systemsx/cisd/common/db/ISequenceNameMapper.java b/common/source/java/ch/systemsx/cisd/common/db/ISequenceNameMapper.java index b9c7cc2909b..4ced91124b7 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/ISequenceNameMapper.java +++ b/common/source/java/ch/systemsx/cisd/common/db/ISequenceNameMapper.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.db; /** * Interface for mapping a table to its corresponding sequence. - * + * * @author Franz-Josef Elmer */ public interface ISequenceNameMapper diff --git a/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutionLogger.java b/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutionLogger.java index ca84e1b7688..6d5f0f5c052 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutionLogger.java +++ b/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutionLogger.java @@ -20,16 +20,16 @@ import ch.systemsx.cisd.common.Script; /** * Interface for logging of SQL script executions. - * + * * @author Bernd Rinn */ public interface ISqlScriptExecutionLogger { public void logStart(final Script moduleScript); - + public void logSuccess(final Script moduleScript); - + public void logFailure(final Script moduleScript, Throwable runException); } diff --git a/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutor.java b/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutor.java index 862d080edd5..c697f5f905e 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutor.java +++ b/common/source/java/ch/systemsx/cisd/common/db/ISqlScriptExecutor.java @@ -34,5 +34,6 @@ public interface ISqlScriptExecutor * @param loggerOrNull A logger to log the execution of the <var>sqlScript</var>, or <code>null</code>, if no * logging should be performed. */ - public void execute(Script sqlScript, boolean honorSingleStepMode, ISqlScriptExecutionLogger loggerOrNull); + public void execute(Script sqlScript, boolean honorSingleStepMode, + ISqlScriptExecutionLogger loggerOrNull); } diff --git a/common/source/java/ch/systemsx/cisd/common/db/OracleSequencerHandler.java b/common/source/java/ch/systemsx/cisd/common/db/OracleSequencerHandler.java index 5f9514442ed..7cf53ca3ca8 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/OracleSequencerHandler.java +++ b/common/source/java/ch/systemsx/cisd/common/db/OracleSequencerHandler.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.db; /** * Implementation of {@link ISequencerHandler} for Oracle. - * + * * @author Franz-Josef Elmer */ public class OracleSequencerHandler implements ISequencerHandler diff --git a/common/source/java/ch/systemsx/cisd/common/db/SQLCommandTokenizer.java b/common/source/java/ch/systemsx/cisd/common/db/SQLCommandTokenizer.java index 65ad21c3fe0..c974ab12783 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/SQLCommandTokenizer.java +++ b/common/source/java/ch/systemsx/cisd/common/db/SQLCommandTokenizer.java @@ -32,15 +32,15 @@ public final class SQLCommandTokenizer private final String sqlScript; private int index = 0; - + private Mode mode = Mode.SCANNING; private boolean newLine = true; - + private boolean newWord = false; - + private Character previous = '\0'; - + private Character current; public SQLCommandTokenizer(String sqlScript) @@ -154,7 +154,7 @@ public final class SQLCommandTokenizer return; } } - + private void scanConstant(StringBuilder builder) { do @@ -168,10 +168,10 @@ public final class SQLCommandTokenizer } while (current != '\'' || previous == '\\'); mode = Mode.SCANNING; } - + private void scanWhitespaces() { - while (Character.isWhitespace(next())) + while (Character.isWhitespace(next())) { if (current == '\n') { @@ -184,7 +184,7 @@ public final class SQLCommandTokenizer } mode = Mode.SCANNING; } - + private void skipLine() { do @@ -196,5 +196,5 @@ public final class SQLCommandTokenizer --index; } } - + } diff --git a/common/source/java/ch/systemsx/cisd/common/db/SQLStateUtils.java b/common/source/java/ch/systemsx/cisd/common/db/SQLStateUtils.java index 5e327f7f130..bba78cb4104 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/SQLStateUtils.java +++ b/common/source/java/ch/systemsx/cisd/common/db/SQLStateUtils.java @@ -41,7 +41,7 @@ public final class SQLStateUtils /** SQL State. */ public static final String DUPLICATE_OBJECT = "42710"; - + /** SQL State. */ public static final String DUPLICATE_DATABASE = "42P04"; diff --git a/common/source/java/ch/systemsx/cisd/common/db/SqlUnitTestRunner.java b/common/source/java/ch/systemsx/cisd/common/db/SqlUnitTestRunner.java index f53dd2252ea..b6094ce5776 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/SqlUnitTestRunner.java +++ b/common/source/java/ch/systemsx/cisd/common/db/SqlUnitTestRunner.java @@ -32,34 +32,37 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; import ch.systemsx.cisd.common.utilities.OSUtilities; /** - * Runner of SQL Unit tests. Needs an implementation of {@link ISqlScriptExecutor} to do the actual tests. - * The runner executes all test scripts found in the specified test scripts folder. The folder should have the - * following structure + * Runner of SQL Unit tests. Needs an implementation of {@link ISqlScriptExecutor} to do the actual tests. The runner + * executes all test scripts found in the specified test scripts folder. The folder should have the following structure + * * <pre> - * <<i>test script folder</i>> - * <<i>1. test case</i>> + * <<i>test script folder</i>> + * <<i>1. test case</i>> * buildup.sql - * 1=<<i>first test</i>>.sql - * 2=<<i>second test</i>>.sql + * 1=<<i>first test</i>>.sql + * 2=<<i>second test</i>>.sql * ... * teardown.sql - * <<i>2. test case</i>> + * <<i>2. test case</i>> * ... * ... * </pre> - * Folder starting with '.' or <code>migration</code> are ignored. - * The test cases are executed in lexicographical order of their name. For each test case <code>buildup.sql</code> - * will be executed first. The test scripts follow the naming schema + * + * Folder starting with '.' or <code>migration</code> are ignored. The test cases are executed in lexicographical + * order of their name. For each test case <code>buildup.sql</code> will be executed first. The test scripts follow + * the naming schema + * * <pre> - * <<i>decimal number</i>>=<<i>test name</i>>.sql + * <<i>decimal number</i>>=<<i>test name</i>>.sql * </pre> - * They are executed in ascending order of their numbers. Finally <code>teardown.sql</code> is executed. - * If execution of <code>buildup.sql</code> failed all test scripts and the tear down script are skipped. - * Note that <code>buildup.sql</code> and <code>teardown.sql</code> are optional. + * + * They are executed in ascending order of their numbers. Finally <code>teardown.sql</code> is executed. If execution + * of <code>buildup.sql</code> failed all test scripts and the tear down script are skipped. Note that + * <code>buildup.sql</code> and <code>teardown.sql</code> are optional. + * <p> + * A script fails if its execution throws an exception. Its innermost cause (usually a {@link SQLException}) will be + * recorded together with the name of the test case and the script. All failed scripts will be recorded. * <p> - * A script fails if its execution throws an exception. Its innermost cause (usually a {@link SQLException}) will - * be recorded together with the name of the test case and the script. All failed scripts will be recorded. - * <p> * The runner throws an {@link AssertionError} if at least one script failed. * * @author Franz-Josef Elmer @@ -72,14 +75,16 @@ public class SqlUnitTestRunner private static final class TestResult { private final boolean ok; + private final Throwable throwable; + private final File testScript; - + public TestResult(File testScript) { this(testScript, true, null); } - + public TestResult(File testScript, Throwable throwable) { this(testScript, false, throwable); @@ -91,7 +96,7 @@ public class SqlUnitTestRunner this.ok = ok; this.throwable = throwable; } - + public final File getTestScript() { return testScript; @@ -107,13 +112,14 @@ public class SqlUnitTestRunner return throwable; } } - + private final ISqlScriptExecutor executor; + private final PrintWriter writer; - + /** * Creates an instance for the specified SQL script executor and writer. - * + * * @param executor SQL script executor. * @param writer Writer used to monitor running progress by printing test and test case names. */ @@ -121,7 +127,7 @@ public class SqlUnitTestRunner { assert executor != null : "Undefined SQL script executor."; assert writer != null : "Undefined writer."; - + this.executor = executor; this.writer = writer; } @@ -172,7 +178,7 @@ public class SqlUnitTestRunner { throw new AssertionError(builder.toString()); } - + } private void runTestCase(File testCaseFolder, List<TestResult> results) @@ -219,13 +225,14 @@ public class SqlUnitTestRunner }); return testScripts; } - + private TestResult runScript(File scriptFile) { writer.println(" execute script " + scriptFile.getName()); try { - executor.execute(new Script(scriptFile.getName(), FileUtilities.loadToString(scriptFile)), true, null); + executor.execute(new Script(scriptFile.getName(), FileUtilities + .loadToString(scriptFile)), true, null); return new TestResult(scriptFile); } catch (Throwable t) { diff --git a/common/source/java/ch/systemsx/cisd/common/db/StandardSequenceNameMapper.java b/common/source/java/ch/systemsx/cisd/common/db/StandardSequenceNameMapper.java index 2ac63d0a628..a2521bfd9f4 100644 --- a/common/source/java/ch/systemsx/cisd/common/db/StandardSequenceNameMapper.java +++ b/common/source/java/ch/systemsx/cisd/common/db/StandardSequenceNameMapper.java @@ -64,7 +64,9 @@ public class StandardSequenceNameMapper implements ISequenceNameMapper String sequenceName = nonstandardMapping.get(tableNameInLowerCase); if (sequenceName == null) { - sequenceName = tableNameInLowerCase.substring(0, tableNameInLowerCase.length() - 1) + "_id_seq"; + sequenceName = + tableNameInLowerCase.substring(0, tableNameInLowerCase.length() - 1) + + "_id_seq"; } return sequenceName; } diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/ConfigurationFailureException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/ConfigurationFailureException.java index 2fd4b6e64b4..52ffd5e0c73 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/ConfigurationFailureException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/ConfigurationFailureException.java @@ -48,7 +48,8 @@ public class ConfigurationFailureException extends HighLevelException /** * Creates an {@link ConfigurationFailureException} using a {@link java.util.Formatter}. */ - public static ConfigurationFailureException fromTemplate(Throwable cause, String messageTemplate, Object... args) + public static ConfigurationFailureException fromTemplate(Throwable cause, + String messageTemplate, Object... args) { return new ConfigurationFailureException(String.format(messageTemplate, args), cause); } diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/EnvironmentFailureException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/EnvironmentFailureException.java index 3264dd973c1..002a2c251a7 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/EnvironmentFailureException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/EnvironmentFailureException.java @@ -49,7 +49,8 @@ public class EnvironmentFailureException extends HighLevelException /** * Creates an {@link EnvironmentFailureException} using a {@link java.util.Formatter}. */ - public static EnvironmentFailureException fromTemplate(Throwable cause, String messageTemplate, Object... args) + public static EnvironmentFailureException fromTemplate(Throwable cause, String messageTemplate, + Object... args) { return new EnvironmentFailureException(String.format(messageTemplate, args), cause); } diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/HighLevelException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/HighLevelException.java index b6763c6196b..a35cfd9d357 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/HighLevelException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/HighLevelException.java @@ -17,8 +17,8 @@ package ch.systemsx.cisd.common.exceptions; /** - * An exception that is "high-level" in the sense that we have a pretty good understanding what the failure - * means in the context where the exception has been thrown. + * An exception that is "high-level" in the sense that we have a pretty good understanding what the failure means in the + * context where the exception has been thrown. * * @author Bernd Rinn */ diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/InvalidSessionException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/InvalidSessionException.java index c3602ceb77d..cb8a72104de 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/InvalidSessionException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/InvalidSessionException.java @@ -16,7 +16,6 @@ package ch.systemsx.cisd.common.exceptions; - /** * This <code>UserFailureException</code> extension signals that a session has expired. * diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/NotImplementedException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/NotImplementedException.java index f7252b3359c..2b79c591012 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/NotImplementedException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/NotImplementedException.java @@ -43,7 +43,9 @@ public final class NotImplementedException extends RuntimeException { super(); final StackTraceExtractor extractor = new StackTraceExtractor(this); - this.message = String.format(MESSAGE_TEMPLATE, extractor.getMethodName(), extractor.getSimpleClassName()); + this.message = + String.format(MESSAGE_TEMPLATE, extractor.getMethodName(), extractor + .getSimpleClassName()); } public NotImplementedException(final String message) diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/RetriableEnvironmentFailureException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/RetriableEnvironmentFailureException.java index 280f02f0dc1..cbf0253ccf9 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/RetriableEnvironmentFailureException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/RetriableEnvironmentFailureException.java @@ -45,7 +45,8 @@ public class RetriableEnvironmentFailureException extends EnvironmentFailureExce /** * Creates a {@link RetriableEnvironmentFailureException} using a {@link java.util.Formatter}. */ - public static RetriableEnvironmentFailureException fromTemplate(String messageTemplate, Object... args) + public static RetriableEnvironmentFailureException fromTemplate(String messageTemplate, + Object... args) { return new RetriableEnvironmentFailureException(String.format(messageTemplate, args)); } @@ -53,8 +54,8 @@ public class RetriableEnvironmentFailureException extends EnvironmentFailureExce /** * Creates a {@link RetriableEnvironmentFailureException} using a {@link java.util.Formatter}. */ - public static RetriableEnvironmentFailureException fromTemplate(Throwable cause, String messageTemplate, - Object... args) + public static RetriableEnvironmentFailureException fromTemplate(Throwable cause, + String messageTemplate, Object... args) { return new RetriableEnvironmentFailureException(String.format(messageTemplate, args), cause); } diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/Status.java b/common/source/java/ch/systemsx/cisd/common/exceptions/Status.java index 194ef4e7adb..e7a239e14cf 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/Status.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/Status.java @@ -16,8 +16,8 @@ package ch.systemsx.cisd.common.exceptions; /** - * A class that holds the information about the status of an operation. To be used whenever a failure of an - * operation is signalled back via a return value rather than an exception. + * A class that holds the information about the status of an operation. To be used whenever a failure of an operation is + * signalled back via a return value rather than an exception. * * @author Bernd Rinn */ diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/StatusFlag.java b/common/source/java/ch/systemsx/cisd/common/exceptions/StatusFlag.java index c92a4d2ae24..50555756b8b 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/StatusFlag.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/StatusFlag.java @@ -17,8 +17,8 @@ package ch.systemsx.cisd.common.exceptions; /** - * The status of an operation. To be used whenever a failure of an operation is signalled back via a return value - * rather than an exception. + * The status of an operation. To be used whenever a failure of an operation is signalled back via a return value rather + * than an exception. * * @author Bernd Rinn */ diff --git a/common/source/java/ch/systemsx/cisd/common/exceptions/UserFailureException.java b/common/source/java/ch/systemsx/cisd/common/exceptions/UserFailureException.java index 64e5be4e6af..c17919cf5c2 100644 --- a/common/source/java/ch/systemsx/cisd/common/exceptions/UserFailureException.java +++ b/common/source/java/ch/systemsx/cisd/common/exceptions/UserFailureException.java @@ -49,7 +49,8 @@ public class UserFailureException extends HighLevelException /** * Creates an {@link UserFailureException} using a {@link java.util.Formatter}. */ - public static UserFailureException fromTemplate(Throwable cause, String messageTemplate, Object... args) + public static UserFailureException fromTemplate(Throwable cause, String messageTemplate, + Object... args) { return new UserFailureException(String.format(messageTemplate, args), cause); } diff --git a/common/source/java/ch/systemsx/cisd/common/io/ILinePrinter.java b/common/source/java/ch/systemsx/cisd/common/io/ILinePrinter.java index cf8ca729cb1..c3827aa173c 100644 --- a/common/source/java/ch/systemsx/cisd/common/io/ILinePrinter.java +++ b/common/source/java/ch/systemsx/cisd/common/io/ILinePrinter.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.io; /** * Interface for classes able to print some text line by line. - * + * * @author Franz-Josef Elmer */ public interface ILinePrinter diff --git a/common/source/java/ch/systemsx/cisd/common/io/SimpleLinePrinter.java b/common/source/java/ch/systemsx/cisd/common/io/SimpleLinePrinter.java index febb1f2073a..da3c990dd7e 100644 --- a/common/source/java/ch/systemsx/cisd/common/io/SimpleLinePrinter.java +++ b/common/source/java/ch/systemsx/cisd/common/io/SimpleLinePrinter.java @@ -20,8 +20,8 @@ import java.io.PrintWriter; import java.io.Writer; /** - * Line printer based on a {@link Writer} instance. - * + * Line printer based on a {@link Writer} instance. + * * @author Franz-Josef Elmer */ public class SimpleLinePrinter implements ILinePrinter @@ -29,12 +29,12 @@ public class SimpleLinePrinter implements ILinePrinter private final PrintWriter printWriter; /** - * Creates an instance for the specified writer. + * Creates an instance for the specified writer. */ public SimpleLinePrinter(Writer writer) { assert writer != null : "Unspecified writer."; - + printWriter = new PrintWriter(writer, true); } diff --git a/common/source/java/ch/systemsx/cisd/common/logging/ConsoleLogger.java b/common/source/java/ch/systemsx/cisd/common/logging/ConsoleLogger.java index 15705b96b78..032f65ab58f 100644 --- a/common/source/java/ch/systemsx/cisd/common/logging/ConsoleLogger.java +++ b/common/source/java/ch/systemsx/cisd/common/logging/ConsoleLogger.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.logging; /** * A {@link ISimpleLogger} that logs to {@link System#out} (for debugging purposes). - * + * * @author Bernd Rinn */ public class ConsoleLogger implements ISimpleLogger diff --git a/common/source/java/ch/systemsx/cisd/common/logging/ISimpleLogger.java b/common/source/java/ch/systemsx/cisd/common/logging/ISimpleLogger.java index 800e1977810..b536c5eb042 100644 --- a/common/source/java/ch/systemsx/cisd/common/logging/ISimpleLogger.java +++ b/common/source/java/ch/systemsx/cisd/common/logging/ISimpleLogger.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.logging; /** * A role that represents a simple logger (may be an ant task or a log4j logger}. - * + * * @author Bernd Rinn */ public interface ISimpleLogger @@ -26,5 +26,5 @@ public interface ISimpleLogger /** Log <var>message</var> at log <var>level</var> out to some log file or display. */ public void log(LogLevel level, String message); - + } diff --git a/common/source/java/ch/systemsx/cisd/common/logging/LogFactory.java b/common/source/java/ch/systemsx/cisd/common/logging/LogFactory.java index fd51ae77c70..ad2f343e46d 100644 --- a/common/source/java/ch/systemsx/cisd/common/logging/LogFactory.java +++ b/common/source/java/ch/systemsx/cisd/common/logging/LogFactory.java @@ -49,7 +49,8 @@ public final class LogFactory { if (category.isAdminLog() == false) { - throw new IllegalArgumentException("Only admin logs are allowed here, but we got " + category + "."); + throw new IllegalArgumentException("Only admin logs are allowed here, but we got " + + category + "."); } return category.name(); } diff --git a/common/source/java/ch/systemsx/cisd/common/logging/LogInitializer.java b/common/source/java/ch/systemsx/cisd/common/logging/LogInitializer.java index 4d60f86bb3b..6939d005ba3 100644 --- a/common/source/java/ch/systemsx/cisd/common/logging/LogInitializer.java +++ b/common/source/java/ch/systemsx/cisd/common/logging/LogInitializer.java @@ -59,7 +59,8 @@ public class LogInitializer assert logFile != null && logFile.exists() : "Given log file must be not null and must exist."; // For non-XML files, you will use <code>PropertyConfigurator.configureAndWatch(String)</code> DOMConfigurator.configureAndWatch(logFile.getPath()); - LogLog.debug(String.format("Log configured from file '%s' (watching).", logFile.getAbsolutePath())); + LogLog.debug(String.format("Log configured from file '%s' (watching).", logFile + .getAbsolutePath())); } private final static void configureFromURL(final URL url) diff --git a/common/source/java/ch/systemsx/cisd/common/logging/LogInvocationHandler.java b/common/source/java/ch/systemsx/cisd/common/logging/LogInvocationHandler.java index d228981dc02..fb3a8cc0a90 100644 --- a/common/source/java/ch/systemsx/cisd/common/logging/LogInvocationHandler.java +++ b/common/source/java/ch/systemsx/cisd/common/logging/LogInvocationHandler.java @@ -47,7 +47,8 @@ public final class LogInvocationHandler implements InvocationHandler * @param logLevel The log level to use for normal (successful) events. * @param classUsedToNameLogger Class used to specify the name of the logger. */ - public LogInvocationHandler(Object object, String name, Level logLevel, Class<?> classUsedToNameLogger) + public LogInvocationHandler(Object object, String name, Level logLevel, + Class<?> classUsedToNameLogger) { this.object = object; this.name = name; @@ -80,7 +81,8 @@ public final class LogInvocationHandler implements InvocationHandler final Logger logger = createLogger(method); if (throwable != null || logger.isEnabledFor(logLevel)) { - final StringBuilder builder = new StringBuilder(throwable == null ? "Successful" : "Failed"); + final StringBuilder builder = + new StringBuilder(throwable == null ? "Successful" : "Failed"); builder.append(" invocation of "); builder.append(name).append('.').append(method.getName()).append('('); if (args != null) @@ -124,7 +126,8 @@ public final class LogInvocationHandler implements InvocationHandler private Logger createLogger(Method method) { final LogAnnotation annotation = method.getAnnotation(LogAnnotation.class); - final LogCategory logCategory = (annotation == null) ? LogCategory.OPERATION : annotation.logCategory(); + final LogCategory logCategory = + (annotation == null) ? LogCategory.OPERATION : annotation.logCategory(); return LogFactory.getLogger(logCategory, classUsedToNameLogger); } } \ No newline at end of file diff --git a/common/source/java/ch/systemsx/cisd/common/logging/LoggingContextHandler.java b/common/source/java/ch/systemsx/cisd/common/logging/LoggingContextHandler.java index 1fd2a7acd57..2dd2d415f2e 100644 --- a/common/source/java/ch/systemsx/cisd/common/logging/LoggingContextHandler.java +++ b/common/source/java/ch/systemsx/cisd/common/logging/LoggingContextHandler.java @@ -23,8 +23,6 @@ import org.apache.log4j.MDC; import ch.systemsx.cisd.common.server.IRemoteHostProvider; - - /** * A class that handles the log4j context information. * diff --git a/common/source/java/ch/systemsx/cisd/common/mail/IMailClient.java b/common/source/java/ch/systemsx/cisd/common/mail/IMailClient.java index 168036d093b..dadda7f16fc 100644 --- a/common/source/java/ch/systemsx/cisd/common/mail/IMailClient.java +++ b/common/source/java/ch/systemsx/cisd/common/mail/IMailClient.java @@ -31,6 +31,7 @@ public interface IMailClient * * @param recipients list of recipients (of type <code>Message.RecipientType.TO</code>) */ - public void sendMessage(String subject, String content, String... recipients) throws EnvironmentFailureException; + public void sendMessage(String subject, String content, String... recipients) + throws EnvironmentFailureException; } \ No newline at end of file diff --git a/common/source/java/ch/systemsx/cisd/common/mail/MailClient.java b/common/source/java/ch/systemsx/cisd/common/mail/MailClient.java index 7db4a402c7f..28711540136 100644 --- a/common/source/java/ch/systemsx/cisd/common/mail/MailClient.java +++ b/common/source/java/ch/systemsx/cisd/common/mail/MailClient.java @@ -45,8 +45,8 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; * <p> * Just instantiate this class and use {@link #sendMessage(String, String, String[])} to send the email via SMTP. * </p> - * If the SMTP host starts with <code>file://</code> the mail is not send to a real SMTP server but it is - * stored in a file in the directory specified by the relative path following this prefix. + * If the SMTP host starts with <code>file://</code> the mail is not send to a real SMTP server but it is stored in a + * file in the directory specified by the relative path following this prefix. * * @author Christian Ribeaud */ @@ -58,7 +58,8 @@ public final class MailClient extends Authenticator implements IMailClient /** This system property is not supported by the <i>JavaMail API</i> */ public final static String MAIL_SMTP_PASSWORD = "mail.smtp.password"; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, MailClient.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, MailClient.class); private final String smtpUsername; @@ -77,10 +78,12 @@ public final class MailClient extends Authenticator implements IMailClient { this(properties.getProperty(JavaMailProperties.MAIL_FROM), properties .getProperty(JavaMailProperties.MAIL_SMTP_HOST), properties - .getProperty(JavaMailProperties.MAIL_SMTP_USER), properties.getProperty(MAIL_SMTP_PASSWORD)); + .getProperty(JavaMailProperties.MAIL_SMTP_USER), properties + .getProperty(MAIL_SMTP_PASSWORD)); } - public MailClient(final String from, final String smtpHost, final String smtpUsername, final String smtpPassword) + public MailClient(final String from, final String smtpHost, final String smtpUsername, + final String smtpPassword) { assert from != null; assert smtpHost != null; @@ -113,8 +116,8 @@ public final class MailClient extends Authenticator implements IMailClient { properties.put(JavaMailProperties.MAIL_SMTP_AUTH, Boolean.TRUE.toString()); } - properties.put(JavaMailProperties.MAIL_DEBUG, operationLog.isDebugEnabled() ? Boolean.TRUE.toString() - : Boolean.FALSE.toString()); + properties.put(JavaMailProperties.MAIL_DEBUG, operationLog.isDebugEnabled() ? Boolean.TRUE + .toString() : Boolean.FALSE.toString()); properties.put(JavaMailProperties.MAIL_TRANSPORT_PROTOCOL, "smtp"); return properties; } @@ -124,9 +127,11 @@ public final class MailClient extends Authenticator implements IMailClient Properties properties = createProperties(); if (operationLog.isDebugEnabled()) { - operationLog.debug("Creating mail session with following properties '" + properties + "'."); + operationLog.debug("Creating mail session with following properties '" + properties + + "'."); } - boolean mailSmtpAuth = Boolean.parseBoolean(properties.getProperty(JavaMailProperties.MAIL_SMTP_AUTH)); + boolean mailSmtpAuth = + Boolean.parseBoolean(properties.getProperty(JavaMailProperties.MAIL_SMTP_AUTH)); Session session = Session.getInstance(properties, mailSmtpAuth ? this : null); session.setDebug(operationLog.isDebugEnabled()); return session; @@ -154,7 +159,8 @@ public final class MailClient extends Authenticator implements IMailClient { if (operationLog.isInfoEnabled()) { - operationLog.info("Sending message from '" + from + "' to recipients '" + Arrays.asList(recipients) + "'"); + operationLog.info("Sending message from '" + from + "' to recipients '" + + Arrays.asList(recipients) + "'"); } int len = recipients.length; InternetAddress[] internetAddresses = new InternetAddress[len]; @@ -172,8 +178,8 @@ public final class MailClient extends Authenticator implements IMailClient send(msg); } catch (MessagingException ex) { - throw new EnvironmentFailureException("Sending e-mail with subject '" + subject + "' to recipients " - + Arrays.asList(recipients) + " failed. Reason: " + ex, ex); + throw new EnvironmentFailureException("Sending e-mail with subject '" + subject + + "' to recipients " + Arrays.asList(recipients) + " failed. Reason: " + ex, ex); } } @@ -186,8 +192,9 @@ public final class MailClient extends Authenticator implements IMailClient { if (emailFolder.isDirectory() == false) { - throw new EnvironmentFailureException("There exists already a file but not a folder with path '" - + emailFolder.getAbsolutePath() + "'."); + throw new EnvironmentFailureException( + "There exists already a file but not a folder with path '" + + emailFolder.getAbsolutePath() + "'."); } } else { @@ -217,7 +224,7 @@ public final class MailClient extends Authenticator implements IMailClient Transport.send(msg); } } - + private String renderAddresses(Address[] addresses) { StringBuilder builder = new StringBuilder(); diff --git a/common/source/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactory.java b/common/source/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactory.java index e54f7f29cfc..c5c630ca951 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactory.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactory.java @@ -46,7 +46,8 @@ public abstract class AbstractParserObjectFactory<E> implements IParserObjectFac /** Analyzes specified <code>beanClass</code> for its mandatory resp. optional properties. */ private final BeanAnalyzer<E> beanAnalyzer; - protected AbstractParserObjectFactory(final Class<E> beanClass, final IAliasPropertyMapper propertyMapper) + protected AbstractParserObjectFactory(final Class<E> beanClass, + final IAliasPropertyMapper propertyMapper) { assert beanClass != null : "Given bean class can not be null."; assert propertyMapper != null : "Given property mapper can not be null."; @@ -102,8 +103,8 @@ public abstract class AbstractParserObjectFactory<E> implements IParserObjectFac * not be found in the same annotated write methods (throws a <code>MandatoryPropertyMissingException</code>). * </p> */ - private final void checkPropertyMapper(final Class<E> clazz, final IAliasPropertyMapper propMapper) - throws ParserException + private final void checkPropertyMapper(final Class<E> clazz, + final IAliasPropertyMapper propMapper) throws ParserException { final Set<String> allPropertyNames = propMapper.getAllPropertyNames(); final Set<String> propertyNames = new LinkedHashSet<String>(allPropertyNames); @@ -120,17 +121,18 @@ public abstract class AbstractParserObjectFactory<E> implements IParserObjectFac missingProperties.add(fieldName); } } - final Set<String> mandatoryPropertyNames = getPropertyNames(beanAnalyzer.getMandatoryProperties(), propMapper); + final Set<String> mandatoryPropertyNames = + getPropertyNames(beanAnalyzer.getMandatoryProperties(), propMapper); if (missingProperties.size() > 0) { - throw new MandatoryPropertyMissingException(mandatoryPropertyNames, getPropertyNames(missingProperties, - propMapper)); + throw new MandatoryPropertyMissingException(mandatoryPropertyNames, getPropertyNames( + missingProperties, propMapper)); } if (propertyNames.size() > 0) { Set<String> names = getPropertyNames(beanAnalyzer.getOptionalProperties(), propMapper); - throw new UnmatchedPropertiesException(clazz, allPropertyNames, mandatoryPropertyNames, names, - propertyNames); + throw new UnmatchedPropertiesException(clazz, allPropertyNames, mandatoryPropertyNames, + names, propertyNames); } } @@ -152,7 +154,8 @@ public abstract class AbstractParserObjectFactory<E> implements IParserObjectFac return propertyNames; } - private final String getPropertyValue(final String[] lineTokens, final IPropertyModel propertyModel) + private final String getPropertyValue(final String[] lineTokens, + final IPropertyModel propertyModel) { final int column = propertyModel.getColumn(); if (column >= lineTokens.length) @@ -169,7 +172,8 @@ public abstract class AbstractParserObjectFactory<E> implements IParserObjectFac public E createObject(final String[] lineTokens) throws ParserException { final E object = ClassUtils.createInstance(beanClass); - for (final Map.Entry<String, Method> entry : beanAnalyzer.getLabelToWriteMethods().entrySet()) + for (final Map.Entry<String, Method> entry : beanAnalyzer.getLabelToWriteMethods() + .entrySet()) { final Method writeMethod = entry.getValue(); final IPropertyModel propertyModel = tryGetPropertyModel(entry.getKey()); @@ -178,8 +182,8 @@ public abstract class AbstractParserObjectFactory<E> implements IParserObjectFac if (propertyModel != null) { final String propertyValue = getPropertyValue(lineTokens, propertyModel); - ClassUtils - .invokeMethod(writeMethod, object, convert(propertyValue, writeMethod.getParameterTypes()[0])); + ClassUtils.invokeMethod(writeMethod, object, convert(propertyValue, writeMethod + .getParameterTypes()[0])); } } return object; diff --git a/common/source/java/ch/systemsx/cisd/common/parser/BeanAnalyzer.java b/common/source/java/ch/systemsx/cisd/common/parser/BeanAnalyzer.java index ad4a0ff238d..428e927173e 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/BeanAnalyzer.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/BeanAnalyzer.java @@ -56,14 +56,16 @@ final class BeanAnalyzer<T> private final void fillProperties() { - final List<Method> annotatedMethods = AnnotationUtils.getAnnotatedMethodList(beanClass, BeanProperty.class); + final List<Method> annotatedMethods = + AnnotationUtils.getAnnotatedMethodList(beanClass, BeanProperty.class); for (final Method method : annotatedMethods) { checkMethod(method); final BeanProperty annotation = method.getAnnotation(BeanProperty.class); final String label = annotation.label(); assert StringUtils.isNotEmpty(label) : String.format( - "BeanProperty annotation's label is not specified for method '%s'", method.getName()); + "BeanProperty annotation's label is not specified for method '%s'", method + .getName()); labelToWriteMethods.put(label, method); final boolean optional = annotation.optional(); checkUnique(label, optional); @@ -80,18 +82,19 @@ final class BeanAnalyzer<T> private final static void checkMethod(final Method method) { final Class<?> returnType = method.getReturnType(); - assert returnType.equals(Void.TYPE) : String.format("Return value of method '%s' must be void.", method - .getName()); + assert returnType.equals(Void.TYPE) : String.format( + "Return value of method '%s' must be void.", method.getName()); final Class<?>[] parameterTypes = method.getParameterTypes(); - assert parameterTypes.length == 1 : String.format("Annotated method '%s' must only accept one parameter.", - method.getName()); + assert parameterTypes.length == 1 : String.format( + "Annotated method '%s' must only accept one parameter.", method.getName()); } private final void checkUnique(final String fieldName, final boolean optional) { - assert optionalProperties.contains(fieldName) == false && mandatoryProperties.contains(fieldName) == false : String - .format("%s bean property '%s' already found and must be unique.", optional ? "Optional" : "Mandatory", - fieldName); + assert optionalProperties.contains(fieldName) == false + && mandatoryProperties.contains(fieldName) == false : String.format( + "%s bean property '%s' already found and must be unique.", optional ? "Optional" + : "Mandatory", fieldName); } /** Whether given <code>property</code> is mandatory. */ diff --git a/common/source/java/ch/systemsx/cisd/common/parser/ColumnSizeMismatchException.java b/common/source/java/ch/systemsx/cisd/common/parser/ColumnSizeMismatchException.java index 89a6bb55b3f..5f5c0dae934 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/ColumnSizeMismatchException.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/ColumnSizeMismatchException.java @@ -30,7 +30,8 @@ public final class ColumnSizeMismatchException extends ParsingException private final String message; - public ColumnSizeMismatchException(final String[] tokens, final int lineNumber, final int headerLength) + public ColumnSizeMismatchException(final String[] tokens, final int lineNumber, + final int headerLength) { super(tokens, lineNumber); assert tokens.length != headerLength : "Tokens length and header length must be different (otherwise no reason to throw this exception)."; @@ -52,8 +53,9 @@ public final class ColumnSizeMismatchException extends ParsingException } } lineStructure.append(" <END_OF_LINE>"); - return String.format("Line <%s> has %s columns (%s) than the header (%s):\n %s", getLineNumber(), moreLessStr, - String.valueOf(tokens.length), String.valueOf(headerLength), lineStructure.toString()); + return String.format("Line <%s> has %s columns (%s) than the header (%s):\n %s", + getLineNumber(), moreLessStr, String.valueOf(tokens.length), String + .valueOf(headerLength), lineStructure.toString()); } private final static String getMoreOrLessString(final String[] tokens, final int headerLength) diff --git a/common/source/java/ch/systemsx/cisd/common/parser/DefaultAliasPropertyMapper.java b/common/source/java/ch/systemsx/cisd/common/parser/DefaultAliasPropertyMapper.java index 47b2900358a..0b574df4742 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/DefaultAliasPropertyMapper.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/DefaultAliasPropertyMapper.java @@ -27,7 +27,8 @@ import java.util.TreeSet; * @author Christian Ribeaud */ // TODO 2008-02-17, Tomasz Pylak: this class should be removed (we do not need or want field aliases) -public class DefaultAliasPropertyMapper extends DefaultPropertyMapper implements IAliasPropertyMapper +public class DefaultAliasPropertyMapper extends DefaultPropertyMapper implements + IAliasPropertyMapper { private final Map<String, String> aliasToPropertyMappings; @@ -44,15 +45,15 @@ public class DefaultAliasPropertyMapper extends DefaultPropertyMapper implements final String alias = tryGetAliasForProperty(propertyName); if (alias != null) { - throw new IllegalArgumentException("Following property name '" + propertyName + "' has already alias '" - + alias + "' registered."); + throw new IllegalArgumentException("Following property name '" + propertyName + + "' has already alias '" + alias + "' registered."); } // No alias for two different properties. final String property = aliasToPropertyMappings.get(aliasName); if (aliasToPropertyMappings.containsKey(aliasName)) { - throw new IllegalArgumentException("Alias name '" + aliasName + "' already specified for property '" - + property + "'."); + throw new IllegalArgumentException("Alias name '" + aliasName + + "' already specified for property '" + property + "'."); } } @@ -147,7 +148,8 @@ public class DefaultAliasPropertyMapper extends DefaultPropertyMapper implements } @Override - public final IPropertyModel getPropertyModel(final String propertyName) throws IllegalArgumentException + public final IPropertyModel getPropertyModel(final String propertyName) + throws IllegalArgumentException { return super.getPropertyModel(getRealPropertyName(propertyName)); } diff --git a/common/source/java/ch/systemsx/cisd/common/parser/DefaultLineTokenizer.java b/common/source/java/ch/systemsx/cisd/common/parser/DefaultLineTokenizer.java index 4ceb0c5a59e..9ec9d01d3a3 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/DefaultLineTokenizer.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/DefaultLineTokenizer.java @@ -52,7 +52,8 @@ public class DefaultLineTokenizer implements ILineTokenizer private final Map<PropertyKey, String> properties; /** The default <code>StrMatcher</code> for each <code>PropertyKey</code>. */ - private final static Map<PropertyKey, StrMatcher> defaultStrMatchers = createDefaultStrMatchers(); + private final static Map<PropertyKey, StrMatcher> defaultStrMatchers = + createDefaultStrMatchers(); /** * Original value is <code>null</code>. @@ -69,7 +70,8 @@ public class DefaultLineTokenizer implements ILineTokenizer private static final Map<PropertyKey, StrMatcher> createDefaultStrMatchers() { - EnumMap<PropertyKey, StrMatcher> map = new EnumMap<PropertyKey, StrMatcher>(PropertyKey.class); + EnumMap<PropertyKey, StrMatcher> map = + new EnumMap<PropertyKey, StrMatcher>(PropertyKey.class); map.put(PropertyKey.SEPARATOR_CHARS, StrMatcher.tabMatcher()); map.put(PropertyKey.QUOTE_CHARS, StrMatcher.noneMatcher()); map.put(PropertyKey.TRIMMER_CHARS, StrMatcher.trimMatcher()); diff --git a/common/source/java/ch/systemsx/cisd/common/parser/DefaultParser.java b/common/source/java/ch/systemsx/cisd/common/parser/DefaultParser.java index 4fc09f6d007..346e117cb2a 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/DefaultParser.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/DefaultParser.java @@ -75,8 +75,8 @@ public class DefaultParser<E> implements IParser<E> // Parser // - public final List<E> parse(final Iterator<Line> lineIterator, final ILineFilter lineFilter, final int headerLength) - throws ParsingException + public final List<E> parse(final Iterator<Line> lineIterator, final ILineFilter lineFilter, + final int headerLength) throws ParsingException { final List<E> elements = new ArrayList<E>(); synchronized (lineTokenizer) diff --git a/common/source/java/ch/systemsx/cisd/common/parser/DefaultPropertyMapper.java b/common/source/java/ch/systemsx/cisd/common/parser/DefaultPropertyMapper.java index e092e2d318e..703b0abb81f 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/DefaultPropertyMapper.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/DefaultPropertyMapper.java @@ -51,8 +51,8 @@ public class DefaultPropertyMapper implements IPropertyMapper final String token = properties[i]; if (StringUtils.isBlank(token)) { - throw new IllegalArgumentException(String.format("%s token of %s is blank.", StringUtilities - .getOrdinal(i), Arrays.asList(properties))); + throw new IllegalArgumentException(String.format("%s token of %s is blank.", + StringUtilities.getOrdinal(i), Arrays.asList(properties))); } String tokenInLowerCase = token.toLowerCase(); propertyModels.put(tokenInLowerCase, new MappedProperty(i, tokenInLowerCase)); @@ -73,11 +73,13 @@ public class DefaultPropertyMapper implements IPropertyMapper return new TreeSet<String>(propertyModels.keySet()); } - public IPropertyModel getPropertyModel(final String propertyName) throws IllegalArgumentException + public IPropertyModel getPropertyModel(final String propertyName) + throws IllegalArgumentException { if (containsPropertyName(propertyName) == false) { - throw new IllegalArgumentException(String.format("Given property name '%s' does not exist.", propertyName)); + throw new IllegalArgumentException(String.format( + "Given property name '%s' does not exist.", propertyName)); } return propertyModels.get(propertyName.toLowerCase()); } diff --git a/common/source/java/ch/systemsx/cisd/common/parser/HeaderLineFilter.java b/common/source/java/ch/systemsx/cisd/common/parser/HeaderLineFilter.java index 77fdb325a74..a5fee8a621f 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/HeaderLineFilter.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/HeaderLineFilter.java @@ -20,8 +20,8 @@ import ch.systemsx.cisd.common.parser.filter.ExcludeEmptyAndCommentLineFilter; import ch.systemsx.cisd.common.parser.filter.ILineFilter; /** - * A <code>ILineFilter</code> implementation that extends {@link ExcludeEmptyAndCommentLineFilter} by - * excluding the header line (if <code>> 1</code>) as well. + * A <code>ILineFilter</code> implementation that extends {@link ExcludeEmptyAndCommentLineFilter} by excluding the + * header line (if <code>> 1</code>) as well. * * @author Christian Ribeaud */ diff --git a/common/source/java/ch/systemsx/cisd/common/parser/IAliasPropertyMapper.java b/common/source/java/ch/systemsx/cisd/common/parser/IAliasPropertyMapper.java index a47a6b7c519..3604b5c8d2b 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/IAliasPropertyMapper.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/IAliasPropertyMapper.java @@ -23,7 +23,7 @@ import java.util.Set; * * @author Christian Ribeaud */ -//TODO 2008-02-17, Tomasz Pylak: this class should be removed (we do not need or want field aliases) +// TODO 2008-02-17, Tomasz Pylak: this class should be removed (we do not need or want field aliases) public interface IAliasPropertyMapper extends IPropertyMapper { /** diff --git a/common/source/java/ch/systemsx/cisd/common/parser/ILineTokenizer.java b/common/source/java/ch/systemsx/cisd/common/parser/ILineTokenizer.java index c906e5975c0..71bc73639c7 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/ILineTokenizer.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/ILineTokenizer.java @@ -32,7 +32,7 @@ public interface ILineTokenizer * </p> */ public void init(); - + /** Splits given <code>line</code> into an array of tokens. */ public String[] tokenize(String line); diff --git a/common/source/java/ch/systemsx/cisd/common/parser/IParser.java b/common/source/java/ch/systemsx/cisd/common/parser/IParser.java index 28a1f135573..6c48a000a33 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/IParser.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/IParser.java @@ -37,8 +37,8 @@ public interface IParser<E> * @param headerLength number of columns in the header * @return a <code>List</code> of elements. */ - public List<E> parse(final Iterator<Line> lineIterator, final ILineFilter lineFilter, final int headerLength) - throws ParsingException; + public List<E> parse(final Iterator<Line> lineIterator, final ILineFilter lineFilter, + final int headerLength) throws ParsingException; /** * Sets the <code>IParserObjectFactory</code>. diff --git a/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactory.java b/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactory.java index 107c438e41c..83fdbaa52af 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactory.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactory.java @@ -45,7 +45,8 @@ public interface IParserObjectFactory<E> // IParserObjectFactory // - public final String[] createObject(final String[] lineTokens) throws ParserException + public final String[] createObject(final String[] lineTokens) + throws ParserException { return lineTokens; } diff --git a/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactoryFactory.java b/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactoryFactory.java index 1a37e2db980..f53c590f954 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactoryFactory.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/IParserObjectFactoryFactory.java @@ -26,5 +26,6 @@ public interface IParserObjectFactoryFactory<T> /** * Creates a new factory for the specified property mapper. */ - public IParserObjectFactory<T> createFactory(final IAliasPropertyMapper propertyMapper) throws ParserException; + public IParserObjectFactory<T> createFactory(final IAliasPropertyMapper propertyMapper) + throws ParserException; } diff --git a/common/source/java/ch/systemsx/cisd/common/parser/IPropertyMapper.java b/common/source/java/ch/systemsx/cisd/common/parser/IPropertyMapper.java index e4296aa2b07..a64cc458734 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/IPropertyMapper.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/IPropertyMapper.java @@ -31,7 +31,8 @@ public interface IPropertyMapper * * @throws IllegalArgumentException if given <var>propertyName</var> does not exist. */ - public IPropertyModel getPropertyModel(final String propertyName) throws IllegalArgumentException; + public IPropertyModel getPropertyModel(final String propertyName) + throws IllegalArgumentException; /** * Returns a set of all property names. diff --git a/common/source/java/ch/systemsx/cisd/common/parser/IndexOutOfBoundsException.java b/common/source/java/ch/systemsx/cisd/common/parser/IndexOutOfBoundsException.java index ea0c295e7e4..74303463b39 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/IndexOutOfBoundsException.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/IndexOutOfBoundsException.java @@ -24,7 +24,8 @@ package ch.systemsx.cisd.common.parser; public final class IndexOutOfBoundsException extends ParserException { - static final String MESSAGE_FORMAT = "Not enough tokens are available (index: %d, available: %d)"; + static final String MESSAGE_FORMAT = + "Not enough tokens are available (index: %d, available: %d)"; private static final long serialVersionUID = 1L; diff --git a/common/source/java/ch/systemsx/cisd/common/parser/Line.java b/common/source/java/ch/systemsx/cisd/common/parser/Line.java index 8dc1066ac95..dfcd0d41157 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/Line.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/Line.java @@ -43,6 +43,5 @@ public final class Line { return number; } - - + } \ No newline at end of file diff --git a/common/source/java/ch/systemsx/cisd/common/parser/ParserUtilities.java b/common/source/java/ch/systemsx/cisd/common/parser/ParserUtilities.java index f07f180a40e..c9c953c4167 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/ParserUtilities.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/ParserUtilities.java @@ -36,7 +36,8 @@ import ch.systemsx.cisd.common.parser.filter.ILineFilter; public final class ParserUtilities { - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, ParserUtilities.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, ParserUtilities.class); private ParserUtilities() { @@ -57,7 +58,8 @@ public final class ParserUtilities public final static Line getFirstAcceptedLine(final File file, final ILineFilter lineFilter) { assert file != null && file.exists() : "Given file must not be null and must exist."; - final ILineFilter filter = lineFilter == null ? AlwaysAcceptLineFilter.INSTANCE : lineFilter; + final ILineFilter filter = + lineFilter == null ? AlwaysAcceptLineFilter.INSTANCE : lineFilter; LineIterator lineIterator = null; try @@ -74,7 +76,8 @@ public final class ParserUtilities } } catch (IOException ex) { - machineLog.error("An I/O exception has occurred while reading file '" + file + "'.", ex); + machineLog + .error("An I/O exception has occurred while reading file '" + file + "'.", ex); } finally { LineIterator.closeQuietly(lineIterator); diff --git a/common/source/java/ch/systemsx/cisd/common/parser/ParsingException.java b/common/source/java/ch/systemsx/cisd/common/parser/ParsingException.java index f59791e9725..c320fa4609a 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/ParsingException.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/ParsingException.java @@ -41,7 +41,8 @@ public class ParsingException extends HighLevelException this(null, tokens, lineNumber); } - public ParsingException(final RuntimeException cause, final String[] tokens, final int lineNumber) + public ParsingException(final RuntimeException cause, final String[] tokens, + final int lineNumber) { super(createMessage(tokens), cause); this.lineNumber = lineNumber; diff --git a/common/source/java/ch/systemsx/cisd/common/parser/TabFileLoader.java b/common/source/java/ch/systemsx/cisd/common/parser/TabFileLoader.java index 694959fbb45..a228461fe9f 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/TabFileLoader.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/TabFileLoader.java @@ -128,7 +128,8 @@ public class TabFileLoader<T> boolean previousLineHasColumnHeaders = false; while (lineIterator.hasNext()) { - previousLineHasColumnHeaders = (previousLine != null) && PREFIX.equals(previousLine.getText()); + previousLineHasColumnHeaders = + (previousLine != null) && PREFIX.equals(previousLine.getText()); previousLine = line; line = lineIterator.next(); if (line.getText().startsWith(PREFIX) == false) @@ -137,7 +138,8 @@ public class TabFileLoader<T> } } @SuppressWarnings("null") - final String headerLine = previousLineHasColumnHeaders ? previousLine.getText().substring(1) : line.getText(); + final String headerLine = + previousLineHasColumnHeaders ? previousLine.getText().substring(1) : line.getText(); final DefaultParser<T> parser = new DefaultParser<T>(); final String[] tokens = StringUtils.split(headerLine, "\t"); @@ -209,7 +211,8 @@ public class TabFileLoader<T> { if (unique.add(token.toLowerCase()) == false) { - throw new IllegalArgumentException(String.format("Duplicated column name '%s'.", token)); + throw new IllegalArgumentException(String.format("Duplicated column name '%s'.", + token)); } } } diff --git a/common/source/java/ch/systemsx/cisd/common/parser/UnmatchedPropertiesException.java b/common/source/java/ch/systemsx/cisd/common/parser/UnmatchedPropertiesException.java index dbd09511271..c0ff42beb03 100644 --- a/common/source/java/ch/systemsx/cisd/common/parser/UnmatchedPropertiesException.java +++ b/common/source/java/ch/systemsx/cisd/common/parser/UnmatchedPropertiesException.java @@ -49,8 +49,9 @@ public final class UnmatchedPropertiesException extends ParserException */ private final Set<String> propertyNames; - public UnmatchedPropertiesException(final Class<?> beanClass, final Set<String> allPropertyNames, - final Set<String> mandatoryNames, final Set<String> optionalNames, final Set<String> propertyNames) + public UnmatchedPropertiesException(final Class<?> beanClass, + final Set<String> allPropertyNames, final Set<String> mandatoryNames, + final Set<String> optionalNames, final Set<String> propertyNames) { super(createMessage(beanClass, propertyNames)); assert allPropertyNames != null : "All property names can not be null."; @@ -63,13 +64,14 @@ public final class UnmatchedPropertiesException extends ParserException this.propertyNames = propertyNames; } - private final static String createMessage(final Class<?> beanClass, final Set<String> propertyNames) + private final static String createMessage(final Class<?> beanClass, + final Set<String> propertyNames) { assert beanClass != null : "Bean class can not be null."; assert propertyNames != null : "Property names can not be null."; assert propertyNames.size() > 0 : "There is no reason to throw this exception."; - return String.format(MESSAGE_FORMAT, beanClass.getSimpleName(), MandatoryPropertyMissingException - .toString((propertyNames))); + return String.format(MESSAGE_FORMAT, beanClass.getSimpleName(), + MandatoryPropertyMissingException.toString((propertyNames))); } public final Class<?> getBeanClass() diff --git a/common/source/java/ch/systemsx/cisd/common/process/CleanUpCallable.java b/common/source/java/ch/systemsx/cisd/common/process/CleanUpCallable.java index d0a57d7e04c..0879a73c306 100644 --- a/common/source/java/ch/systemsx/cisd/common/process/CleanUpCallable.java +++ b/common/source/java/ch/systemsx/cisd/common/process/CleanUpCallable.java @@ -16,7 +16,6 @@ package ch.systemsx.cisd.common.process; - /** * A class that implements the logic of cleaning up a resource even in case of an exception but re-throws an exception * of the clean up procedure only when the main procedure didn't throw one. <code>CleanUpRunner</code>s can be diff --git a/common/source/java/ch/systemsx/cisd/common/process/CleanUpRegistry.java b/common/source/java/ch/systemsx/cisd/common/process/CleanUpRegistry.java index afc7e5c76a0..fb4b57e5ee2 100644 --- a/common/source/java/ch/systemsx/cisd/common/process/CleanUpRegistry.java +++ b/common/source/java/ch/systemsx/cisd/common/process/CleanUpRegistry.java @@ -19,10 +19,9 @@ package ch.systemsx.cisd.common.process; import java.util.ArrayList; import java.util.List; - /** * A class that allows registering items for clean up and that allows to perform the clean up later. - * + * * @author Bernd Rinn */ public final class CleanUpRegistry implements ICleanUpRegistry diff --git a/common/source/java/ch/systemsx/cisd/common/process/FileRenamingProcess.java b/common/source/java/ch/systemsx/cisd/common/process/FileRenamingProcess.java index 97dd5f2fa09..ec7aae1b0cf 100644 --- a/common/source/java/ch/systemsx/cisd/common/process/FileRenamingProcess.java +++ b/common/source/java/ch/systemsx/cisd/common/process/FileRenamingProcess.java @@ -30,7 +30,8 @@ import ch.systemsx.cisd.common.logging.LogFactory; */ public final class FileRenamingProcess implements IProcess { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, FileRenamingProcess.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, FileRenamingProcess.class); public static final long DEFAULT_MILLIS_TO_SLEEP = 5000L; @@ -53,8 +54,8 @@ public final class FileRenamingProcess implements IProcess this(DEFAULT_MAX_RETRIES, DEFAULT_MILLIS_TO_SLEEP, sourceFile, destinationFile); } - public FileRenamingProcess(final int maxRetries, final long millisToSleep, final File sourceFile, - final File destinationFile) + public FileRenamingProcess(final int maxRetries, final long millisToSleep, + final File sourceFile, final File destinationFile) { this.sourceFile = sourceFile; this.maxRetries = maxRetries; @@ -98,12 +99,14 @@ public final class FileRenamingProcess implements IProcess { if (sourceFile.exists() == false) { - operationLog.error(String.format("Path '%s' doesn't exist, so it can't be moved to '%s'.", sourceFile, + operationLog.error(String.format( + "Path '%s' doesn't exist, so it can't be moved to '%s'.", sourceFile, destinationFile)); // Nothing to do here. So exit the looping by returning true. return true; } - operationLog.warn(String.format("Moving path '%s' to directory '%s' failed (attempt %d).", sourceFile, + operationLog.warn(String.format( + "Moving path '%s' to directory '%s' failed (attempt %d).", sourceFile, destinationFile, ++failures)); } return true; diff --git a/common/source/java/ch/systemsx/cisd/common/process/ICleanUpRegistry.java b/common/source/java/ch/systemsx/cisd/common/process/ICleanUpRegistry.java index d78a39be4b0..d0a5b098c56 100644 --- a/common/source/java/ch/systemsx/cisd/common/process/ICleanUpRegistry.java +++ b/common/source/java/ch/systemsx/cisd/common/process/ICleanUpRegistry.java @@ -18,7 +18,7 @@ package ch.systemsx.cisd.common.process; /** * A role that allows to register a clean-up method that is called regardless of whether an exception occurs or not. - * + * * @author Bernd Rinn */ public interface ICleanUpRegistry @@ -28,5 +28,5 @@ public interface ICleanUpRegistry * Register a clean-up to run when the main {@link Runnable} has been executed. */ public void registerCleanUp(Runnable cleanUp); - + } diff --git a/common/source/java/ch/systemsx/cisd/common/process/ProcessExecutionHelper.java b/common/source/java/ch/systemsx/cisd/common/process/ProcessExecutionHelper.java index ef192bf08a6..66366724fa2 100644 --- a/common/source/java/ch/systemsx/cisd/common/process/ProcessExecutionHelper.java +++ b/common/source/java/ch/systemsx/cisd/common/process/ProcessExecutionHelper.java @@ -100,10 +100,11 @@ public class ProcessExecutionHelper * @param machineLog The {@link Logger} to use for all message on the lower (machine) level. * @return <code>true</code>, if the process did complete successfully, <code>false</code> otherwise. */ - public static boolean runAndLog(List<String> cmd, long millisToWaitForCompletion, Logger operationLog, - Logger machineLog) + public static boolean runAndLog(List<String> cmd, long millisToWaitForCompletion, + Logger operationLog, Logger machineLog) { - return new ProcessExecutionHelper(operationLog, machineLog).runAndLog(cmd, millisToWaitForCompletion); + return new ProcessExecutionHelper(operationLog, machineLog).runAndLog(cmd, + millisToWaitForCompletion); } /** @@ -116,10 +117,11 @@ public class ProcessExecutionHelper * @param machineLog The {@link Logger} to use for all message on the lower (machine) level. * @return The process result. */ - public static ProcessResult run(List<String> cmd, long millisToWaitForCompletion, Logger operationLog, - Logger machineLog) + public static ProcessResult run(List<String> cmd, long millisToWaitForCompletion, + Logger operationLog, Logger machineLog) { - return new ProcessExecutionHelper(operationLog, machineLog).run(cmd, millisToWaitForCompletion); + return new ProcessExecutionHelper(operationLog, machineLog).run(cmd, + millisToWaitForCompletion); } /** @@ -148,7 +150,8 @@ public class ProcessExecutionHelper { return processOutput; } - final BufferedReader reader = new BufferedReader(new InputStreamReader(processOrNull.getInputStream())); + final BufferedReader reader = + new BufferedReader(new InputStreamReader(processOrNull.getInputStream())); try { String ln; @@ -158,7 +161,8 @@ public class ProcessExecutionHelper } } catch (IOException e) { - machineLog.warn(String.format("IOException when reading stdout, msg='%s'.", e.getMessage())); + machineLog.warn(String.format("IOException when reading stdout, msg='%s'.", e + .getMessage())); } finally { IOUtils.closeQuietly(reader); @@ -231,7 +235,8 @@ public class ProcessExecutionHelper boolean isInterrupted = false; try { - watchDogOrNull = tryCreateWatchDog(processStatus, millisoWaitForCompletion, commandLine.get(0)); + watchDogOrNull = + tryCreateWatchDog(processStatus, millisoWaitForCompletion, commandLine.get(0)); final Process process; try { @@ -279,7 +284,8 @@ public class ProcessExecutionHelper return ProcessResult.createNotStarted(commandLine, operationLog, machineLog); } - private ProcessResult createResult(List<String> commandLine, final Process processOrNull, boolean isInterrupted) + private ProcessResult createResult(List<String> commandLine, final Process processOrNull, + boolean isInterrupted) { if (processOrNull == null) { @@ -288,7 +294,8 @@ public class ProcessExecutionHelper { if (isInterrupted) { - return ProcessResult.createWaitingInterrupted(processOrNull, commandLine, operationLog, machineLog); + return ProcessResult.createWaitingInterrupted(processOrNull, commandLine, + operationLog, machineLog); } else { return ProcessResult.create(processOrNull, commandLine, operationLog, machineLog); @@ -296,22 +303,24 @@ public class ProcessExecutionHelper } } - private void logInterruption(final String commandLine, ProcessStatus terminationStatus, InterruptedException ex) + private void logInterruption(final String commandLine, ProcessStatus terminationStatus, + InterruptedException ex) { if (terminationStatus.isInterruptedAfterTimeout() == false) // have NOT been stopped by the watchDog { machineLog.error(String.format("Execution of %s interrupted", commandLine), ex); } else { - operationLog.warn(String.format("Execution of %s interrupted after timeout", commandLine)); + operationLog.warn(String.format("Execution of %s interrupted after timeout", + commandLine)); } } /* * isTerminated is passed by reference. Access to it should be synchronized on process variable */ - private Timer tryCreateWatchDog(final ProcessStatus processStatus, final long millisToWaitForCompletion, - final String commandForLog) + private Timer tryCreateWatchDog(final ProcessStatus processStatus, + final long millisToWaitForCompletion, final String commandForLog) { final Timer watchDogOrNull; if (millisToWaitForCompletion > 0L) @@ -323,7 +332,8 @@ public class ProcessExecutionHelper @Override public void run() { - operationLog.warn(String.format("Destroy process since it didn't finish in %d milli seconds", + operationLog.warn(String.format( + "Destroy process since it didn't finish in %d milli seconds", millisToWaitForCompletion)); Process process = processStatus.tryGetProcess(); if (process != null) @@ -338,7 +348,8 @@ public class ProcessExecutionHelper { processStatus.setInterruptedAfterTimeout(); operationLog.info(String.format( - "Interrupting waiting for the process %s by the watchDog", commandForLog)); + "Interrupting waiting for the process %s by the watchDog", + commandForLog)); // stop waiting for the process. We want to prevent situations when the child process, // which is an external program, gets stuck during the start or cannot be destroyed. It // would cause the whole system to hang and we do not want that. @@ -373,8 +384,8 @@ public class ProcessExecutionHelper return result.isOK(); } - public static void logProcessExecution(String commandName, int exitValue, List<String> processOutput, - Logger operationLog, Logger machineLog) + public static void logProcessExecution(String commandName, int exitValue, + List<String> processOutput, Logger operationLog, Logger machineLog) { if (exitValue != EXIT_VALUE_OK) { @@ -387,7 +398,8 @@ public class ProcessExecutionHelper } } - private static void logProcessExitValue(final Level logLevel, Logger operationLog, String commandName, int exitValue) + private static void logProcessExitValue(final Level logLevel, Logger operationLog, + String commandName, int exitValue) { assert logLevel != null; assert operationLog != null; @@ -398,13 +410,13 @@ public class ProcessExecutionHelper operationLog.log(logLevel, String.format("[%s] process was destroyed.", commandName)); } else { - operationLog.log(logLevel, String.format("[%s] process returned with exit value %d.", commandName, - exitValue)); + operationLog.log(logLevel, String.format("[%s] process returned with exit value %d.", + commandName, exitValue)); } } - private static void logProcessOutput(final Level logLevel, Logger machineLog, String commandName, - List<String> processOutputLines) + private static void logProcessOutput(final Level logLevel, Logger machineLog, + String commandName, List<String> processOutputLines) { assert logLevel != null; assert machineLog != null; diff --git a/common/source/java/ch/systemsx/cisd/common/process/ProcessResult.java b/common/source/java/ch/systemsx/cisd/common/process/ProcessResult.java index 06cf63111cc..8272c38bc20 100644 --- a/common/source/java/ch/systemsx/cisd/common/process/ProcessResult.java +++ b/common/source/java/ch/systemsx/cisd/common/process/ProcessResult.java @@ -46,13 +46,15 @@ public final class ProcessResult private List<String> outputLines; // process finished or was terminated after timeout - public static ProcessResult create(Process process, List<String> commandLine, Logger operationLog, Logger machineLog) + public static ProcessResult create(Process process, List<String> commandLine, + Logger operationLog, Logger machineLog) { return new ProcessResult(process, false, commandLine, operationLog, machineLog); } // process could not start at all - public static ProcessResult createNotStarted(List<String> commandLine, Logger operationLog, Logger machineLog) + public static ProcessResult createNotStarted(List<String> commandLine, Logger operationLog, + Logger machineLog) { return new ProcessResult(null, false, commandLine, operationLog, machineLog); } @@ -64,8 +66,8 @@ public final class ProcessResult return new ProcessResult(process, true, commandLine, operationLog, machineLog); } - private ProcessResult(Process processOrNull, boolean hasBlocked, List<String> commandLine, Logger operationLog, - Logger machineLog) + private ProcessResult(Process processOrNull, boolean hasBlocked, List<String> commandLine, + Logger operationLog, Logger machineLog) { this.commandLine = commandLine; this.commandName = new File(commandLine.get(0)).getName(); @@ -180,18 +182,19 @@ public final class ProcessResult { if (isRun() == false) { - operationLog.log(logLevel, String.format("[%s] process could not be run.", commandName)); + operationLog + .log(logLevel, String.format("[%s] process could not be run.", commandName)); } else if (isTerminated()) { operationLog.log(logLevel, String.format("[%s] process was destroyed.", commandName)); } else if (hasBlocked()) { - operationLog.log(logLevel, String.format("[%s] process has blocked and could not be destroyed.", - commandName)); + operationLog.log(logLevel, String.format( + "[%s] process has blocked and could not be destroyed.", commandName)); } else { - operationLog.log(logLevel, String.format("[%s] process returned with exit value %d.", commandName, - exitValue())); + operationLog.log(logLevel, String.format("[%s] process returned with exit value %d.", + commandName, exitValue())); } } diff --git a/common/source/java/ch/systemsx/cisd/common/test/InterfaceForRMIChecker.java b/common/source/java/ch/systemsx/cisd/common/test/InterfaceForRMIChecker.java index 73d0465f5e8..939a000fc2c 100644 --- a/common/source/java/ch/systemsx/cisd/common/test/InterfaceForRMIChecker.java +++ b/common/source/java/ch/systemsx/cisd/common/test/InterfaceForRMIChecker.java @@ -26,24 +26,24 @@ import java.util.HashSet; import java.util.Set; /** - * Helper class for checking an interface or a class to be ready for RMI. - * + * Helper class for checking an interface or a class to be ready for RMI. + * * @author Franz-Josef Elmer */ public class InterfaceForRMIChecker { /** - * Asserts that the specified interface is ready for RMI. That is, for all methods - * the parameter types and the return type is {@link Serializable}. + * Asserts that the specified interface is ready for RMI. That is, for all methods the parameter types and the + * return type is {@link Serializable}. * - * @throws AssertionError if <code>interfaze</code> is not an interface or a parameter type or - * a return value is not serializable. + * @throws AssertionError if <code>interfaze</code> is not an interface or a parameter type or a return value is + * not serializable. */ public static void assertInterfaceForRMI(Class<?> interfaze) { assert interfaze != null : "Unspecified interface."; assert interfaze.isInterface() : "Not an interface " + interfaze; - + Set<Class<?>> visitedClasses = new HashSet<Class<?>>(); Method[] methods = interfaze.getMethods(); for (Method method : methods) @@ -51,7 +51,7 @@ public class InterfaceForRMIChecker assertMethodForRMI(method, visitedClasses); } } - + private static void assertMethodForRMI(Method method, Set<Class<?>> visitedClasses) { Class<?>[] parameterTypes = method.getParameterTypes(); @@ -65,19 +65,20 @@ public class InterfaceForRMIChecker assertSerializable(returnType, visitedClasses, true); } } - + /** * Asserts that the specified class is serializable. * - * @throws AssertionError if <code>clazz</code> is not serializable or a non-transient non-static - * attribute isn't serializable. + * @throws AssertionError if <code>clazz</code> is not serializable or a non-transient non-static attribute isn't + * serializable. */ public static void assertSerializable(Class<?> clazz) { assertSerializable(clazz, new HashSet<Class<?>>(), true); } - private static void assertSerializable(Class<?> clazz, Set<Class<?>> visitedClasses, boolean checkImplementsSerializable) + private static void assertSerializable(Class<?> clazz, Set<Class<?>> visitedClasses, + boolean checkImplementsSerializable) { assert clazz != null : "Unspecified class."; if (clazz.isPrimitive() || visitedClasses.contains(clazz)) @@ -92,7 +93,8 @@ public class InterfaceForRMIChecker { if (checkImplementsSerializable) { - assert Serializable.class.isAssignableFrom(clazz) : clazz + " does not implements java.io.Serializable"; + assert Serializable.class.isAssignableFrom(clazz) : clazz + + " does not implements java.io.Serializable"; } Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/AbstractHashable.java b/common/source/java/ch/systemsx/cisd/common/utilities/AbstractHashable.java index 15dc6ab3683..65a3808055f 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/AbstractHashable.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/AbstractHashable.java @@ -23,7 +23,6 @@ import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; - /** * If you want your class to behave correctly when used in {@link Map}s or {@link Set}s, you can do this by: * <ol> @@ -55,6 +54,7 @@ public abstract class AbstractHashable @Override public final String toString() { - return ToStringBuilder.reflectionToString(this, ModifiedShortPrefixToStringStyle.MODIFIED_SHORT_PREFIX_STYLE); + return ToStringBuilder.reflectionToString(this, + ModifiedShortPrefixToStringStyle.MODIFIED_SHORT_PREFIX_STYLE); } } diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/BeanUtils.java b/common/source/java/ch/systemsx/cisd/common/utilities/BeanUtils.java index a90fe315a14..848ba013c38 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/BeanUtils.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/BeanUtils.java @@ -151,9 +151,10 @@ public final class BeanUtils @SuppressWarnings("unchecked") private static final Set<Class> immutableTypes = - new LinkedHashSet<Class>(Arrays.asList(boolean.class, Boolean.class, byte.class, Byte.class, short.class, - Short.class, int.class, Integer.class, long.class, Long.class, float.class, Float.class, - double.class, Double.class, String.class, Date.class)); + new LinkedHashSet<Class>(Arrays.asList(boolean.class, Boolean.class, byte.class, + Byte.class, short.class, Short.class, int.class, Integer.class, long.class, + Long.class, float.class, Float.class, double.class, Double.class, String.class, + Date.class)); /** * Creates a new list of Beans of type <var>clazz</var>. @@ -173,7 +174,8 @@ public final class BeanUtils * Creates a new array of Beans of type <var>clazz</var>. See <code>createBeanList()</code> for parameter * specification. */ - public static <T, S> T[] createBeanArray(Class<T> clazz, Collection<S> source, Converter converter) + public static <T, S> T[] createBeanArray(Class<T> clazz, Collection<S> source, + Converter converter) { assert clazz != null; @@ -214,7 +216,8 @@ public final class BeanUtils * @return The new list filled from <var>sourceList</var> or <code>null</code>, if <var>sourceList</var> is * <code>null</code>. */ - public final static <T, S> List<T> createBeanList(Class<T> clazz, Iterable<S> source, Converter converter) + public final static <T, S> List<T> createBeanList(Class<T> clazz, Iterable<S> source, + Converter converter) { assert clazz != null; @@ -260,7 +263,8 @@ public final class BeanUtils * <code>null</code>, in which case only standard conversions are allowed. * @return The new bean or <code>null</code> if <var>sourceBean</var> is <code>null</code>. */ - public static <T> T fillBean(Class<T> beanClass, T beanInstance, Object sourceBean, Converter converter) + public static <T> T fillBean(Class<T> beanClass, T beanInstance, Object sourceBean, + Converter converter) { Converter c = converter; if (c == null) @@ -319,7 +323,8 @@ public final class BeanUtils try { T destinationBean = - (beanInstance != null) ? beanInstance : instantiateBean(beanClass, sourceBean, setterAnnotations); + (beanInstance != null) ? beanInstance : instantiateBean(beanClass, sourceBean, + setterAnnotations); if (isArray(destinationBean)) { if (isArray(sourceBean)) @@ -327,17 +332,20 @@ public final class BeanUtils destinationBean = copyArrayToArray(destinationBean, sourceBean, converter); } else if (isCollection(sourceBean)) { - destinationBean = (T) copyCollectionToArray(destinationBean, (Collection<?>) sourceBean, converter); + destinationBean = + (T) copyCollectionToArray(destinationBean, (Collection<?>) sourceBean, + converter); } } else if (isCollection(destinationBean)) { if (isArray(sourceBean)) { - copyArrayToCollection((Collection<?>) destinationBean, sourceBean, setterAnnotations, converter); + copyArrayToCollection((Collection<?>) destinationBean, sourceBean, + setterAnnotations, converter); } else if (isCollection(sourceBean)) { - copyCollectionToCollection((Collection<?>) destinationBean, (Collection<?>) sourceBean, - setterAnnotations, converter); + copyCollectionToCollection((Collection<?>) destinationBean, + (Collection<?>) sourceBean, setterAnnotations, converter); } } else { @@ -378,8 +386,9 @@ public final class BeanUtils return clazz.isArray(); } - private static <T> T instantiateBean(Class<T> beanClass, Object sourceBean, AnnotationMap setterAnnotations) - throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException + private static <T> T instantiateBean(Class<T> beanClass, Object sourceBean, + AnnotationMap setterAnnotations) throws InstantiationException, IllegalAccessException, + InvocationTargetException, NoSuchMethodException { if (sourceBean == null) { @@ -421,21 +430,24 @@ public final class BeanUtils } @SuppressWarnings("unchecked") - private static <T> T createArray(Class<T> beanClass, int length) throws NegativeArraySizeException + private static <T> T createArray(Class<T> beanClass, int length) + throws NegativeArraySizeException { return (T) Array.newInstance(beanClass.getComponentType(), length); } @SuppressWarnings("unchecked") - private static <E> E[] createArrayOfType(Class<E> elemClass, int length) throws NegativeArraySizeException + private static <E> E[] createArrayOfType(Class<E> elemClass, int length) + throws NegativeArraySizeException { return (E[]) Array.newInstance(elemClass, length); } @SuppressWarnings("unchecked") // No way to avoid the warning since the compiler doesn't accept something like ArrayList<String>.class - private final static <T> T createCollection(final int size, final AnnotationMap setterAnnotations) - throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, + private final static <T> T createCollection(final int size, + final AnnotationMap setterAnnotations) throws InstantiationException, + IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { final CollectionMapping mapping = getCollectionMapping(setterAnnotations); @@ -452,8 +464,10 @@ public final class BeanUtils } @SuppressWarnings("unchecked") - private static <T> T constructCollection(final Constructor<? extends Collection> constructorWithSize, int size) - throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException + private static <T> T constructCollection( + final Constructor<? extends Collection> constructorWithSize, int size) + throws InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException { // This conversion _can_ go wrong if the concrete collection class doesn't implement the right sub-interface of // collection, e.g. when using a HashSet as concrete collection class where a List is required. @@ -506,7 +520,8 @@ public final class BeanUtils for (int index = 0; index < length; ++index) { final Object sourceElement = Array.get(source, index); - final Object destinationElement = createBean(componentType, sourceElement, converter); + final Object destinationElement = + createBean(componentType, sourceElement, converter); Array.set(returned, index, destinationElement); } } @@ -514,8 +529,8 @@ public final class BeanUtils } @SuppressWarnings("unchecked") - private final static <T> T[] copyCollectionToArray(Object destination, Collection<T> source, Converter converter) - throws IllegalAccessException, InvocationTargetException + private final static <T> T[] copyCollectionToArray(Object destination, Collection<T> source, + Converter converter) throws IllegalAccessException, InvocationTargetException { if (destination == null) { @@ -543,7 +558,8 @@ public final class BeanUtils int index = 0; for (Object sourceElement : source) { - final Object destinationElement = createBean(componentType, sourceElement, converter); + final Object destinationElement = + createBean(componentType, sourceElement, converter); Array.set(returned, index++, destinationElement); } } @@ -571,7 +587,8 @@ public final class BeanUtils for (int index = 0; index < length; ++index) { final Object sourceElement = Array.get(source, index); - final Object destinationElement = createBean(componentType, sourceElement, converter); + final Object destinationElement = + createBean(componentType, sourceElement, converter); addToUntypedCollection(destination, destinationElement); } } @@ -595,7 +612,8 @@ public final class BeanUtils { for (Object sourceElement : source) { - final Object destinationElement = createBean(componentType, sourceElement, converter); + final Object destinationElement = + createBean(componentType, sourceElement, converter); addToUntypedCollection(destination, destinationElement); } } @@ -623,20 +641,25 @@ public final class BeanUtils return mapping; } - private static <T> void copyBean(T destination, Object source, Converter converter) throws IllegalAccessException, - InvocationTargetException + private static <T> void copyBean(T destination, Object source, Converter converter) + throws IllegalAccessException, InvocationTargetException { if (destination == null) { return; } - final Collection<Method> destinationSetters = scanForPublicMethods(destination, SETTER_PREFIX, 1).values(); - final Map<String, Method> destinationGetters = scanForPublicMethods(destination, GETTER_PREFIX, 0); + final Collection<Method> destinationSetters = + scanForPublicMethods(destination, SETTER_PREFIX, 1).values(); + final Map<String, Method> destinationGetters = + scanForPublicMethods(destination, GETTER_PREFIX, 0); final Map<String, Method> sourceGetters = scanForPublicMethods(source, GETTER_PREFIX, 0); - scanForPublicMethods(source, sourceGetters, BOOLEAN_GETTER_PREFIX, 0, boolean.class, Boolean.class); + scanForPublicMethods(source, sourceGetters, BOOLEAN_GETTER_PREFIX, 0, boolean.class, + Boolean.class); for (Method setter : destinationSetters) { - final T newBean = emergeNewBean(setter, source, destination, sourceGetters, destinationGetters, converter); + final T newBean = + emergeNewBean(setter, source, destination, sourceGetters, destinationGetters, + converter); if (newBean != null) { try @@ -648,9 +671,10 @@ public final class BeanUtils final String defaultJavaArgumentTypeMismatchMessage = "argument type mismatch"; if (defaultJavaArgumentTypeMismatchMessage.equals(ex.getMessage())) { - throw new IllegalArgumentException(defaultJavaArgumentTypeMismatchMessage + ": method '" - + setter.toGenericString() + "': cannot assign from '" - + newBean.getClass().getCanonicalName() + "'."); + throw new IllegalArgumentException(defaultJavaArgumentTypeMismatchMessage + + ": method '" + setter.toGenericString() + + "': cannot assign from '" + newBean.getClass().getCanonicalName() + + "'."); } else { throw ex; @@ -674,9 +698,10 @@ public final class BeanUtils * </p> */ @SuppressWarnings("unchecked") - private static <T> T emergeNewBean(Method setter, Object source, T destination, Map<String, Method> sourceGetters, - Map<String, Method> destinationGetters, Converter converter) throws IllegalArgumentException, - IllegalAccessException, InvocationTargetException + private static <T> T emergeNewBean(Method setter, Object source, T destination, + Map<String, Method> sourceGetters, Map<String, Method> destinationGetters, + Converter converter) throws IllegalArgumentException, IllegalAccessException, + InvocationTargetException { final AnnotationMap annotationMap = new SetterAnnotationMap(setter); final Method converterMethod = getConverterMethod(setter, source, converter); @@ -739,12 +764,15 @@ public final class BeanUtils { String methodName = "convertTo" + setter.getName().substring(SETTER_PREFIX.length()); Class<? extends Converter> converterClasss = converter.getClass(); - Collection<Class<?>> classes = ClassUtils.gatherAllCastableClassesAndInterfacesFor(sourceBean); + Collection<Class<?>> classes = + ClassUtils.gatherAllCastableClassesAndInterfacesFor(sourceBean); for (Class<?> clazz : classes) { try { - final Method converterMethod = converterClasss.getMethod(methodName, new Class[] { clazz }); + final Method converterMethod = + converterClasss.getMethod(methodName, new Class[] + { clazz }); if (converterMethod.isAccessible() == false) { converterMethod.setAccessible(true); @@ -778,27 +806,30 @@ public final class BeanUtils return null; } - private static Map<String, Method> scanForPublicMethods(Object bean, String prefix, int numberOfParameters) + private static Map<String, Method> scanForPublicMethods(Object bean, String prefix, + int numberOfParameters) { final Map<String, Method> methodMap = new LinkedHashMap<String, Method>(); scanForPublicMethods(bean, methodMap, prefix, numberOfParameters, (Set<Class<?>>) null); return methodMap; } - private static void scanForPublicMethods(Object bean, Map<String, Method> methodMap, String prefix, - int numberOfParameters, Class<?>... returnValueTypes) + private static void scanForPublicMethods(Object bean, Map<String, Method> methodMap, + String prefix, int numberOfParameters, Class<?>... returnValueTypes) { List<Class<?>> list = Arrays.asList(returnValueTypes); - scanForPublicMethods(bean, methodMap, prefix, numberOfParameters, new LinkedHashSet<Class<?>>(list)); + scanForPublicMethods(bean, methodMap, prefix, numberOfParameters, + new LinkedHashSet<Class<?>>(list)); } - private static void scanForPublicMethods(Object bean, Map<String, Method> methodMap, String prefix, - int numberOfParameters, Set<Class<?>> returnValueTypes) + private static void scanForPublicMethods(Object bean, Map<String, Method> methodMap, + String prefix, int numberOfParameters, Set<Class<?>> returnValueTypes) { for (Method method : bean.getClass().getMethods()) { final String methodName = method.getName(); - if (methodName.startsWith(prefix) && method.getParameterTypes().length == numberOfParameters + if (methodName.startsWith(prefix) + && method.getParameterTypes().length == numberOfParameters && Modifier.isPublic(method.getModifiers())) { if (returnValueTypes == null || returnValueTypes.contains(method.getReturnType())) @@ -820,7 +851,8 @@ public final class BeanUtils { try { - final Map<String, PropertyDescriptor> map = new LinkedHashMap<String, PropertyDescriptor>(); + final Map<String, PropertyDescriptor> map = + new LinkedHashMap<String, PropertyDescriptor>(); final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>(Arrays.asList(Introspector.getBeanInfo(clazz) .getPropertyDescriptors())); diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/ClassUtils.java b/common/source/java/ch/systemsx/cisd/common/utilities/ClassUtils.java index 29dba01ad90..9e0149c1968 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/ClassUtils.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/ClassUtils.java @@ -45,7 +45,8 @@ public final class ClassUtils /** * Gathers all classes and interfaces the specified object can be casted to. */ - public final static Collection<Class<?>> gatherAllCastableClassesAndInterfacesFor(final Object object) + public final static Collection<Class<?>> gatherAllCastableClassesAndInterfacesFor( + final Object object) { assert object != null : "Unspecified object"; @@ -134,7 +135,8 @@ public final class ClassUtils * <code>null</code> arguments but rather as <code>new Object[]{null}</code>. * @return an instance of type <code>interface</code>. */ - public static <T> T create(final Class<T> superClazz, final String className, final Object... argumentsOrNull) + public static <T> T create(final Class<T> superClazz, final String className, + final Object... argumentsOrNull) { assert superClazz != null : "Missing super class"; assert className != null : "Missing class name"; @@ -144,8 +146,8 @@ public final class ClassUtils final Class<?> clazz = Class.forName(className); assert clazz.isInterface() == false : "Interface '" + clazz.getName() + "' can not be instanciated as it is an interface."; - assert superClazz.isAssignableFrom(clazz) : "Class '" + clazz.getName() + "' does not implements/extends '" - + superClazz.getName() + "'."; + assert superClazz.isAssignableFrom(clazz) : "Class '" + clazz.getName() + + "' does not implements/extends '" + superClazz.getName() + "'."; if (argumentsOrNull == null) { return cast(clazz.newInstance()); @@ -154,8 +156,8 @@ public final class ClassUtils final Constructor<T> constructor = getConstructor(clazz, classes); if (constructor == null) { - throw new IllegalArgumentException(String.format("No constructor could be found for classes '%s'.", - Arrays.asList(classes))); + throw new IllegalArgumentException(String.format( + "No constructor could be found for classes '%s'.", Arrays.asList(classes))); } return constructor.newInstance(argumentsOrNull); } catch (final ClassNotFoundException e) @@ -169,8 +171,9 @@ public final class ClassUtils } catch (final NoSuchMethodException ex) { } - throw new IllegalArgumentException(String.format("Cannot instantiate class '%s' with given arguments '%s'.", - className, Arrays.asList(argumentsOrNull))); + throw new IllegalArgumentException(String.format( + "Cannot instantiate class '%s' with given arguments '%s'.", className, Arrays + .asList(argumentsOrNull))); } @SuppressWarnings("unchecked") @@ -190,8 +193,8 @@ public final class ClassUtils return classes; } - private final static <T> Constructor<T> getConstructor(final Class<?> clazz, final Class<?>[] classes) - throws NoSuchMethodException + private final static <T> Constructor<T> getConstructor(final Class<?> clazz, + final Class<?>[] classes) throws NoSuchMethodException { final Constructor<?>[] constructors = clazz.getConstructors(); Constructor<?> returned = null; @@ -250,7 +253,8 @@ public final class ClassUtils * Wraps any checked exception in a {@link CheckedExceptionTunnel}. * </p> */ - public final static void invokeMethod(final Method method, final Object obj, final Object... args) + public final static void invokeMethod(final Method method, final Object obj, + final Object... args) { try { @@ -274,7 +278,8 @@ public final class ClassUtils * * @return a <code>true</code> if <code>fieldName</code> has been modified. */ - public final static boolean setFieldValue(final Object object, final String fieldName, final Object newValue) + public final static boolean setFieldValue(final Object object, final String fieldName, + final Object newValue) { assert object != null : "Unspecified object."; final Class<?> clazz = object.getClass(); diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTask.java b/common/source/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTask.java index 4479526ac02..bf43a88d806 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTask.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTask.java @@ -105,11 +105,11 @@ public final class DirectoryScanningTimerTask extends TimerTask * next error is logged (can be used to suppress error when the directory is on a remote share and the * server is flaky sometimes) */ - public DirectoryScanningTimerTask(File sourceDirectory, FileFilter filter, IPathHandler handler, - int ignoredErrorCount) + public DirectoryScanningTimerTask(File sourceDirectory, FileFilter filter, + IPathHandler handler, int ignoredErrorCount) { - this(asScannedStore(sourceDirectory, filter), sourceDirectory, asScanningHandler(sourceDirectory, handler), - ignoredErrorCount); + this(asScannedStore(sourceDirectory, filter), sourceDirectory, asScanningHandler( + sourceDirectory, handler), ignoredErrorCount); } /** @@ -122,8 +122,8 @@ public final class DirectoryScanningTimerTask extends TimerTask * next error is logged (can be used to suppress error when the directory is on a remote share and the * server is flaky sometimes) */ - public DirectoryScanningTimerTask(IScannedStore scannedStore, File faultyPathDirectory, IStoreHandler handler, - int ignoredErrorCount) + public DirectoryScanningTimerTask(IScannedStore scannedStore, File faultyPathDirectory, + IStoreHandler handler, int ignoredErrorCount) { assert scannedStore != null; assert handler != null; @@ -265,7 +265,8 @@ public final class DirectoryScanningTimerTask extends TimerTask faultyPathsLastChanged = faultyPathsFile.lastModified(); if (operationLog.isInfoEnabled()) { - operationLog.info(String.format("Reread faulty paths file (%s), new set contains %d entries", + operationLog.info(String.format( + "Reread faulty paths file (%s), new set contains %d entries", getLocationDescription(faultyPathsFile), faultyPaths.size())); } } @@ -282,14 +283,16 @@ public final class DirectoryScanningTimerTask extends TimerTask final boolean logOperationError = (errorCountReadingDirectory < ignoredErrorCount); final ISimpleLogger errorLogger = logNotifyError ? createSimpleErrorLogger(LogCategory.NOTIFY) - : (logOperationError ? createSimpleErrorLogger(LogCategory.OPERATION) : null); + : (logOperationError ? createSimpleErrorLogger(LogCategory.OPERATION) + : null); final StoreItem[] paths = sourceDirectory.tryListSortedReadyToProcess(errorLogger); if (errorCountReadingDirectory > ignoredErrorCount && paths != null) { if (notificationLog.isInfoEnabled()) { - notificationLog.info(String.format("Directory '%s' is available again.", sourceDirectory)); + notificationLog.info(String.format("Directory '%s' is available again.", + sourceDirectory)); } } if (paths == null) diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/ExceptionUtils.java b/common/source/java/ch/systemsx/cisd/common/utilities/ExceptionUtils.java index 8b8206377e1..6417aa3989e 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/ExceptionUtils.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/ExceptionUtils.java @@ -54,12 +54,14 @@ public final class ExceptionUtils } /** Recursively copies cause exception from <var>fromException</var> to <var>toException</var>. */ - private final static void copyCauseException(final Exception fromException, final Exception toException) + private final static void copyCauseException(final Exception fromException, + final Exception toException) { assert fromException != null : "Unspecified 'from' Exception."; assert toException != null : "Unspecified 'to' Exception."; final Exception fromCauseException = - (Exception) org.apache.commons.lang.exception.ExceptionUtils.getCause(fromException); + (Exception) org.apache.commons.lang.exception.ExceptionUtils + .getCause(fromException); if (fromCauseException != null && fromCauseException != fromException) { final Exception toCauseException = createMasqueradingException(fromCauseException); @@ -67,7 +69,8 @@ public final class ExceptionUtils { if (ClassUtils.setFieldValue(toException, "cause", toCauseException) == false) { - org.apache.commons.lang.exception.ExceptionUtils.setCause(toException, toCauseException); + org.apache.commons.lang.exception.ExceptionUtils.setCause(toException, + toCauseException); } } copyCauseException(fromCauseException, toCauseException); diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/ExtendedProperties.java b/common/source/java/ch/systemsx/cisd/common/utilities/ExtendedProperties.java index a811bd2bac5..9af049459f5 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/ExtendedProperties.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/ExtendedProperties.java @@ -76,7 +76,8 @@ public final class ExtendedProperties extends Properties * @param prefix string, each property key should start with. * @param dropPrefix If <code>true</code> the prefix will be removed from the key. */ - public static ExtendedProperties getSubset(Properties properties, String prefix, boolean dropPrefix) + public static ExtendedProperties getSubset(Properties properties, String prefix, + boolean dropPrefix) { return ExtendedProperties.createWith(properties).getSubset(prefix, dropPrefix); } @@ -205,6 +206,7 @@ public final class ExtendedProperties extends Properties @Override public final String toString() { - return StringUtils.replace(super.toString(), PROPERTY_SEPARATOR, SystemUtils.LINE_SEPARATOR); + return StringUtils + .replace(super.toString(), PROPERTY_SEPARATOR, SystemUtils.LINE_SEPARATOR); } } diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/FileUtilities.java b/common/source/java/ch/systemsx/cisd/common/utilities/FileUtilities.java index bc115557a4a..6ce02a6c347 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/FileUtilities.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/FileUtilities.java @@ -91,8 +91,8 @@ public final class FileUtilities * be transfered to <code>destinationFile</code>. * @throws EnvironmentFailureException if a {@link IOException} occured. */ - public static void copyFileTo(File sourceFile, File destinationFile, boolean preservesLastModifiedDate) - throws CheckedExceptionTunnel + public static void copyFileTo(File sourceFile, File destinationFile, + boolean preservesLastModifiedDate) throws CheckedExceptionTunnel { FileInputStream inputStream = null; FileOutputStream outputStream = null; @@ -103,8 +103,8 @@ public final class FileUtilities IOUtils.copy(inputStream, outputStream); } catch (IOException ex) { - throw new EnvironmentFailureException("Couldn't copy file '" + sourceFile + "' to '" + destinationFile - + "'.", ex); + throw new EnvironmentFailureException("Couldn't copy file '" + sourceFile + "' to '" + + destinationFile + "'.", ex); } finally { IOUtils.closeQuietly(inputStream); @@ -116,8 +116,8 @@ public final class FileUtilities boolean successful = destinationFile.setLastModified(sourceFile.lastModified()); if (successful == false) { - throw new EnvironmentFailureException("Couldn't copy last modified date of file '" + sourceFile - + "' to '" + destinationFile + "' for some unknown reason."); + throw new EnvironmentFailureException("Couldn't copy last modified date of file '" + + sourceFile + "' to '" + destinationFile + "' for some unknown reason."); } } } @@ -180,7 +180,8 @@ public final class FileUtilities * @return The content of the file line by line. * @throws CheckedExceptionTunnel for wrapping an {@link IOException}, e.g. if the file does not exist. */ - public final static List<String> loadToStringList(final File file) throws CheckedExceptionTunnel + public final static List<String> loadToStringList(final File file) + throws CheckedExceptionTunnel { return loadToStringList(file, null); } @@ -194,8 +195,8 @@ public final class FileUtilities * @return The content of the file line by line. * @throws CheckedExceptionTunnel for wrapping an {@link IOException}, e.g. if the file does not exist. */ - public final static List<String> loadToStringList(final File file, final ILineFilter lineFilterOrNull) - throws CheckedExceptionTunnel + public final static List<String> loadToStringList(final File file, + final ILineFilter lineFilterOrNull) throws CheckedExceptionTunnel { assert file != null : "Unspecified file."; @@ -224,7 +225,8 @@ public final class FileUtilities * @return The content of the resource, or <code>null</code> if the specified resource does not exist. * @throws CheckedExceptionTunnel for wrapping an {@link IOException} */ - public static String loadToString(final Class<?> clazz, final String resource) throws CheckedExceptionTunnel + public static String loadToString(final Class<?> clazz, final String resource) + throws CheckedExceptionTunnel { assert clazz != null : "Given class can not be null."; assert resource != null && resource.length() > 0 : "Given resource can not be null."; @@ -293,8 +295,8 @@ public final class FileUtilities } } - private final static BufferedReader tryGetBufferedReader(final Class<?> clazz, final String resource) - throws FileNotFoundException + private final static BufferedReader tryGetBufferedReader(final Class<?> clazz, + final String resource) throws FileNotFoundException { final URL url = clazz.getResource(resource); if (url == null) @@ -322,8 +324,8 @@ public final class FileUtilities return builder.toString(); } - private final static List<String> readStringList(final BufferedReader reader, final ILineFilter lineFilterOrNull) - throws IOException + private final static List<String> readStringList(final BufferedReader reader, + final ILineFilter lineFilterOrNull) throws IOException { assert reader != null : "Unspecified BufferedReader."; final ILineFilter lineFilter; @@ -375,13 +377,14 @@ public final class FileUtilities final String msg = checkPathFullyAccessible(directory, kindOfDirectory, "directory"); if (msg == null && directory.isDirectory() == false) { - return String.format("Path '%s' is supposed to be a %s directory, but is a file.", directory.getPath(), - kindOfDirectory); + return String.format("Path '%s' is supposed to be a %s directory, but is a file.", + directory.getPath(), kindOfDirectory); } return msg; } - private static String checkPathFullyAccessible(File path, String kindOfPath, String directoryOrFile) + private static String checkPathFullyAccessible(File path, String kindOfPath, + String directoryOrFile) { assert path != null; assert kindOfPath != null; @@ -391,18 +394,18 @@ public final class FileUtilities { if (path.exists() == false) { - return String.format("%s %s '%s' does not exist.", StringUtilities.capitalize(kindOfPath), - directoryOrFile, path.getPath()); + return String.format("%s %s '%s' does not exist.", StringUtilities + .capitalize(kindOfPath), directoryOrFile, path.getPath()); } else { - return String.format("%s %s '%s' is not readable.", StringUtilities.capitalize(kindOfPath), - directoryOrFile, path.getPath()); + return String.format("%s %s '%s' is not readable.", StringUtilities + .capitalize(kindOfPath), directoryOrFile, path.getPath()); } } if (path.canWrite() == false) { - return String.format("%s directory '%s' is not writable.", StringUtilities.capitalize(kindOfPath), path - .getPath()); + return String.format("%s directory '%s' is not writable.", StringUtilities + .capitalize(kindOfPath), path.getPath()); } return null; } @@ -447,7 +450,8 @@ public final class FileUtilities { if (loggerOrNull != null) { - loggerOrNull.log(LogLevel.INFO, String.format("Deleting file '%s'", file.getPath())); + loggerOrNull.log(LogLevel.INFO, String.format("Deleting file '%s'", file + .getPath())); } file.delete(); } @@ -455,7 +459,8 @@ public final class FileUtilities } if (loggerOrNull != null) { - loggerOrNull.log(LogLevel.INFO, String.format("Deleting directory '%s'", path.getPath())); + loggerOrNull.log(LogLevel.INFO, String + .format("Deleting directory '%s'", path.getPath())); } return path.delete(); } @@ -504,7 +509,8 @@ public final class FileUtilities private boolean terminated; - LastChangedWorker(File root, boolean subDirectoriesOnly, long reference, boolean referenceIsRelative) + LastChangedWorker(File root, boolean subDirectoriesOnly, long reference, + boolean referenceIsRelative) { assert root != null; @@ -526,8 +532,8 @@ public final class FileUtilities if (path.canRead() == false) { - throw new CheckedExceptionTunnel(new IOException(String.format("Path '%s' cannot be read.", path - .getPath()))); + throw new CheckedExceptionTunnel(new IOException(String.format( + "Path '%s' cannot be read.", path.getPath()))); } final long lastModified = path.lastModified(); lastChanged = Math.max(lastModified, lastChanged); @@ -565,7 +571,8 @@ public final class FileUtilities } if (Thread.interrupted()) { - throw new CheckedExceptionTunnel(new InterruptedException("lastChanged() interrupted")); + throw new CheckedExceptionTunnel(new InterruptedException( + "lastChanged() interrupted")); } traverse(entry); } @@ -620,7 +627,8 @@ public final class FileUtilities */ public static long lastChanged(File path, boolean subDirectoriesOnly, long stopWhenFindYounger) { - return (new LastChangedWorker(path, subDirectoriesOnly, stopWhenFindYounger, false)).getLastChanged(); + return (new LastChangedWorker(path, subDirectoriesOnly, stopWhenFindYounger, false)) + .getLastChanged(); } /** @@ -643,9 +651,11 @@ public final class FileUtilities * @throws CheckedExceptionTunnel of a {@link InterruptedException} if the thread that the method runs in gets * interrupted. */ - public static long lastChangedRelative(File path, boolean subDirectoriesOnly, long stopWhenFindYoungerRelative) + public static long lastChangedRelative(File path, boolean subDirectoriesOnly, + long stopWhenFindYoungerRelative) { - return (new LastChangedWorker(path, subDirectoriesOnly, stopWhenFindYoungerRelative, true)).getLastChanged(); + return (new LastChangedWorker(path, subDirectoriesOnly, stopWhenFindYoungerRelative, true)) + .getLastChanged(); } /** @@ -703,7 +713,8 @@ public final class FileUtilities * @param regexOrNull pattern to find out the counter. If <code>null</code> then a default (<code>(\\d+)</code>) * will be used. The given <var>regex</var> must contain <code>(\\d+)</code> or <code>([0-9]+)</code>. */ - public final static File createNextNumberedFile(File path, Pattern regexOrNull, String defaultFileNameOrNull) + public final static File createNextNumberedFile(File path, Pattern regexOrNull, + String defaultFileNameOrNull) { assert path != null; if (path.exists() == false) @@ -716,7 +727,8 @@ public final class FileUtilities pattern = ONE_OR_MORE_DIGITS; } else { - assert regexOrNull.pattern().indexOf("(\\d+)") > -1 || regexOrNull.pattern().indexOf("([0-9]+)") > -1; + assert regexOrNull.pattern().indexOf("(\\d+)") > -1 + || regexOrNull.pattern().indexOf("([0-9]+)") > -1; pattern = regexOrNull; } @@ -733,7 +745,8 @@ public final class FileUtilities { fileName = pathName + "1"; } - return createNextNumberedFile(new File(path.getParent(), fileName), pattern, defaultFileNameOrNull); + return createNextNumberedFile(new File(path.getParent(), fileName), pattern, + defaultFileNameOrNull); } StringBuilder builder = new StringBuilder(); int nextStart = 0; @@ -823,25 +836,32 @@ public final class FileUtilities Arrays.sort(files, FileComparator.BY_LAST_MODIFIED); } - private static void logFailureInDirectoryListing(RuntimeException exOrNull, File directory, ISimpleLogger logger) + private static void logFailureInDirectoryListing(RuntimeException exOrNull, File directory, + ISimpleLogger logger) { if (exOrNull == null) { if (directory.isFile()) { - logger.log(LogLevel.ERROR, String.format( - "Failed to get listing of directory '%s' (path is file instead of directory).", directory)); + logger + .log( + LogLevel.ERROR, + String + .format( + "Failed to get listing of directory '%s' (path is file instead of directory).", + directory)); } else { - logger.log(LogLevel.ERROR, String.format("Failed to get listing of directory '%s' (path not found).", - directory)); + logger.log(LogLevel.ERROR, String.format( + "Failed to get listing of directory '%s' (path not found).", directory)); } } else { StringWriter exStackWriter = new StringWriter(); exOrNull.printStackTrace(new PrintWriter(exStackWriter)); - logger.log(LogLevel.ERROR, String.format("Failed to get listing of directory '%s'. Exception: %s", - directory, exStackWriter.toString())); + logger.log(LogLevel.ERROR, String.format( + "Failed to get listing of directory '%s'. Exception: %s", directory, + exStackWriter.toString())); } } @@ -892,7 +912,8 @@ public final class FileUtilities * @param postfix The postfix to use for the temporary name. * @return The name of the temporary file, or <code>null</code>, if the resource could not be copied. */ - public final static String tryCopyResourceToTempFile(String resource, String prefix, String postfix) + public final static String tryCopyResourceToTempFile(String resource, String prefix, + String postfix) { try { @@ -916,8 +937,8 @@ public final class FileUtilities final File[] fileList = directory.listFiles(); if (fileList == null) { - throw EnvironmentFailureException.fromTemplate("Failed to get listing of directory '%s'", directory - .getAbsolutePath()); + throw EnvironmentFailureException.fromTemplate( + "Failed to get listing of directory '%s'", directory.getAbsolutePath()); } return fileList; } diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcher.java b/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcher.java index 65b709d6fe3..2aa0ba20dfc 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcher.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcher.java @@ -38,9 +38,11 @@ public abstract class FileWatcher extends TimerTask static final String HAS_CHANGED_FORMAT = "Watched file '%s' has changed."; - static final String PERMISSION_EXCEPTION_FORMAT = "Was not allowed to check existence of file '%s'."; + static final String PERMISSION_EXCEPTION_FORMAT = + "Was not allowed to check existence of file '%s'."; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, FileWatcher.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, FileWatcher.class); /** The default <code>FileWatcherState</code> implementation used. */ private static final IFileWatcherState DEFAULT_FILE_WATCHER_STATE = new LastModifiedState(); diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcherSynchronizer.java b/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcherSynchronizer.java index 6cdc01f992c..25b45c7c7bd 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcherSynchronizer.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/FileWatcherSynchronizer.java @@ -81,7 +81,8 @@ public class FileWatcherSynchronizer extends TimerTask } } - public final synchronized void addChangeListener(final File file, final ChangeListener changeListener) + public final synchronized void addChangeListener(final File file, + final ChangeListener changeListener) { FileWatcher fileWatcher = fileWatchers.get(file); if (fileWatcher == null) @@ -101,7 +102,8 @@ public class FileWatcherSynchronizer extends TimerTask }; if (operationLog.isDebugEnabled()) { - operationLog.debug(String.format("A new watcher has been created for file '%s'", file)); + operationLog.debug(String.format("A new watcher has been created for file '%s'", + file)); } fileWatchers.put(file, fileWatcher); } @@ -114,13 +116,16 @@ public class FileWatcherSynchronizer extends TimerTask listeners.add(changeListener); if (operationLog.isDebugEnabled()) { - operationLog.debug(String.format( - "A new listener has been registered for file '%s'. Currently %d listener(s) registered.", file, - listeners.size())); + operationLog + .debug(String + .format( + "A new listener has been registered for file '%s'. Currently %d listener(s) registered.", + file, listeners.size())); } } - public final synchronized void removeChangeListener(final File file, final ChangeListener changeListener) + public final synchronized void removeChangeListener(final File file, + final ChangeListener changeListener) { final FileWatcher fileWatcher = fileWatchers.get(file); if (fileWatcher == null) @@ -136,8 +141,11 @@ public class FileWatcherSynchronizer extends TimerTask final int size = listeners.size(); if (operationLog.isDebugEnabled()) { - operationLog.debug(String.format( - "A listener for file '%s' has been removed. Currently %d listener(s) registered.", file, size)); + operationLog + .debug(String + .format( + "A listener for file '%s' has been removed. Currently %d listener(s) registered.", + file, size)); } if (size == 0) { diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/IExitHandler.java b/common/source/java/ch/systemsx/cisd/common/utilities/IExitHandler.java index 582d3d39948..50558a7306e 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/IExitHandler.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/IExitHandler.java @@ -17,8 +17,8 @@ package ch.systemsx.cisd.common.utilities; /** - * Interface which capsulates the behaviour of a system exit. - * + * Interface which capsulates the behaviour of a system exit. + * * @author Franz-Josef Elmer */ public interface IExitHandler diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/ITriggerable.java b/common/source/java/ch/systemsx/cisd/common/utilities/ITriggerable.java index 7742bff2535..77550c71300 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/ITriggerable.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/ITriggerable.java @@ -17,8 +17,8 @@ package ch.systemsx.cisd.common.utilities; /** - * A role that allows to trigger some operation. - * + * A role that allows to trigger some operation. + * * @author Bernd Rinn */ public interface ITriggerable @@ -28,5 +28,5 @@ public interface ITriggerable * The trigger. */ public void trigger(); - + } diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/ModifiedShortPrefixToStringStyle.java b/common/source/java/ch/systemsx/cisd/common/utilities/ModifiedShortPrefixToStringStyle.java index d23f0a9cfcb..b4806772d39 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/ModifiedShortPrefixToStringStyle.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/ModifiedShortPrefixToStringStyle.java @@ -18,20 +18,20 @@ package ch.systemsx.cisd.common.utilities; import org.apache.commons.lang.builder.ToStringStyle; - /** - * A modified short prefix {@link ToStringStyle} which allows to work together with jmock and - * cruisecontrol. The problem was that in jmock exception messages <code>]]></code> appeared which is the - * end of a <code><![CDATA[</code> section in the XML test report. This yields a hiccup in cruisecontrol. - * + * A modified short prefix {@link ToStringStyle} which allows to work together with jmock and cruisecontrol. The problem + * was that in jmock exception messages <code>]]></code> appeared which is the end of a <code><![CDATA[</code> + * section in the XML test report. This yields a hiccup in cruisecontrol. + * * @author Franz-Josef Elmer */ public class ModifiedShortPrefixToStringStyle extends ToStringStyle { private static final long serialVersionUID = 1L; - + /** The one and only one instance. */ - public static final ToStringStyle MODIFIED_SHORT_PREFIX_STYLE = new ModifiedShortPrefixToStringStyle(); + public static final ToStringStyle MODIFIED_SHORT_PREFIX_STYLE = + new ModifiedShortPrefixToStringStyle(); private ModifiedShortPrefixToStringStyle() { @@ -42,7 +42,8 @@ public class ModifiedShortPrefixToStringStyle extends ToStringStyle } /** - * <p>Ensure <code>Singleton</ode> after serialization.</p> + * <p> + * Ensure <code>Singleton</ode> after serialization.</p> * @return the singleton */ private Object readResolve() diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilter.java b/common/source/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilter.java index f7ee6291719..0d184a6ba91 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilter.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilter.java @@ -35,7 +35,7 @@ public class NamePrefixFileFilter implements FileFilter public NamePrefixFileFilter(String prefix, boolean shouldStartWithPrefix) { assert prefix != null; - + this.prefix = prefix; this.shouldStartWithPrefix = shouldStartWithPrefix; } @@ -43,7 +43,7 @@ public class NamePrefixFileFilter implements FileFilter public boolean accept(File pathname) { assert pathname != null; - + final boolean startsWithPrefix = pathname.getName().startsWith(prefix); return startsWithPrefix == shouldStartWithPrefix; } diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/OSUtilities.java b/common/source/java/ch/systemsx/cisd/common/utilities/OSUtilities.java index fbb92686ea1..fedbc80aedd 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/OSUtilities.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/OSUtilities.java @@ -69,7 +69,7 @@ public class OSUtilities { return System.getProperty("os.arch") + "-" + System.getProperty("os.name"); } - + /** * @return The name of user that runs this program. */ @@ -98,7 +98,8 @@ public class OSUtilities */ public static Set<String> getOSPath() { - final String[] pathEntries = System.getenv("PATH").split(Pattern.quote(System.getProperty("path.separator"))); + final String[] pathEntries = + System.getenv("PATH").split(Pattern.quote(System.getProperty("path.separator"))); return new LinkedHashSet<String>(Arrays.asList(pathEntries)); } @@ -172,7 +173,8 @@ public class OSUtilities */ public static File findExecutable(String executableName, Set<String> pathSet) { - final String executableNameWithExtension = addWindowsExecutableExtensionIfNecessary(executableName); + final String executableNameWithExtension = + addWindowsExecutableExtensionIfNecessary(executableName); for (String dir : pathSet) { final File fileToCheck = new File(dir, executableNameWithExtension); @@ -189,7 +191,8 @@ public class OSUtilities */ public static boolean executableExists(String executableName) { - return (new File(OSUtilities.addWindowsExecutableExtensionIfNecessary(executableName))).exists(); + return (new File(OSUtilities.addWindowsExecutableExtensionIfNecessary(executableName))) + .exists(); } /** @@ -197,7 +200,8 @@ public class OSUtilities */ public static boolean executableExists(File executable) { - return (new File(OSUtilities.addWindowsExecutableExtensionIfNecessary(executable.getPath()))).exists(); + return (new File(OSUtilities.addWindowsExecutableExtensionIfNecessary(executable.getPath()))) + .exists(); } private static String addWindowsExecutableExtensionIfNecessary(String executableName) diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/PasswordGenerator.java b/common/source/java/ch/systemsx/cisd/common/utilities/PasswordGenerator.java index 77c36ac8026..14d8e66ae2f 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/PasswordGenerator.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/PasswordGenerator.java @@ -20,7 +20,7 @@ import java.util.Random; /** * Generator for human pronounceable passwords - * + * * @author Franz-Josef Elmer */ public class PasswordGenerator @@ -41,7 +41,7 @@ public class PasswordGenerator return "0123456789"; } }, - + CONSONANT() { @Override @@ -55,9 +55,9 @@ public class PasswordGenerator { return "bdcfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"; } - + }, - + VOWEL() { @Override @@ -72,23 +72,23 @@ public class PasswordGenerator return "aeiouyAEIOUY"; } }; - + State nextState(Random random) { return this; } - + void appendCharacterTo(StringBuilder builder, Random random) { String characters = getCharacters(); builder.append(characters.charAt(random.nextInt(characters.length()))); } - + abstract String getCharacters(); } - + private final Random random; - + /** * Creates an instance based on the default constructor of {@link Random}. */ @@ -105,7 +105,7 @@ public class PasswordGenerator assert random != null : "Unspecified random number generator."; this.random = random; } - + /** * Creates a password of specified length. */ diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/PathPrefixPrepender.java b/common/source/java/ch/systemsx/cisd/common/utilities/PathPrefixPrepender.java index b4b1c299972..6eb8cc20243 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/PathPrefixPrepender.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/PathPrefixPrepender.java @@ -38,8 +38,8 @@ public final class PathPrefixPrepender /** * Creates an instances for the specified prefixes. <code>null</code> arguments are handled as empty strings. */ - public PathPrefixPrepender(final String prefixForAbsolutePathsOrNull, final String prefixForRelativePathsOrNull) - throws ConfigurationFailureException + public PathPrefixPrepender(final String prefixForAbsolutePathsOrNull, + final String prefixForRelativePathsOrNull) throws ConfigurationFailureException { this.prefixForAbsolutePaths = StringUtils.defaultString(prefixForAbsolutePathsOrNull); assertValid(this.prefixForAbsolutePaths, "absolute"); @@ -60,7 +60,8 @@ public final class PathPrefixPrepender return pathPrefix + "/"; } - private void assertValid(final String prefix, final String type) throws ConfigurationFailureException + private void assertValid(final String prefix, final String type) + throws ConfigurationFailureException { if (prefix.length() != 0) { @@ -68,7 +69,8 @@ public final class PathPrefixPrepender if (file.exists() == false) { throw ConfigurationFailureException.fromTemplate( - "Invalid prefix for %s paths: given file '%s' does not exist.", type, file.getAbsolutePath()); + "Invalid prefix for %s paths: given file '%s' does not exist.", type, file + .getAbsolutePath()); } } } @@ -79,6 +81,8 @@ public final class PathPrefixPrepender public String addPrefixTo(final String path) { assert path != null : "Undefined path."; - return (FilenameUtils.getPrefixLength(path) > 0 ? prefixForAbsolutePaths : prefixForRelativePaths) + path; + return (FilenameUtils.getPrefixLength(path) > 0 ? prefixForAbsolutePaths + : prefixForRelativePaths) + + path; } } diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMaker.java b/common/source/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMaker.java index ac8eba0e301..81ac30951e6 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMaker.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMaker.java @@ -41,17 +41,20 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, RecursiveHardLinkMaker.class); - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, RecursiveHardLinkMaker.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, RecursiveHardLinkMaker.class); private final String linkExecPath; private final RetryingOperationTimeout singleFileLinkTimeout; - private RecursiveHardLinkMaker(final String linkExecPath, RetryingOperationTimeout singleFileLinkTimeoutOrNull) + private RecursiveHardLinkMaker(final String linkExecPath, + RetryingOperationTimeout singleFileLinkTimeoutOrNull) { this.linkExecPath = linkExecPath; this.singleFileLinkTimeout = - singleFileLinkTimeoutOrNull != null ? singleFileLinkTimeoutOrNull : createNoTimeout(); + singleFileLinkTimeoutOrNull != null ? singleFileLinkTimeoutOrNull + : createNoTimeout(); } private RetryingOperationTimeout createNoTimeout() @@ -106,11 +109,13 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier * @param millisToSleepOnFailure The number of milliseconds we should wait before re-executing the copy of a single * file. Specify 0 to wait till the first operation completes. */ - public static final IPathImmutableCopier tryCreateRetrying(final long millisToWaitForCompletion, - final int maxRetryOnFailure, final long millisToSleepOnFailure) + public static final IPathImmutableCopier tryCreateRetrying( + final long millisToWaitForCompletion, final int maxRetryOnFailure, + final long millisToSleepOnFailure) { RetryingOperationTimeout timeout = - new RetryingOperationTimeout(millisToWaitForCompletion, maxRetryOnFailure, millisToSleepOnFailure); + new RetryingOperationTimeout(millisToWaitForCompletion, maxRetryOnFailure, + millisToSleepOnFailure); return tryCreate(timeout); } @@ -120,7 +125,8 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier return tryCreate(null); } - private static final IPathImmutableCopier tryCreate(RetryingOperationTimeout singleFileLinkTimeoutOrNull) + private static final IPathImmutableCopier tryCreate( + RetryingOperationTimeout singleFileLinkTimeoutOrNull) { final File lnExec = OSUtilities.findExecutable(HARD_LINK_EXEC); if (lnExec == null) @@ -137,7 +143,8 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier * <i>Note that <var>nameOrNull</var> cannot already exist in given <var>destinationDirectory</var>.</i> * </p> */ - public final File tryCopy(final File path, final File destinationDirectory, final String nameOrNull) + public final File tryCopy(final File path, final File destinationDirectory, + final String nameOrNull) { assert path != null : "Given path can not be null."; assert destinationDirectory != null && destinationDirectory.isDirectory() : "Given destination directory can not be null and must be a directory."; @@ -145,19 +152,21 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier final File destFile = new File(destinationDirectory, destName); if (destFile.exists()) { - operationLog.error(String.format("File '%s' already exists in given destination directory '%s'", destName, + operationLog.error(String.format( + "File '%s' already exists in given destination directory '%s'", destName, destinationDirectory)); return null; } if (operationLog.isInfoEnabled()) { - operationLog.info(String.format("Creating a hard link copy of '%s' in '%s'.", path.getPath(), - destinationDirectory.getPath())); + operationLog.info(String.format("Creating a hard link copy of '%s' in '%s'.", path + .getPath(), destinationDirectory.getPath())); } return tryMakeCopy(path, destinationDirectory, nameOrNull); } - private final File tryMakeCopy(final File resource, final File destinationDirectory, final String nameOrNull) + private final File tryMakeCopy(final File resource, final File destinationDirectory, + final String nameOrNull) { if (resource.isFile()) { @@ -185,11 +194,12 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier { if (resource.exists() == false) { - operationLog.error(String.format("Path '%s' vanished during processing.", resource)); + operationLog.error(String.format("Path '%s' vanished during processing.", + resource)); } else { - operationLog.error(String.format("Found path '%s' that is neither a file nor a directory.", - resource)); + operationLog.error(String.format( + "Found path '%s' that is neither a file nor a directory.", resource)); } } return dir; @@ -204,12 +214,13 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier { if (dir.isDirectory()) { - machineLog.error(String.format("Directory %s already exists in %s", name, destDir.getAbsolutePath())); + machineLog.error(String.format("Directory %s already exists in %s", name, destDir + .getAbsolutePath())); ok = true; } else { - machineLog.error(String.format("Could not create directory %s inside %s.", name, destDir - .getAbsolutePath())); + machineLog.error(String.format("Could not create directory %s inside %s.", name, + destDir.getAbsolutePath())); if (dir.isFile()) { machineLog.error("There is a file with a same name."); @@ -219,7 +230,8 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier return ok ? dir : null; } - private final File tryCreateHardLinkIn(final File file, final File destDir, final String nameOrNull) + private final File tryCreateHardLinkIn(final File file, final File destDir, + final String nameOrNull) { assert file.isFile() : String.format("Given file '%s' must be a file and is not.", file); final File destFile = new File(destDir, nameOrNull == null ? file.getName() : nameOrNull); @@ -228,13 +240,13 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier { public boolean run() { - return ProcessExecutionHelper.runAndLog(cmd, singleFileLinkTimeout.getMillisToWaitForCompletion(), - operationLog, machineLog); + return ProcessExecutionHelper.runAndLog(cmd, singleFileLinkTimeout + .getMillisToWaitForCompletion(), operationLog, machineLog); } }; boolean ok = - runRepeatableProcess(processTask, singleFileLinkTimeout.getMaxRetryOnFailure(), singleFileLinkTimeout - .getMillisToSleepOnFailure()); + runRepeatableProcess(processTask, singleFileLinkTimeout.getMaxRetryOnFailure(), + singleFileLinkTimeout.getMillisToSleepOnFailure()); return ok ? destFile : null; } @@ -252,8 +264,8 @@ public final class RecursiveHardLinkMaker implements IPathImmutableCopier boolean run(); // returns true if operation succeeded } - private static boolean runRepeatableProcess(final IProcessTask task, final int maxRetryOnFailure, - final long millisToSleepOnFailure) + private static boolean runRepeatableProcess(final IProcessTask task, + final int maxRetryOnFailure, final long millisToSleepOnFailure) { IProcess process = new IProcess() { diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/RegexFileFilter.java b/common/source/java/ch/systemsx/cisd/common/utilities/RegexFileFilter.java index 151bef30956..530ee22e72d 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/RegexFileFilter.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/RegexFileFilter.java @@ -96,7 +96,8 @@ public class RegexFileFilter implements FileFilter return false; } final PathPattern that = (PathPattern) obj; - return this.type.equals(that.type) && this.pattern.pattern().equals(that.pattern.pattern()); + return this.type.equals(that.type) + && this.pattern.pattern().equals(that.pattern.pattern()); } @Override diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/StringUtilities.java b/common/source/java/ch/systemsx/cisd/common/utilities/StringUtilities.java index abef1b0b831..18e5451489c 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/StringUtilities.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/StringUtilities.java @@ -39,31 +39,38 @@ public final class StringUtilities private static final String[] STRINGS = new String[] - { "phalanx", "nightmare", "concierge", "asbestos", "cody", "hermit", "nbc", "couplet", "dice", - "thumbnail", "finley", "figure", "exclamation", "whoosh", "punish", "servitor", "portend", - "boulevard", "bacterial", "dilate", "emboss", "birmingham", "illustrate", "pomona", "truk", - "bursitis", "trustworthy", "harriman", "schenectady", "obligate", "oceania", "knew", - "quickstep", "woo", "strickland", "sadie", "malabar", "posit", "breadfruit", "grandfather", - "vishnu", "vacuous", "melpomene", "assam", "blaine", "taskmaster", "polymeric", "hector", - "counterrevolution", "compassionate", "linkage", "distant", "vet", "shako", "eagan", - "neutronium", "stony", "lie", "hoydenish", "dial", "hecate", "pinch", "olin", "piglet", - "basswood", "yawn", "ouzo", "scrupulosity", "bestiary", "subpoena", "nudge", "baton", "thing", - "hallmark", "bossy", "preferential", "bambi", "narwhal", "brighten", "omnipotent", "forsake", - "flapping", "orthodoxy", "upcome", "teaspoonful", "wabash", "lipid", "enjoin", "shoshone", - "wartime", "gatekeeper", "litigate", "siderite", "sadden", "visage", "boogie", "scald", - "equate", "tragic", "ordinary", "wick", "gigawatt", "desultory", "bambi", "aureomycin", "car", - "especial", "rescue", "protector", "burnett", "constant", "heroes", "filmstrip", "homeown", - "verdant", "governor", "cornwall", "predisposition", "sedan", "resemblant", "satellite", - "committeemen", "given", "narragansett", "switzer", "clockwatcher", "sweeten", "monologist", - "execrate", "gila", "lad", "mahayanist", "solicitation", "linemen", "reading", "hoard", - "phyla", "carcinoma", "glycol", "polymer", "hangmen", "dualism", "betrayal", "corpsman", - "stint", "hannah", "balsam", "granola", "charitable", "osborn", "party", "laboratory", - "norwich", "laxative", "collude", "rockefeller", "crack", "lamarck", "purposeful", - "neuroanotomy", "araby", "crucible", "oratorical", "dramaturgy", "kitty", "pit", "ephesus", - "bum", "amuse", "clogging", "joker", "fobbing", "extent", "colossal", "macromolecule", - "choppy", "tennessee", "primrose", "glassine", "vampire", "chap", "precursor", "incorrigible", - "slither", "interrogate", "spectral", "debut", "creche", "pyrolysis", "homicidal", "sonnet", - "gin", "science", "magma", "metaphor", "cobble", "dyer", "narrate", "goody", "optometric" }; + { "phalanx", "nightmare", "concierge", "asbestos", "cody", "hermit", "nbc", + "couplet", "dice", "thumbnail", "finley", "figure", "exclamation", + "whoosh", "punish", "servitor", "portend", "boulevard", "bacterial", + "dilate", "emboss", "birmingham", "illustrate", "pomona", "truk", + "bursitis", "trustworthy", "harriman", "schenectady", "obligate", + "oceania", "knew", "quickstep", "woo", "strickland", "sadie", "malabar", + "posit", "breadfruit", "grandfather", "vishnu", "vacuous", "melpomene", + "assam", "blaine", "taskmaster", "polymeric", "hector", + "counterrevolution", "compassionate", "linkage", "distant", "vet", "shako", + "eagan", "neutronium", "stony", "lie", "hoydenish", "dial", "hecate", + "pinch", "olin", "piglet", "basswood", "yawn", "ouzo", "scrupulosity", + "bestiary", "subpoena", "nudge", "baton", "thing", "hallmark", "bossy", + "preferential", "bambi", "narwhal", "brighten", "omnipotent", "forsake", + "flapping", "orthodoxy", "upcome", "teaspoonful", "wabash", "lipid", + "enjoin", "shoshone", "wartime", "gatekeeper", "litigate", "siderite", + "sadden", "visage", "boogie", "scald", "equate", "tragic", "ordinary", + "wick", "gigawatt", "desultory", "bambi", "aureomycin", "car", "especial", + "rescue", "protector", "burnett", "constant", "heroes", "filmstrip", + "homeown", "verdant", "governor", "cornwall", "predisposition", "sedan", + "resemblant", "satellite", "committeemen", "given", "narragansett", + "switzer", "clockwatcher", "sweeten", "monologist", "execrate", "gila", + "lad", "mahayanist", "solicitation", "linemen", "reading", "hoard", + "phyla", "carcinoma", "glycol", "polymer", "hangmen", "dualism", + "betrayal", "corpsman", "stint", "hannah", "balsam", "granola", + "charitable", "osborn", "party", "laboratory", "norwich", "laxative", + "collude", "rockefeller", "crack", "lamarck", "purposeful", "neuroanotomy", + "araby", "crucible", "oratorical", "dramaturgy", "kitty", "pit", "ephesus", + "bum", "amuse", "clogging", "joker", "fobbing", "extent", "colossal", + "macromolecule", "choppy", "tennessee", "primrose", "glassine", "vampire", + "chap", "precursor", "incorrigible", "slither", "interrogate", "spectral", + "debut", "creche", "pyrolysis", "homicidal", "sonnet", "gin", "science", + "magma", "metaphor", "cobble", "dyer", "narrate", "goody", "optometric" }; private final static Pattern pattern = Pattern.compile("([a-zA-Z]+)([0-9]+)"); @@ -71,7 +78,7 @@ public final class StringUtilities { // This class can not be instantiated. } - + /** * Computes the MD5 hash value of <var>string</var>. * @@ -80,14 +87,14 @@ public final class StringUtilities public static String computeMD5Hash(String string) { assert string != null : "Unspecified string."; - + try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(string.getBytes("utf8")); byte messageDigest[] = algorithm.digest(); - + StringBuilder builder = new StringBuilder(); for (int i = 0; i < messageDigest.length; i++) { diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/SynchronizationMonitor.java b/common/source/java/ch/systemsx/cisd/common/utilities/SynchronizationMonitor.java index 42718ce9891..0223f167946 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/SynchronizationMonitor.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/SynchronizationMonitor.java @@ -18,17 +18,17 @@ package ch.systemsx.cisd.common.utilities; /** * A pure monitor for us in <code>synchronized()</code> clauses. - * + * * @author Bernd Rinn */ public final class SynchronizationMonitor { - + private SynchronizationMonitor() { // Use create() to call this. } - + /** * Creates a new {@link SynchronizationMonitor}. */ diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/Template.java b/common/source/java/ch/systemsx/cisd/common/utilities/Template.java index 50191c811ef..0e492528a3d 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/Template.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/Template.java @@ -23,25 +23,28 @@ import java.util.Map; /** * A little template engine. Usage example: + * * <pre> - * Template template = new Template("Hello ${name}!"); - * template.bind("name", "world"); + * Template template = new Template("Hello ${name}!"); + * template.bind("name", "world"); * String text = template.createText(); * </pre> - * The method {@link #bind(String, String)} throws an exception if the placeholder name is unknown. - * The method {@link #attemptToBind(String, String)} returns <code>false</code> if the placeholder name is unknown. - * The method {@link #createText()} throws an exception if not all placeholders have been bound. + * + * The method {@link #bind(String, String)} throws an exception if the placeholder name is unknown. The method + * {@link #attemptToBind(String, String)} returns <code>false</code> if the placeholder name is unknown. The method + * {@link #createText()} throws an exception if not all placeholders have been bound. * <p> * Since placeholder bindings change the state of an instance of this class there is method {@link #createFreshCopy()} * which creates a copy without reparsing the template. Usage example: + * * <pre> - * static final Template TEMPLATE = new Template("Hello ${name}!"); + * static final Template TEMPLATE = new Template("Hello ${name}!"); * * void doSomething() * { - * Template template = TEMPLATE.createFreshCopy(); - * template.bind("name", "world"); - * String text = template.createText(); + * Template template = TEMPLATE.createFreshCopy(); + * template.bind("name", "world"); + * String text = template.createText(); * } * </pre> * @@ -50,41 +53,44 @@ import java.util.Map; public class Template { private static final char PLACEHOLDER_ESCAPE_CHARACTER = '$'; + private static final char PLACEHOLDER_START_CHARACTER = '{'; + private static final char PLACEHOLDER_END_CHARACTER = '}'; - + private static final String createPlaceholder(String variableName) { - return PLACEHOLDER_ESCAPE_CHARACTER + (PLACEHOLDER_START_CHARACTER + variableName) + PLACEHOLDER_END_CHARACTER; + return PLACEHOLDER_ESCAPE_CHARACTER + (PLACEHOLDER_START_CHARACTER + variableName) + + PLACEHOLDER_END_CHARACTER; } - + private static interface IToken { public void appendTo(StringBuilder builder); } - + private static final class PlainToken implements IToken { private final String plainText; - + PlainToken(String plainText) { assert plainText != null : "Unspecified plain text."; this.plainText = plainText; } - + public void appendTo(StringBuilder builder) { builder.append(plainText); } } - + private static final class VariableToken implements IToken { private final String variableName; - + private String value; - + VariableToken(String variablePlaceHolder) { assert variablePlaceHolder != null : "Unspecified variable place holder."; @@ -95,7 +101,7 @@ public class Template { builder.append(isBound() ? value : createPlaceholder(variableName)); } - + String getVariableName() { return variableName; @@ -105,13 +111,13 @@ public class Template { return value != null; } - + void bind(String v) { this.value = v; } } - + private static enum State { PLAIN() @@ -127,7 +133,7 @@ public class Template return PLAIN; } }, - + STARTING_PLACEHOLDER() { @Override @@ -135,7 +141,7 @@ public class Template { switch (character) { - case PLACEHOLDER_ESCAPE_CHARACTER: + case PLACEHOLDER_ESCAPE_CHARACTER: tokenBuilder.addCharacter(PLACEHOLDER_ESCAPE_CHARACTER); return PLAIN; case PLACEHOLDER_START_CHARACTER: @@ -148,7 +154,7 @@ public class Template } } }, - + PLACEHOLDER() { @Override @@ -163,14 +169,16 @@ public class Template return PLACEHOLDER; } }; - + abstract State next(char character, TokenBuilder tokenBuilder); } - + private static final class TokenBuilder { private final Map<String, VariableToken> variableTokens; + private final List<IToken> tokens; + private final StringBuilder builder; TokenBuilder(Map<String, VariableToken> variableTokens, List<IToken> tokens) @@ -184,7 +192,7 @@ public class Template { builder.append(character); } - + public void finishPlainToken() { if (builder.length() > 0) @@ -199,7 +207,8 @@ public class Template String variableName = builder.toString(); if (variableName.length() == 0) { - throw new IllegalArgumentException("Nameless placeholder " + createPlaceholder("") + " found."); + throw new IllegalArgumentException("Nameless placeholder " + createPlaceholder("") + + " found."); } VariableToken token = variableTokens.get(variableName); if (token == null) @@ -213,18 +222,19 @@ public class Template } private final Map<String, VariableToken> variableTokens; + private final List<IToken> tokens; - + /** * Creates a new instance for the specified template. - * + * * @throws IllegalArgumentException if some error occurred during parsing. */ public Template(String template) { this(new LinkedHashMap<String, VariableToken>(), new ArrayList<IToken>()); assert template != null : "Unspecified template."; - + TokenBuilder tokenBuilder = new TokenBuilder(variableTokens, tokens); State state = State.PLAIN; final int n = template.length(); @@ -238,13 +248,13 @@ public class Template } tokenBuilder.finishPlainToken(); } - + private Template(Map<String, VariableToken> variableTokens, List<IToken> tokens) { this.variableTokens = variableTokens; this.tokens = tokens; } - + /** * Creates a copy of this template with no variable bindings. */ @@ -269,7 +279,6 @@ public class Template } return new Template(map, list); } - /** * Binds the specified value to the specified placeholder name. @@ -281,7 +290,7 @@ public class Template boolean successful = attemptToBind(placeholderName, value); if (successful == false) { - throw new IllegalArgumentException("Unknown variable '" + placeholderName + "'."); + throw new IllegalArgumentException("Unknown variable '" + placeholderName + "'."); } } @@ -294,7 +303,7 @@ public class Template { assert placeholderName != null : "Unspecified placeholder name."; assert value != null : "Unspecified value for '" + placeholderName + "'"; - + VariableToken variableToken = variableTokens.get(placeholderName); if (variableToken == null) { @@ -303,7 +312,7 @@ public class Template variableToken.bind(value); return true; } - + /** * Creates the text by using all placeholder bindings. * @@ -313,12 +322,12 @@ public class Template { return createText(true); } - + /** * Creates the text by using placeholder bindings. * - * @param complete If <code>true</code> an {@link IllegalStateException} will be thrown if not all - * bindings are set. + * @param complete If <code>true</code> an {@link IllegalStateException} will be thrown if not all bindings are + * set. */ public String createText(boolean complete) { diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/TimerHelper.java b/common/source/java/ch/systemsx/cisd/common/utilities/TimerHelper.java index e671cd4f0d6..606e1a9fecf 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/TimerHelper.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/TimerHelper.java @@ -20,14 +20,14 @@ import java.util.Timer; /** * Helper methods for timer operations. - * + * * @author Bernd Rinn */ public class TimerHelper { /** - * Returns an {@link ITerminable} for the <var>timer</var>. + * Returns an {@link ITerminable} for the <var>timer</var>. */ public static ITerminable asTerminable(final Timer timer) { diff --git a/common/source/java/ch/systemsx/cisd/common/utilities/TriggeringTimerTask.java b/common/source/java/ch/systemsx/cisd/common/utilities/TriggeringTimerTask.java index 459f69952bc..9e4a9644e39 100644 --- a/common/source/java/ch/systemsx/cisd/common/utilities/TriggeringTimerTask.java +++ b/common/source/java/ch/systemsx/cisd/common/utilities/TriggeringTimerTask.java @@ -32,9 +32,11 @@ import ch.systemsx.cisd.common.logging.LogFactory; public class TriggeringTimerTask extends TimerTask { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, TriggeringTimerTask.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, TriggeringTimerTask.class); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, TriggeringTimerTask.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, TriggeringTimerTask.class); private final ITriggerable triggerable; @@ -62,7 +64,8 @@ public class TriggeringTimerTask extends TimerTask * action available. * @param monitor The monitor to synchronize on. */ - public TriggeringTimerTask(File triggerFile, ITriggerable triggerable, SynchronizationMonitor monitor) + public TriggeringTimerTask(File triggerFile, ITriggerable triggerable, + SynchronizationMonitor monitor) { assert triggerFile != null; assert triggerable != null; @@ -79,7 +82,7 @@ public class TriggeringTimerTask extends TimerTask @Override public synchronized void run() { - synchronized(monitor) + synchronized (monitor) { try { @@ -101,7 +104,8 @@ public class TriggeringTimerTask extends TimerTask { if (operationLog.isInfoEnabled()) { - operationLog.info(String.format("File '%s' found - triggering.", triggerFile.getAbsolutePath())); + operationLog.info(String.format("File '%s' found - triggering.", triggerFile + .getAbsolutePath())); } triggerable.trigger(); } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionIOTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionIOTest.java index 0dbbad3203d..1cd14b997b8 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionIOTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionIOTest.java @@ -47,7 +47,8 @@ import ch.systemsx.cisd.common.logging.LogInitializer; public class CollectionIOTest { - private static final File workingDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File workingDirectory = + new File("targets" + File.separator + "unit-test-wd"); @BeforeSuite public void init() @@ -129,13 +130,14 @@ public class CollectionIOTest assert ps.checkError() == false; final String resultingString = new String(os.toByteArray()); final String lineSeparator = System.getProperty("line.separator"); - assert resultingString.equals(String.format("One%1$sTwo%1$sThree%1$sStill open%1$s", lineSeparator)); + assert resultingString.equals(String.format("One%1$sTwo%1$sThree%1$sStill open%1$s", + lineSeparator)); assert CollectionIO.writeIterable(ps, Arrays.asList("yellow")); assert ps.checkError() == false; ps.println("Still open"); final String resultingString2 = new String(os.toByteArray()); - assert resultingString2.equals(String.format("One%1$sTwo%1$sThree%1$sStill open%1$syellow%1$sStill open%1$s", - lineSeparator)); + assert resultingString2.equals(String.format( + "One%1$sTwo%1$sThree%1$sStill open%1$syellow%1$sStill open%1$s", lineSeparator)); } @Test diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionUtilsTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionUtilsTest.java index c99f4634f1d..2507007ae71 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionUtilsTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/collections/CollectionUtilsTest.java @@ -61,7 +61,8 @@ public final class CollectionUtilsTest final String[] s = StringUtilities.getStrings(5); final CollectionStyle collectionStyle = CollectionStyle.DEFAULT_COLLECTION_STYLE; String string = - collectionStyle.getCollectionStart() + StringUtils.join(s, collectionStyle.getCollectionSeparator()) + collectionStyle.getCollectionStart() + + StringUtils.join(s, collectionStyle.getCollectionSeparator()) + collectionStyle.getCollectionEnd(); assertEquals(string, CollectionUtils.abbreviate(s, -1, false)); assertEquals(string, CollectionUtils.abbreviate(s, -10, false)); @@ -83,7 +84,8 @@ public final class CollectionUtilsTest } try { - CollectionUtils.abbreviate(objects, 0, false, ToStringDefaultConverter.getInstance(), null); + CollectionUtils.abbreviate(objects, 0, false, ToStringDefaultConverter.getInstance(), + null); fail("Given CollectionStyle can not be null."); } catch (AssertionError e) { diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/collections/FilteredListTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/collections/FilteredListTest.java index f5359f63553..0e4b1f72fc2 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/collections/FilteredListTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/collections/FilteredListTest.java @@ -134,7 +134,7 @@ public final class FilteredListTest assertEquals(5, list.size()); assertEquals("renew", list.get(4)); } - + @Test public final void testSubList() { diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKeyTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKeyTest.java index 25bd8aa9df0..0a6f190d19b 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKeyTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapNonUniqueKeyTest.java @@ -52,7 +52,8 @@ public class TableMapNonUniqueKeyTest public void testIterationUniqueKey() { final TableMapNonUniqueKey<Integer, String> tableMap = - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0"), integerExtractor); + new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0"), + integerExtractor); Iterator<String> it = tableMap.iterator(); assertEquals("1", it.next()); assertEquals("7", it.next()); @@ -63,7 +64,8 @@ public class TableMapNonUniqueKeyTest @Test(expectedExceptions = TableMapNonUniqueKey.UniqueValueViolationException.class) public void testIterationDuplicateValuesStrategyError() { - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0", "0", "1"), integerExtractor); + new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0", "0", "1"), + integerExtractor); } @Test @@ -72,14 +74,15 @@ public class TableMapNonUniqueKeyTest final String null1 = new String(Integer.toString(0)); final String null2 = new String(Integer.toString(0)); final TableMapNonUniqueKey<Integer, String> tableMap = - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", null1, null2, "1"), integerExtractor, + new TableMapNonUniqueKey<Integer, String>(Arrays + .asList("1", "7", null1, null2, "1"), integerExtractor, TableMapNonUniqueKey.UniqueValueViolationStrategy.KEEP_LAST); Iterator<String> it = tableMap.iterator(); assertEquals("1", it.next()); assertEquals("7", it.next()); final String null3 = it.next(); - System.out.println(System.identityHashCode(null1) + ":" + System.identityHashCode(null2) + ":" - + System.identityHashCode(null3)); + System.out.println(System.identityHashCode(null1) + ":" + System.identityHashCode(null2) + + ":" + System.identityHashCode(null3)); assertEquals(System.identityHashCode(null2), System.identityHashCode(null3)); assertFalse(it.hasNext()); } @@ -90,14 +93,15 @@ public class TableMapNonUniqueKeyTest final String null1 = new String(Integer.toString(0)); final String null2 = new String(Integer.toString(0)); final TableMapNonUniqueKey<Integer, String> tableMap = - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", null1, null2, "1"), integerExtractor, + new TableMapNonUniqueKey<Integer, String>(Arrays + .asList("1", "7", null1, null2, "1"), integerExtractor, TableMapNonUniqueKey.UniqueValueViolationStrategy.KEEP_FIRST); Iterator<String> it = tableMap.iterator(); assertEquals("1", it.next()); assertEquals("7", it.next()); final String null3 = it.next(); - System.out.println(System.identityHashCode(null1) + ":" + System.identityHashCode(null2) + ":" - + System.identityHashCode(null3)); + System.out.println(System.identityHashCode(null1) + ":" + System.identityHashCode(null2) + + ":" + System.identityHashCode(null3)); assertEquals(System.identityHashCode(null1), System.identityHashCode(null3)); assertFalse(it.hasNext()); } @@ -106,7 +110,8 @@ public class TableMapNonUniqueKeyTest public void testIterationDuplicateKey() { final TableMapNonUniqueKey<Integer, String> tableMap = - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0", "x:0", "x:1"), integerExtractor); + new TableMapNonUniqueKey<Integer, String>(Arrays + .asList("1", "7", "0", "x:0", "x:1"), integerExtractor); Iterator<String> it = tableMap.iterator(); assertEquals("1", it.next()); assertEquals("x:1", it.next()); @@ -120,7 +125,8 @@ public class TableMapNonUniqueKeyTest public void testTryGet() { final TableMapNonUniqueKey<Integer, String> tableMap = - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0"), integerExtractor); + new TableMapNonUniqueKey<Integer, String>(Arrays.asList("1", "7", "0"), + integerExtractor); assertNull(tableMap.tryGet(10)); assertEquals(Collections.singleton("0"), tableMap.tryGet(0)); assertEquals(Collections.singleton("1"), tableMap.tryGet(1)); @@ -131,12 +137,13 @@ public class TableMapNonUniqueKeyTest public void testTryGetNonUnique() { final TableMapNonUniqueKey<Integer, String> tableMap = - new TableMapNonUniqueKey<Integer, String>(Arrays.asList("a:42", "7", "b:42", "0", "b:7", "c:42"), - integerExtractor); + new TableMapNonUniqueKey<Integer, String>(Arrays.asList("a:42", "7", "b:42", "0", + "b:7", "c:42"), integerExtractor); assertNull(tableMap.tryGet(10)); assertEquals(Collections.singleton("0"), tableMap.tryGet(0)); assertEquals(new HashSet<String>(Arrays.asList("7", "b:7")), tableMap.tryGet(7)); - assertEquals(new HashSet<String>(Arrays.asList("a:42", "b:42", "c:42")), tableMap.tryGet(42)); + assertEquals(new HashSet<String>(Arrays.asList("a:42", "b:42", "c:42")), tableMap + .tryGet(42)); } } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapTest.java index 28a2f3e10ae..905ca1d7302 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/collections/TableMapTest.java @@ -86,8 +86,8 @@ public class TableMapTest public void testUniqueKeyViolationKeepFirst() { final TableMap<Integer, String> tableMap = - new TableMap<Integer, String>(Arrays.asList("a:1", "7", "0", "b:1"), integerExtractor, - UniqueKeyViolationStrategy.KEEP_FIRST); + new TableMap<Integer, String>(Arrays.asList("a:1", "7", "0", "b:1"), + integerExtractor, UniqueKeyViolationStrategy.KEEP_FIRST); assertNull(tableMap.tryGet(10)); assertEquals("0", tableMap.tryGet(0)); assertEquals("a:1", tableMap.tryGet(1)); @@ -98,8 +98,8 @@ public class TableMapTest public void testUniqueKeyViolationKeepLast() { final TableMap<Integer, String> tableMap = - new TableMap<Integer, String>(Arrays.asList("a:1", "7", "0", "b:1"), integerExtractor, - UniqueKeyViolationStrategy.KEEP_LAST); + new TableMap<Integer, String>(Arrays.asList("a:1", "7", "0", "b:1"), + integerExtractor, UniqueKeyViolationStrategy.KEEP_LAST); assertNull(tableMap.tryGet(10)); assertEquals("0", tableMap.tryGet(0)); assertEquals("b:1", tableMap.tryGet(1)); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/collections/ValidatorUtilsTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/collections/ValidatorUtilsTest.java index b694e275072..37778d646b7 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/collections/ValidatorUtilsTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/collections/ValidatorUtilsTest.java @@ -41,14 +41,14 @@ public final class ValidatorUtilsTest { // Nothing to do here. } - + s = "hello"; String regEx = ValidatorUtils.convertToRegEx(s); assertEquals("hello", regEx); Pattern pattern = Pattern.compile(regEx); assertEquals(false, pattern.matcher("heelo").matches()); assertEquals(true, pattern.matcher("hello").matches()); - + s = "he?lo"; regEx = ValidatorUtils.convertToRegEx(s); assertEquals("he.lo", regEx); @@ -56,7 +56,7 @@ public final class ValidatorUtilsTest assertEquals(true, pattern.matcher("heelo").matches()); assertEquals(false, pattern.matcher("helllo").matches()); assertEquals(false, pattern.matcher("xhello").matches()); - + s = "he?l"; regEx = ValidatorUtils.convertToRegEx(s); assertEquals("he.l", regEx); @@ -65,7 +65,7 @@ public final class ValidatorUtilsTest assertEquals(true, pattern.matcher("heul").matches()); assertEquals(false, pattern.matcher("hello").matches()); assertEquals(false, pattern.matcher("helloo").matches()); - + s = "he*o"; regEx = ValidatorUtils.convertToRegEx(s); assertEquals("he.*o", regEx); @@ -74,11 +74,11 @@ public final class ValidatorUtilsTest assertEquals(true, pattern.matcher("helllllllllllllllo").matches()); assertEquals(true, pattern.matcher("helloo").matches()); assertEquals(false, pattern.matcher("chelloo").matches()); - + s = "h?l*o"; regEx = ValidatorUtils.convertToRegEx(s); assertEquals("h.l.*o", regEx); - + s = "h\\*ll*o"; regEx = ValidatorUtils.convertToRegEx(s); assertEquals("h\\*ll.*o", regEx); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/compression/file/CompressionWorkerTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/compression/file/CompressionWorkerTest.java index 87e70d3ccab..39ad51041ae 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/compression/file/CompressionWorkerTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/compression/file/CompressionWorkerTest.java @@ -309,8 +309,8 @@ public class CompressionWorkerTest final FailureRecord record = failed.iterator().next(); assertEquals(faultyFile, record.getFailedFile().getName()); assertEquals(StatusFlag.FATAL_ERROR, record.getFailureStatus().getFlag()); - assertEquals("Exceptional condition: " + FakedException.class.getSimpleName(), record.getFailureStatus() - .getMessage()); + assertEquals("Exceptional condition: " + FakedException.class.getSimpleName(), record + .getFailureStatus().getMessage()); assertEquals(ex, record.tryGetThrowable()); assertTrue(logRecorder.getLogContent().indexOf( String.format(CompressionWorker.EXCEPTION_COMPRESSING_MSG_TEMPLATE, faultyFile)) >= 0); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilitiesTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilitiesTest.java index b630996e30b..bfa5c0bcce4 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilitiesTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/concurrent/ConcurrencyUtilitiesTest.java @@ -33,14 +33,15 @@ import ch.systemsx.cisd.common.exceptions.CheckedExceptionTunnel; import ch.systemsx.cisd.common.logging.LogInitializer; /** - * Test cases for {@link ConcurrencyUtilities}. - * + * Test cases for {@link ConcurrencyUtilities}. + * * @author Bernd Rinn */ public class ConcurrencyUtilitiesTest { private final static String name = "This is the pool name"; + private ThreadPoolExecutor eservice; @BeforeClass @@ -49,19 +50,19 @@ public class ConcurrencyUtilitiesTest LogInitializer.init(); eservice = (ThreadPoolExecutor) ConcurrencyUtilities.newNamedPool(name, 1, 2); } - + @Test public void testNewNamedPool() throws Throwable { assertEquals(1, eservice.getCorePoolSize()); assertEquals(2, eservice.getMaximumPoolSize()); final Future<?> future = eservice.submit(new Runnable() - { - public void run() { - assertEquals(name + " 1", Thread.currentThread().getName()); - } - }); + public void run() + { + assertEquals(name + " 1", Thread.currentThread().getName()); + } + }); try { future.get(200L, TimeUnit.MILLISECONDS); @@ -70,25 +71,24 @@ public class ConcurrencyUtilitiesTest throw ex.getCause(); } } - - + @Test public void testTryGetFutureTimeout() { final Future<String> future = eservice.submit(new Callable<String>() + { + public String call() throws Exception { - public String call() throws Exception + try + { + Thread.sleep(200L); + } catch (InterruptedException ex) { - try - { - Thread.sleep(200L); - } catch (InterruptedException ex) - { - throw new CheckedExceptionTunnel(ex); - } - return null; + throw new CheckedExceptionTunnel(ex); } - }); + return null; + } + }); final String shouldBeNull = ConcurrencyUtilities.tryGetResult(future, 20L); assertNull(shouldBeNull); assertTrue(future.isDone()); @@ -99,27 +99,28 @@ public class ConcurrencyUtilitiesTest { final Thread thread = Thread.currentThread(); final Future<String> future = eservice.submit(new Callable<String>() + { + public String call() throws Exception { - public String call() throws Exception + try + { + Thread.sleep(200L); + } catch (InterruptedException ex) { - try - { - Thread.sleep(200L); - } catch (InterruptedException ex) - { - throw new CheckedExceptionTunnel(ex); - } - return null; + throw new CheckedExceptionTunnel(ex); } - }); + return null; + } + }); final Timer t = new Timer(); - t.schedule(new TimerTask() { - @Override - public void run() + t.schedule(new TimerTask() { - thread.interrupt(); - } - }, 20L); + @Override + public void run() + { + thread.interrupt(); + } + }, 20L); final String shouldBeNull = ConcurrencyUtilities.tryGetResult(future, 200L); t.cancel(); assertNull(shouldBeNull); @@ -131,17 +132,17 @@ public class ConcurrencyUtilitiesTest { private static final long serialVersionUID = 1L; } - + @Test public void testTryGetFutureException() { final Future<String> future = eservice.submit(new Callable<String>() + { + public String call() throws Exception { - public String call() throws Exception - { - throw new TaggedException(); - } - }); + throw new TaggedException(); + } + }); try { ConcurrencyUtilities.tryGetResult(future, 100L); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/db/DBRestrictionParserTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/db/DBRestrictionParserTest.java index 721b5b75ce0..9330c22c360 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/db/DBRestrictionParserTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/db/DBRestrictionParserTest.java @@ -51,15 +51,17 @@ public class DBRestrictionParserTest { LogInitializer.init(); sqlScript = - FileUtilities.loadToString(new File( - "../common/sourceTest/java/ch/systemsx/cisd/common/db/DBRestrictionsTest.sql")); + FileUtilities + .loadToString(new File( + "../common/sourceTest/java/ch/systemsx/cisd/common/db/DBRestrictionsTest.sql")); assert sqlScript != null; } @Test public void testNormalize() { - final List<String> normalizedList = DBRestrictionParser.normalize(" a 1 ;; B\t2;\n\nC; \n--D\n E "); + final List<String> normalizedList = + DBRestrictionParser.normalize(" a 1 ;; B\t2;\n\nC; \n--D\n E "); assertEquals(Arrays.asList("a 1", "b 2", "c", "e"), normalizedList); } @@ -68,10 +70,12 @@ public class DBRestrictionParserTest { String invalidDomainStatement = "create domain bla for varchar(0)"; final List<String> domainScript = - Arrays.asList("create table sometable", "create domain user_id as varchar(15)", invalidDomainStatement, - "create domain code as varchar(8)", "create domain description_80 as varchar(81)"); + Arrays.asList("create table sometable", "create domain user_id as varchar(15)", + invalidDomainStatement, "create domain code as varchar(8)", + "create domain description_80 as varchar(81)"); final LogMonitoringAppender appender = - LogMonitoringAppender.addAppender(LogCategory.OPERATION, "line \"" + invalidDomainStatement + LogMonitoringAppender.addAppender(LogCategory.OPERATION, "line \"" + + invalidDomainStatement + "\" starts like a domain definition, but key word 'AS' is missing."); try { @@ -91,9 +95,11 @@ public class DBRestrictionParserTest @Test public void testDefaultKeywordInDomain() { - final List<String> domainScript = Arrays.asList("create domain vc22 as varchar(22) default 'nothing special'"); + final List<String> domainScript = + Arrays.asList("create domain vc22 as varchar(22) default 'nothing special'"); - final LogMonitoringAppender appender = LogMonitoringAppender.addAppender(LogCategory.OPERATION, "ill-formed"); + final LogMonitoringAppender appender = + LogMonitoringAppender.addAppender(LogCategory.OPERATION, "ill-formed"); try { final Map<String, Integer> domains = DBRestrictionParser.parseDomains(domainScript); @@ -111,7 +117,8 @@ public class DBRestrictionParserTest { final List<String> domainScript = Arrays.asList("create domain dp as double precision"); - final LogMonitoringAppender appender = LogMonitoringAppender.addAppender(LogCategory.OPERATION, "ill-formed"); + final LogMonitoringAppender appender = + LogMonitoringAppender.addAppender(LogCategory.OPERATION, "ill-formed"); try { final Map<String, Integer> domains = DBRestrictionParser.parseDomains(domainScript); @@ -126,9 +133,11 @@ public class DBRestrictionParserTest @Test public void testDoublePrecisionAndDefaultInDomain() { - final List<String> domainScript = Arrays.asList("create domain dp as double precision default 3.14159"); + final List<String> domainScript = + Arrays.asList("create domain dp as double precision default 3.14159"); - final LogMonitoringAppender appender = LogMonitoringAppender.addAppender(LogCategory.OPERATION, "ill-formed"); + final LogMonitoringAppender appender = + LogMonitoringAppender.addAppender(LogCategory.OPERATION, "ill-formed"); try { final Map<String, Integer> domains = DBRestrictionParser.parseDomains(domainScript); @@ -163,14 +172,17 @@ public class DBRestrictionParserTest public void testInvalidTable() { final DBRestrictionParser parser = new DBRestrictionParser(""); - assertEquals(Integer.MAX_VALUE, parser.getTableRestrictions("doesnotexit").getLength("doesnotexist")); + assertEquals(Integer.MAX_VALUE, parser.getTableRestrictions("doesnotexit").getLength( + "doesnotexist")); } @Test(expectedExceptions = AssertionError.class) public void testInvalidColumn() { - final DBRestrictionParser parser = new DBRestrictionParser("create table tab (a integer, b varchar(1))"); - assertEquals(Integer.MAX_VALUE, parser.getTableRestrictions("tab").getLength("doesnotexist")); + final DBRestrictionParser parser = + new DBRestrictionParser("create table tab (a integer, b varchar(1))"); + assertEquals(Integer.MAX_VALUE, parser.getTableRestrictions("tab") + .getLength("doesnotexist")); } @Test @@ -178,10 +190,10 @@ public class DBRestrictionParserTest { final DBRestrictionParser parser = new DBRestrictionParser(sqlScript); - assertEquals(new HashSet<String>(Arrays.asList("PERS", "ORGA")), parser.getTableRestrictions("contacts") - .tryGetCheckedConstaint("cnta_type")); - assertEquals(new HashSet<String>(Arrays.asList("STOB", "MATE")), parser.getTableRestrictions("materials") - .tryGetCheckedConstaint("mate_sub_type")); + assertEquals(new HashSet<String>(Arrays.asList("PERS", "ORGA")), parser + .getTableRestrictions("contacts").tryGetCheckedConstaint("cnta_type")); + assertEquals(new HashSet<String>(Arrays.asList("STOB", "MATE")), parser + .getTableRestrictions("materials").tryGetCheckedConstaint("mate_sub_type")); } } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/db/SQLCommandTokenizerTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/db/SQLCommandTokenizerTest.java index a771314becd..04e63defd5d 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/db/SQLCommandTokenizerTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/db/SQLCommandTokenizerTest.java @@ -69,7 +69,8 @@ public class SQLCommandTokenizerTest @Test public void testWhitespaces() { - final SQLCommandTokenizer cmdTokenizer = new SQLCommandTokenizer(" A ; \n b B;\t c\tC\n "); + final SQLCommandTokenizer cmdTokenizer = + new SQLCommandTokenizer(" A ; \n b B;\t c\tC\n "); assertEquals("a", cmdTokenizer.getNextCommand()); assertEquals("b b", cmdTokenizer.getNextCommand()); assertEquals("c c", cmdTokenizer.getNextCommand()); @@ -101,7 +102,8 @@ public class SQLCommandTokenizerTest @Test public void testConstants() { - final SQLCommandTokenizer cmdTokenizer = new SQLCommandTokenizer("A 'A \\'B\tc';\nb;\ncC;"); + final SQLCommandTokenizer cmdTokenizer = + new SQLCommandTokenizer("A 'A \\'B\tc';\nb;\ncC;"); assertEquals("a 'A \\'B\tc'", cmdTokenizer.getNextCommand()); assertEquals("b", cmdTokenizer.getNextCommand()); assertEquals("cc", cmdTokenizer.getNextCommand()); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/db/SqlUnitTestRunnerTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/db/SqlUnitTestRunnerTest.java index 27468c27213..ea68f6e4904 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/db/SqlUnitTestRunnerTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/db/SqlUnitTestRunnerTest.java @@ -41,19 +41,20 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; import ch.systemsx.cisd.common.utilities.OSUtilities; /** - * - * * @author Franz-Josef Elmer */ public class SqlUnitTestRunnerTest { private static final File TEST_SCRIPTS_FOLDER = new File("temporary_test_scripts_folder"); - + private Mockery context; + private ISqlScriptExecutor executor; + private StringWriter monitor; + private SqlUnitTestRunner testRunner; - + @BeforeMethod public void setup() { @@ -63,7 +64,7 @@ public class SqlUnitTestRunnerTest monitor = new StringWriter(); testRunner = new SqlUnitTestRunner(executor, new PrintWriter(monitor)); } - + @AfterMethod public void teardown() { @@ -72,57 +73,58 @@ public class SqlUnitTestRunnerTest // Otherwise one do not known which test failed. context.assertIsSatisfied(); } - + @Test public void testNullFolder() { testRunner.run(null); assertEquals("", monitor.toString()); - + context.assertIsSatisfied(); } - + @Test public void testNotExistingFolder() { testRunner.run(new File("blabla")); assertEquals("", monitor.toString()); - + context.assertIsSatisfied(); } - + @Test public void testEmptyFolder() { testRunner.run(TEST_SCRIPTS_FOLDER); assertEquals("", monitor.toString()); - + context.assertIsSatisfied(); } - + @Test public void testNonEmptyFolderButNoTestCases() throws IOException { assert new File(TEST_SCRIPTS_FOLDER, "some file").createNewFile(); assert new File(TEST_SCRIPTS_FOLDER, ".folder").mkdir(); - + testRunner.run(TEST_SCRIPTS_FOLDER); assertEquals("", monitor.toString()); - + context.assertIsSatisfied(); } - + @Test public void testEmptyTestCase() { assert new File(TEST_SCRIPTS_FOLDER, "my test case").mkdir(); - + testRunner.run(TEST_SCRIPTS_FOLDER); - assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR, monitor.toString()); - + assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR, monitor + .toString()); + context.assertIsSatisfied(); } - + @Test public void testNonEmptyTestCaseButNoScripts() throws IOException { @@ -130,35 +132,38 @@ public class SqlUnitTestRunnerTest assert testCaseFolder.mkdir(); assert new File(testCaseFolder, "blabla.sql").createNewFile(); assert new File(testCaseFolder, "folder").mkdir(); - + testRunner.run(TEST_SCRIPTS_FOLDER); - assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR, monitor.toString()); - + assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR, monitor + .toString()); + context.assertIsSatisfied(); } - + @Test - public void testTestCaseWithNoTestsButBuildupScript() throws IOException + public void testTestCaseWithNoTestsButBuildupScript() throws IOException { File testCaseFolder = new File(TEST_SCRIPTS_FOLDER, "my test case"); assert testCaseFolder.mkdir(); createScriptPrepareExecutor(new File(testCaseFolder, "buildup.sql"), "-- build up\n", null); - + testRunner.run(TEST_SCRIPTS_FOLDER); assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR - + " execute script buildup.sql" + OSUtilities.LINE_SEPARATOR, monitor.toString()); - + + " execute script buildup.sql" + OSUtilities.LINE_SEPARATOR, monitor + .toString()); + context.assertIsSatisfied(); } @Test - public void testTestCaseWithFailingBuildupScript() throws IOException + public void testTestCaseWithFailingBuildupScript() throws IOException { File testCaseFolder = new File(TEST_SCRIPTS_FOLDER, "my test case"); assert testCaseFolder.mkdir(); RuntimeException runtimeException = new RuntimeException("42"); - createScriptPrepareExecutor(new File(testCaseFolder, "buildup.sql"), "-- build up\n", runtimeException); - + createScriptPrepareExecutor(new File(testCaseFolder, "buildup.sql"), "-- build up\n", + runtimeException); + try { testRunner.run(TEST_SCRIPTS_FOLDER); @@ -167,27 +172,28 @@ public class SqlUnitTestRunnerTest { final String message = StringUtils.split(e.getMessage(), "\n")[0]; assertEquals("Script 'buildup.sql' of test case 'my test case' failed because of " - + runtimeException, message.trim()); + + runtimeException, message.trim()); } assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR - + " execute script buildup.sql" + OSUtilities.LINE_SEPARATOR - + " script failed: skip test scripts and teardown script." + OSUtilities.LINE_SEPARATOR, - monitor.toString()); - + + " execute script buildup.sql" + OSUtilities.LINE_SEPARATOR + + " script failed: skip test scripts and teardown script." + + OSUtilities.LINE_SEPARATOR, monitor.toString()); + context.assertIsSatisfied(); } - + @Test - public void testOrderOfExecutingTestScripts() throws IOException + public void testOrderOfExecutingTestScripts() throws IOException { File testCaseFolder = new File(TEST_SCRIPTS_FOLDER, "my test case"); assert testCaseFolder.mkdir(); RuntimeException runtimeException = new RuntimeException("42"); - createScriptPrepareExecutor(new File(testCaseFolder, "9=b.sql"), "Select 9\n", runtimeException); + createScriptPrepareExecutor(new File(testCaseFolder, "9=b.sql"), "Select 9\n", + runtimeException); FileUtils.writeStringToFile(new File(testCaseFolder, "abc=abc.sql"), "Select abc\n"); createScriptPrepareExecutor(new File(testCaseFolder, "10=c.sql"), "Select 10\n", null); createScriptPrepareExecutor(new File(testCaseFolder, "1=a.sql"), "Select 1\n", null); - + try { testRunner.run(TEST_SCRIPTS_FOLDER); @@ -197,41 +203,41 @@ public class SqlUnitTestRunnerTest // Strip away stack trace final String message = StringUtils.split(e.getMessage(), "\n")[0]; assertEquals("Script '9=b.sql' of test case 'my test case' failed because of " - + runtimeException, message.trim()); + + runtimeException, message.trim()); } assertEquals("====== Test case: my test case ======" + OSUtilities.LINE_SEPARATOR - + " execute script 1=a.sql" + OSUtilities.LINE_SEPARATOR - + " execute script 9=b.sql" + OSUtilities.LINE_SEPARATOR - + " execute script 10=c.sql" + OSUtilities.LINE_SEPARATOR, - monitor.toString()); - + + " execute script 1=a.sql" + OSUtilities.LINE_SEPARATOR + + " execute script 9=b.sql" + OSUtilities.LINE_SEPARATOR + + " execute script 10=c.sql" + OSUtilities.LINE_SEPARATOR, monitor.toString()); + context.assertIsSatisfied(); } - + @Test - public void testOrderOfExecutingTestCases() throws IOException + public void testOrderOfExecutingTestCases() throws IOException { assert new File(TEST_SCRIPTS_FOLDER, "TC002").mkdir(); File testCaseFolder1 = new File(TEST_SCRIPTS_FOLDER, "TC001"); assert testCaseFolder1.mkdir(); - createScriptPrepareExecutor(new File(testCaseFolder1, "buildup.sql"), "create table\n", null); + createScriptPrepareExecutor(new File(testCaseFolder1, "buildup.sql"), "create table\n", + null); createScriptPrepareExecutor(new File(testCaseFolder1, "1=a.sql"), "Select 1\n", null); createScriptPrepareExecutor(new File(testCaseFolder1, "2=b.sql"), "Select 2\n", null); createScriptPrepareExecutor(new File(testCaseFolder1, "teardown.sql"), "drop table\n", null); - + testRunner.run(TEST_SCRIPTS_FOLDER); assertEquals("====== Test case: TC001 ======" + OSUtilities.LINE_SEPARATOR - + " execute script buildup.sql" + OSUtilities.LINE_SEPARATOR - + " execute script 1=a.sql" + OSUtilities.LINE_SEPARATOR - + " execute script 2=b.sql" + OSUtilities.LINE_SEPARATOR - + " execute script teardown.sql" + OSUtilities.LINE_SEPARATOR - + "====== Test case: TC002 ======" + OSUtilities.LINE_SEPARATOR, - monitor.toString()); - - context.assertIsSatisfied(); + + " execute script buildup.sql" + OSUtilities.LINE_SEPARATOR + + " execute script 1=a.sql" + OSUtilities.LINE_SEPARATOR + + " execute script 2=b.sql" + OSUtilities.LINE_SEPARATOR + + " execute script teardown.sql" + OSUtilities.LINE_SEPARATOR + + "====== Test case: TC002 ======" + OSUtilities.LINE_SEPARATOR, monitor.toString()); + + context.assertIsSatisfied(); } - - private void createScriptPrepareExecutor(File scriptFile, String script, Throwable throwable) throws IOException + + private void createScriptPrepareExecutor(File scriptFile, String script, Throwable throwable) + throws IOException { FileUtils.writeStringToFile(scriptFile, script); InvocationExpectationBuilder builder = new InvocationExpectationBuilder(); @@ -240,5 +246,5 @@ public class SqlUnitTestRunnerTest Action action = throwable == null ? new VoidAction() : new ThrowAction(throwable); context.addExpectation(builder.toExpectation(action)); } - + } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/exceptions/UserFailureExceptionTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/exceptions/UserFailureExceptionTest.java index 6c43b4dac71..4584b62c977 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/exceptions/UserFailureExceptionTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/exceptions/UserFailureExceptionTest.java @@ -37,19 +37,25 @@ public final class UserFailureExceptionTest @Test public final void testFromTemplateStringObjectArray() { - UserFailureException exception = UserFailureException.fromTemplate("This is a %s exception to see how it works.", "dummy"); + UserFailureException exception = + UserFailureException.fromTemplate("This is a %s exception to see how it works.", + "dummy"); assertEquals("This is a dummy exception to see how it works.", exception.getMessage()); // With not enough arguments. try { - exception = UserFailureException.fromTemplate("This is a %s exception to see how it works."); + exception = + UserFailureException + .fromTemplate("This is a %s exception to see how it works."); fail("MissingFormatArgumentException must be thrown."); } catch (MissingFormatArgumentException e) { // Does nothing here. } // With more arguments than needed. - exception = UserFailureException.fromTemplate("This is a %s exception to see how it works.", "dummy", "more dummy"); + exception = + UserFailureException.fromTemplate("This is a %s exception to see how it works.", + "dummy", "more dummy"); assertEquals("This is a dummy exception to see how it works.", exception.getMessage()); exception = UserFailureException.fromTemplate("This is an exception to see how it works."); // No format needed. diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/logging/LogMonitoringAppender.java b/common/sourceTest/java/ch/systemsx/cisd/common/logging/LogMonitoringAppender.java index 5e16109a171..1fa2ef8be1f 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/logging/LogMonitoringAppender.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/logging/LogMonitoringAppender.java @@ -35,7 +35,8 @@ import ch.systemsx.cisd.common.logging.LogCategory; public final class LogMonitoringAppender extends AppenderSkeleton { - private static Map<LogMonitoringAppender, String> appenderMap = new HashMap<LogMonitoringAppender, String>(); + private static Map<LogMonitoringAppender, String> appenderMap = + new HashMap<LogMonitoringAppender, String>(); private final StringBuilder eventRecorder = new StringBuilder(); @@ -54,7 +55,8 @@ public final class LogMonitoringAppender extends AppenderSkeleton * * @return The created appender. */ - public static synchronized LogMonitoringAppender addAppender(LogCategory category, String messagePart) + public static synchronized LogMonitoringAppender addAppender(LogCategory category, + String messagePart) { return addAppender(category, Pattern.compile(Pattern.quote(messagePart))); } @@ -112,7 +114,8 @@ public final class LogMonitoringAppender extends AppenderSkeleton { eventRecorder.append("event throwable: ").append(throwableStr).append('\n'); } - if (regex.matcher(event.getMessage().toString()).find() || regex.matcher(getThrowableStr(event)).find()) + if (regex.matcher(event.getMessage().toString()).find() + || regex.matcher(getThrowableStr(event)).find()) { ++logCount; } @@ -144,8 +147,8 @@ public final class LogMonitoringAppender extends AppenderSkeleton public void verifyLogHappendNTimes(int n) { assert logCount == n : String.format( - "Log snippet '%s' should have found %d times, but has been found %d times.", regex, n, - logCount); + "Log snippet '%s' should have found %d times, but has been found %d times.", regex, + n, logCount); } public void reset() diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/mail/MailClientTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/mail/MailClientTest.java index ce87483bc43..929355bb1d8 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/mail/MailClientTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/mail/MailClientTest.java @@ -27,8 +27,6 @@ import ch.systemsx.cisd.common.utilities.AbstractFileSystemTestCase; import ch.systemsx.cisd.common.utilities.FileUtilities; /** - * - * * @author Franz-Josef Elmer */ public class MailClientTest extends AbstractFileSystemTestCase @@ -39,18 +37,19 @@ public class MailClientTest extends AbstractFileSystemTestCase String path = workingDirectory.getPath() + "/emails"; File emailFolder = new File(path); assert emailFolder.exists() == false; - + MailClient mailClient = new MailClient("sender", "file://" + path); mailClient.sendMessage("some message", "Hello world\nHow are you today?", "a@b.c", "d@e.f"); - + assert emailFolder.exists(); assert emailFolder.isDirectory(); File[] files = emailFolder.listFiles(); assertEquals(1, files.length); assertEquals("email", files[0].getName()); - assertEquals("Subj: some message\n" + "From: sender\n" + "To: a@b.c, d@e.f\n" + "Content:\n" - + "Hello world\nHow are you today?\n", FileUtilities.loadToString(files[0])); - + assertEquals("Subj: some message\n" + "From: sender\n" + "To: a@b.c, d@e.f\n" + + "Content:\n" + "Hello world\nHow are you today?\n", FileUtilities + .loadToString(files[0])); + // second mail mailClient.sendMessage("Greetings", "Hello world!"); files = emailFolder.listFiles(); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactoryTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactoryTest.java index f9300089494..c9ca6c087f0 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactoryTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/parser/AbstractParserObjectFactoryTest.java @@ -68,15 +68,17 @@ public final class AbstractParserObjectFactoryTest fail("Following properties '[isnotin]' are not part of 'Bean'."); } catch (final UnmatchedPropertiesException ex) { - assertEquals("Following header columns are not part of 'Bean': isnotin", ex.getMessage()); + assertEquals("Following header columns are not part of 'Bean': isnotin", ex + .getMessage()); } } @Test public final void testMandatoryFields() { - final DefaultAliasPropertyMapper propertyMapper = new DefaultAliasPropertyMapper(new String[] - { "description" }); + final DefaultAliasPropertyMapper propertyMapper = + new DefaultAliasPropertyMapper(new String[] + { "description" }); try { final BeanFactory beanFactory = new BeanFactory(Bean.class, propertyMapper); @@ -86,7 +88,8 @@ public final class AbstractParserObjectFactoryTest fail("Field/Property name 'name' is mandatory."); } catch (final MandatoryPropertyMissingException ex) { - assertEquals(String.format(MandatoryPropertyMissingException.MESSAGE_FORMAT, "name"), ex.getMessage()); + assertEquals(String.format(MandatoryPropertyMissingException.MESSAGE_FORMAT, "name"), + ex.getMessage()); } } @@ -106,8 +109,10 @@ public final class AbstractParserObjectFactoryTest final IAliasPropertyMapper propertyMapper = createPropertyMapper(); final BeanFactory beanFactory = new BeanFactory(Bean.class, propertyMapper); final String[] defaultTokens = createDefaultLineTokens(); - final String[] lineTokens = (String[]) ArrayUtils.remove(defaultTokens, defaultTokens.length - 1); - final String msg = String.format(IndexOutOfBoundsException.MESSAGE_FORMAT, 2, lineTokens.length); + final String[] lineTokens = + (String[]) ArrayUtils.remove(defaultTokens, defaultTokens.length - 1); + final String msg = + String.format(IndexOutOfBoundsException.MESSAGE_FORMAT, 2, lineTokens.length); try { beanFactory.createObject(lineTokens); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/parser/DefaultParserTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/parser/DefaultParserTest.java index 7655ffbca14..a487f15ae8c 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/parser/DefaultParserTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/parser/DefaultParserTest.java @@ -49,7 +49,8 @@ public final class DefaultParserTest public final void testParseWithoutFactoryAndHeader() { final IParser<String[]> parser = createParser(); - final List<String[]> result = parser.parse(createLineIterator(), new HeaderLineFilter(), HEADER_LENGTH); + final List<String[]> result = + parser.parse(createLineIterator(), new HeaderLineFilter(), HEADER_LENGTH); assertEquals(3, result.size()); assertEquals(result.get(0)[0], "firstName"); assertEquals(result.get(1)[1], "Darwin"); @@ -61,7 +62,8 @@ public final class DefaultParserTest public final void testParseWithoutFactoryWithLineFilter() { final IParser<String[]> parser = createParser(); - final List<String[]> result = parser.parse(createLineIterator(), new HeaderLineFilter(3), HEADER_LENGTH); + final List<String[]> result = + parser.parse(createLineIterator(), new HeaderLineFilter(3), HEADER_LENGTH); assertEquals(2, result.size()); assertEquals(result.get(0)[0], "Charles"); assertEquals(result.get(1)[1], "Einstein"); @@ -76,9 +78,10 @@ public final class DefaultParserTest parser.parse(createLineIterator(), new HeaderLineFilter(3), HEADER_LENGTH + 1); } catch (final ColumnSizeMismatchException ex) { - assertEquals("Line <4> has less columns (4) than the header (5):\n " - + "Charles <TAB> Darwin <TAB> Humboldt Ave. 1865 <TAB> 4242 Somewhere <END_OF_LINE>", ex - .getMessage()); + assertEquals( + "Line <4> has less columns (4) than the header (5):\n " + + "Charles <TAB> Darwin <TAB> Humboldt Ave. 1865 <TAB> 4242 Somewhere <END_OF_LINE>", + ex.getMessage()); } } @@ -103,8 +106,9 @@ public final class DefaultParserTest parser.parse(createLineIterator(), new HeaderLineFilter(2), HEADER_LENGTH); } catch (final ParsingException ex) { - assertEquals("Creating an object with following tokens '[firstName, lastName, address, city]' failed.", ex - .getMessage()); + assertEquals( + "Creating an object with following tokens '[firstName, lastName, address, city]' failed.", + ex.getMessage()); assertEquals(3, ex.getLineNumber()); } } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/parser/HeaderLineFilterTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/parser/HeaderLineFilterTest.java index 48960489187..dd5103f7b36 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/parser/HeaderLineFilterTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/parser/HeaderLineFilterTest.java @@ -20,8 +20,8 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** - * Test cases for the {@link HeaderLineFilter} - * + * Test cases for the {@link HeaderLineFilter} + * * @author Bernd Rinn */ public class HeaderLineFilterTest @@ -36,13 +36,18 @@ public class HeaderLineFilterTest assert filter.acceptLine("text", i) : "Line " + i; } } - + @DataProvider(name = "headerNumbers") public Object[][] headerNumbers() { - return new Object[][] { { 0 }, { 1 }, { 2 }, { 3 } }; + return new Object[][] + { + { 0 }, + { 1 }, + { 2 }, + { 3 } }; } - + @Test(dataProvider = "headerNumbers") public void testHeaderLine(int headerLine) { @@ -51,10 +56,12 @@ public class HeaderLineFilterTest { if (headerLine == i) { - assert filter.acceptLine("text", i) == false : "Line " + i + " (header line: " + headerLine + ")"; + assert filter.acceptLine("text", i) == false : "Line " + i + " (header line: " + + headerLine + ")"; } else { - assert filter.acceptLine("text", i) : "Line " + i + " (header line: " + headerLine + ")"; + assert filter.acceptLine("text", i) : "Line " + i + " (header line: " + headerLine + + ")"; } } } @@ -66,33 +73,33 @@ public class HeaderLineFilterTest assert filter.acceptLine("", 0) == false; assert filter.acceptLine("something", 1); } - + @Test public void testSkipEmptyLine() { final HeaderLineFilter filter = new HeaderLineFilter(); assert filter.acceptLine("", 0) == false; } - + @Test public void testSkipBlankLine() { final HeaderLineFilter filter = new HeaderLineFilter(); assert filter.acceptLine(" ", 0) == false; } - + @Test public void testSkipCommentLine() { final HeaderLineFilter filter = new HeaderLineFilter(); assert filter.acceptLine("# Some comment", 0) == false; } - + @Test public void testSkipCommentLineWithLeadingWhiteSpace() { final HeaderLineFilter filter = new HeaderLineFilter(); assert filter.acceptLine("\t# Some comment", 0) == false; } - + } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/parser/ParserUtilitiesTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/parser/ParserUtilitiesTest.java index f2af1aa96ec..845faba0f00 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/parser/ParserUtilitiesTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/parser/ParserUtilitiesTest.java @@ -40,9 +40,11 @@ import ch.systemsx.cisd.common.parser.filter.ExcludeEmptyAndCommentLineFilter; public final class ParserUtilitiesTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "ParserUtilitiesTest"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "ParserUtilitiesTest"); @BeforeClass public final void setUp() @@ -102,7 +104,9 @@ public final class ParserUtilitiesTest { StringUtils.EMPTY, "# comment line", StringUtils.EMPTY, "hello" }; File file = new File(workingDirectory, "test.txt"); FileUtils.writeLines(file, Arrays.asList(lines)); - Line line = ParserUtilities.getFirstAcceptedLine(file, ExcludeEmptyAndCommentLineFilter.INSTANCE); + Line line = + ParserUtilities.getFirstAcceptedLine(file, + ExcludeEmptyAndCommentLineFilter.INSTANCE); assertEquals("hello", line.getText()); assertEquals(3, line.getNumber()); assert file.delete(); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/parser/TabFileLoaderTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/parser/TabFileLoaderTest.java index 0e8cdd13512..01c3a570da4 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/parser/TabFileLoaderTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/parser/TabFileLoaderTest.java @@ -87,8 +87,8 @@ public final class TabFileLoaderTest // IParserObjectFactoryFactory // - public final IParserObjectFactory<ABC> createFactory(final IAliasPropertyMapper propertyMapper) - throws ParserException + public final IParserObjectFactory<ABC> createFactory( + final IAliasPropertyMapper propertyMapper) throws ParserException { return new IParserObjectFactory<ABC>() { @@ -160,7 +160,9 @@ public final class TabFileLoaderTest private void loadAndCheck(String preamble) { TabFileLoader<ABC> loader = new TabFileLoader<ABC>(new ABCFactoryFactory()); - List<ABC> list = loader.load(new StringReader(preamble + "A\tB\tC\n" + "a1\tb1\tc1\n" + "a2\tb2\tc2\n")); + List<ABC> list = + loader.load(new StringReader(preamble + "A\tB\tC\n" + "a1\tb1\tc1\n" + + "a2\tb2\tc2\n")); assertEquals(list.toString(), 2, list.size()); assertEquals("a1b1c1", list.get(0).toString()); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/process/ProcessExecutionHelperTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/process/ProcessExecutionHelperTest.java index d539bf06e0d..30a9de40e0c 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/process/ProcessExecutionHelperTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/process/ProcessExecutionHelperTest.java @@ -50,26 +50,32 @@ public class ProcessExecutionHelperTest private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, ProcessExecutionHelperTest.class); - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "ProcessExecutionHelperTest"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "ProcessExecutionHelperTest"); - private File createExecutable(String name, String... lines) throws IOException, InterruptedException + private File createExecutable(String name, String... lines) throws IOException, + InterruptedException { final File executable = new File(workingDirectory, name); executable.delete(); CollectionIO.writeIterable(executable, Arrays.asList(lines)); - Runtime.getRuntime().exec(String.format("/bin/chmod +x %s", executable.getPath())).waitFor(); + Runtime.getRuntime().exec(String.format("/bin/chmod +x %s", executable.getPath())) + .waitFor(); executable.deleteOnExit(); return executable; } - private File createExecutable(String name, int exitValue) throws IOException, InterruptedException + private File createExecutable(String name, int exitValue) throws IOException, + InterruptedException { return createExecutable(name, "#! /bin/sh", "exit " + exitValue); } - private File createSleepingExecutable(String name, long millisToSleep) throws IOException, InterruptedException + private File createSleepingExecutable(String name, long millisToSleep) throws IOException, + InterruptedException { return createExecutable(name, "#! /bin/sh", "sleep " + (millisToSleep / 1000.0f), "exit 0"); } @@ -96,7 +102,8 @@ public class ProcessExecutionHelperTest { final File dummyExec = createExecutable("dummy.sh", 0); final boolean ok = - ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), operationLog, machineLog); + ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), + operationLog, machineLog); assertTrue(ok); } @@ -106,7 +113,8 @@ public class ProcessExecutionHelperTest { final File dummyExec = createExecutable("dummy.sh", 1); final boolean ok = - ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), operationLog, machineLog); + ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), + operationLog, machineLog); assertFalse(ok); } @@ -116,8 +124,8 @@ public class ProcessExecutionHelperTest { final File dummyExec = createExecutable("dummy.sh", 0); final boolean ok = - ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), WATCHDOG_WAIT_MILLIS, - operationLog, machineLog); + ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), + WATCHDOG_WAIT_MILLIS, operationLog, machineLog); assertTrue(ok); } @@ -127,8 +135,8 @@ public class ProcessExecutionHelperTest { final File dummyExec = createExecutable("dummy.sh", 1); final boolean ok = - ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), WATCHDOG_WAIT_MILLIS, - operationLog, machineLog); + ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), + WATCHDOG_WAIT_MILLIS, operationLog, machineLog); assertFalse(ok); } @@ -138,8 +146,8 @@ public class ProcessExecutionHelperTest { final File dummyExec = createSleepingExecutable("dummy.sh", WATCHDOG_WAIT_MILLIS / 2); final boolean ok = - ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), WATCHDOG_WAIT_MILLIS, - operationLog, machineLog); + ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), + WATCHDOG_WAIT_MILLIS, operationLog, machineLog); assertTrue(ok); } @@ -149,8 +157,8 @@ public class ProcessExecutionHelperTest { final File dummyExec = createSleepingExecutable("dummy.sh", 2 * WATCHDOG_WAIT_MILLIS); final boolean ok = - ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), WATCHDOG_WAIT_MILLIS, - operationLog, machineLog); + ProcessExecutionHelper.runAndLog(Arrays.asList(dummyExec.getAbsolutePath()), + WATCHDOG_WAIT_MILLIS, operationLog, machineLog); assertFalse(ok); } @@ -160,9 +168,10 @@ public class ProcessExecutionHelperTest { final File dummyExec = createSleepingExecutable("dummy.sh", 2 * WATCHDOG_WAIT_MILLIS); final ProcessResult result = - ProcessExecutionHelper.run(Arrays.asList(dummyExec.getAbsolutePath()), WATCHDOG_WAIT_MILLIS, - operationLog, machineLog); - assertTrue(result.hasBlocked() || ProcessExecutionHelper.isProcessTerminated(result.exitValue())); + ProcessExecutionHelper.run(Arrays.asList(dummyExec.getAbsolutePath()), + WATCHDOG_WAIT_MILLIS, operationLog, machineLog); + assertTrue(result.hasBlocked() + || ProcessExecutionHelper.isProcessTerminated(result.exitValue())); } @Test(groups = @@ -174,9 +183,11 @@ public class ProcessExecutionHelperTest final String stderr1 = "This goes to stderr, 1"; final String stderr2 = "This goes to stderr, 2"; final File dummyExec = - createExecutable("dummy.sh", "echo " + stdout1, "echo " + stderr1, "echo " + stdout2, "echo " + stderr2); + createExecutable("dummy.sh", "echo " + stdout1, "echo " + stderr1, "echo " + + stdout2, "echo " + stderr2); final ProcessResult result = - ProcessExecutionHelper.run(Arrays.asList(dummyExec.getAbsolutePath()), operationLog, machineLog); + ProcessExecutionHelper.run(Arrays.asList(dummyExec.getAbsolutePath()), + operationLog, machineLog); final int exitValue = result.exitValue(); assertEquals(0, exitValue); result.log(); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/test/InterfaceForRMICheckerTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/test/InterfaceForRMICheckerTest.java index 4f369039090..d2c8d93d018 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/test/InterfaceForRMICheckerTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/test/InterfaceForRMICheckerTest.java @@ -25,8 +25,6 @@ import java.util.List; import org.testng.annotations.Test; /** - * - * * @author Franz-Josef Elmer */ public class InterfaceForRMICheckerTest @@ -34,32 +32,35 @@ public class InterfaceForRMICheckerTest public static class NonSerializableClass { } - + @Test public void testRMIReadyInterface() { InterfaceForRMIChecker.assertInterfaceForRMI(RMIReadyInterface.class); } - + public interface RMIReadyInterface { public int get(); + public void set(int a); + public Void set2(String s); + public Number get2(); } - + @Test public void testRMIReadyInterfaceWhichRefersToItself() { InterfaceForRMIChecker.assertInterfaceForRMI(RMIReadyInterfaceWhichRefersToItself.class); } - + public interface RMIReadyInterfaceWhichRefersToItself extends Serializable { public void set(RMIReadyInterfaceWhichRefersToItself interfaze); } - + @Test public void testInterfaceWithNonSerializableParameter() { @@ -70,43 +71,48 @@ public class InterfaceForRMICheckerTest { public void set(NonSerializableClass a); } - + @Test public void testInterfaceWithNonSerializableReturnValue() { checkNonRMIReadyInterface(InterfaceWithNonSerializableParameter.class); } - + public interface InterfaceWithNonSerializableReturnValue { public NonSerializableClass get(); } - + @Test public void testInterfaceExtendsNonRMIReadyInterface() { checkNonRMIReadyInterface(InterfaceExtendsNonRMIReadyInterface.class); } - - public interface InterfaceExtendsNonRMIReadyInterface extends InterfaceWithNonSerializableParameter + + public interface InterfaceExtendsNonRMIReadyInterface extends + InterfaceWithNonSerializableParameter { public int get(); } - + @Test public void testSerializablityOfSerializableClass() { InterfaceForRMIChecker.assertSerializable(SerializableClass.class); } - + public static class SerializableClass implements Serializable { private static final long serialVersionUID = 1L; + private static NonSerializableClass non; + private int n; + private transient NonSerializableClass transientNon; + private List<String> list; - + @Override public String toString() { @@ -118,21 +124,27 @@ public class InterfaceForRMICheckerTest return list; } } - + @Test public void testSerializablityOfSerializableClassExtendsNonSerializableClass() { - InterfaceForRMIChecker.assertSerializable(SerializableClassExtendsNonSerializableClass.class); + InterfaceForRMIChecker + .assertSerializable(SerializableClassExtendsNonSerializableClass.class); } - - public static class SerializableClassExtendsNonSerializableClass extends NonSerializableClass implements Serializable + + public static class SerializableClassExtendsNonSerializableClass extends NonSerializableClass + implements Serializable { private static final long serialVersionUID = 1L; + private static NonSerializableClass non; + private int n; + private transient NonSerializableClass transientNon; + private List<String> list; - + @Override public String toString() { @@ -144,22 +156,23 @@ public class InterfaceForRMICheckerTest return list; } } - + @Test public void testSerializablityOfNonSerializableClass() { checkNonSerializableClass(NonSerializableClass.class); } - + @Test public void testSerializablityOfClassWithNonSerializableAttribute() { checkNonSerializableClass(ClassWithNonSerializableAttribute.class); } - + public static class ClassWithNonSerializableAttribute implements Serializable { private static final long serialVersionUID = 1L; + private NonSerializableClass nonSerializable; @Override @@ -168,56 +181,57 @@ public class InterfaceForRMICheckerTest return nonSerializable.toString(); } } - + @Test public void testSerializablityOfClassWithAnArrayOfNonSerializables() { checkNonSerializableClass(ClassWithAnArrayOfNonSerializables.class); } - + public static class ClassWithAnArrayOfNonSerializables implements Serializable { private static final long serialVersionUID = 1L; + private NonSerializableClass[] nonSerializables; - + @Override public String toString() { return nonSerializables.toString(); } } - + @Test public void testSerializablityOfClassWithAListOfNonSerializables() { checkNonSerializableClass(ClassWithAListOfNonSerializables.class); } - + public static class ClassWithAListOfNonSerializables implements Serializable { private static final long serialVersionUID = 1L; + private List<NonSerializableClass> nonSerializables; - + @Override public String toString() { return nonSerializables.toString(); } } - + @Test public void testClassWithExtendingClassWithNonSerializableAttribute() { checkNonSerializableClass(ClassWithExtendingClassWithNonSerializableAttribute.class); } - - public static class ClassWithExtendingClassWithNonSerializableAttribute extends ClassWithNonSerializableAttribute + + public static class ClassWithExtendingClassWithNonSerializableAttribute extends + ClassWithNonSerializableAttribute { private static final long serialVersionUID = 1L; } - - - + private void checkNonRMIReadyInterface(Class<?> interfaze) { boolean failed = false; @@ -253,11 +267,11 @@ public class InterfaceForRMICheckerTest fail("AssertionError expected"); } } - private void checkErrorMessage(AssertionError e) { - assertEquals(NonSerializableClass.class + " does not implements java.io.Serializable", e.getMessage()); + assertEquals(NonSerializableClass.class + " does not implements java.io.Serializable", e + .getMessage()); } - + } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/test/StoringUncaughtExceptionHandler.java b/common/sourceTest/java/ch/systemsx/cisd/common/test/StoringUncaughtExceptionHandler.java index 604cf248f15..2091bfac24f 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/test/StoringUncaughtExceptionHandler.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/test/StoringUncaughtExceptionHandler.java @@ -83,8 +83,8 @@ public final class StoringUncaughtExceptionHandler implements UncaughtExceptionH { if (hasExceptionOccurred()) { - throw new RuntimeException(String.format("An exception occurred in thread %s.", getThreadName()), - getThrowable()); + throw new RuntimeException(String.format("An exception occurred in thread %s.", + getThreadName()), getThrowable()); } } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/BeanUtilsTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/BeanUtilsTest.java index 459f8b32641..402dc6dcf88 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/BeanUtilsTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/BeanUtilsTest.java @@ -48,11 +48,12 @@ public final class BeanUtilsTest @SuppressWarnings("null") @Test - public final void testGetPropertyDescriptors() throws IllegalArgumentException, IllegalAccessException, - InvocationTargetException + public final void testGetPropertyDescriptors() throws IllegalArgumentException, + IllegalAccessException, InvocationTargetException { List<PropertyDescriptor> descriptors = - new ArrayList<PropertyDescriptor>(BeanUtils.getPropertyDescriptors(FooBean.class).values()); + new ArrayList<PropertyDescriptor>(BeanUtils.getPropertyDescriptors(FooBean.class) + .values()); assertEquals(1, descriptors.size()); PropertyDescriptor outerDescriptor = null; // Play with property 'description' @@ -587,7 +588,8 @@ public final class BeanUtilsTest final String[] array = new String[] { "hot", "warm", "cool", "icy" }; aWrapper.setArray(array); - final CollectionWrapper1 colWrapper = BeanUtils.createBean(CollectionWrapper1.class, aWrapper); + final CollectionWrapper1 colWrapper = + BeanUtils.createBean(CollectionWrapper1.class, aWrapper); List<String> list = colWrapper.getArray(); assertNotNull(list); assertEquals(array.length, list.size()); @@ -604,7 +606,8 @@ public final class BeanUtilsTest final List<String> list = new ArrayList<String>(Arrays.asList(new String[] { "hot", "warm", "cool", "icy" })); colWrapper.setArray(list); - final CollectionWrapper1 colWrapper2 = BeanUtils.createBean(CollectionWrapper1.class, colWrapper); + final CollectionWrapper1 colWrapper2 = + BeanUtils.createBean(CollectionWrapper1.class, colWrapper); List<String> list2 = colWrapper2.getArray(); assertNotNull(list2); assertEquals(list.size(), list2.size()); @@ -768,7 +771,8 @@ public final class BeanUtilsTest final Bean1a[] arrayb1 = new Bean1a[] { b1a, b1b }; b1Array.setBeanArray(arrayb1); - final BeanWithBeanCollection2 b2Collection = BeanUtils.createBean(BeanWithBeanCollection2.class, b1Array); + final BeanWithBeanCollection2 b2Collection = + BeanUtils.createBean(BeanWithBeanCollection2.class, b1Array); final Collection<Bean2a> colb2 = b2Collection.getBeanArray(); assertNotNull(colb2); assertEquals(arrayb1.length, colb2.size()); @@ -792,7 +796,8 @@ public final class BeanUtilsTest final Bean2a[] arrayb2 = new Bean2a[] { b2a, b2b }; b2Array.setBeanArray(arrayb2); - final BeanWithBeanCollection1 b1Collection = BeanUtils.createBean(BeanWithBeanCollection1.class, b2Array); + final BeanWithBeanCollection1 b1Collection = + BeanUtils.createBean(BeanWithBeanCollection1.class, b2Array); final Collection<Bean1a> colb1 = b1Collection.getBeanArray(); assertNotNull(colb1); assertEquals(arrayb2.length, colb1.size()); @@ -822,7 +827,8 @@ public final class BeanUtilsTest final Collection<Bean1a> colb1 = new LinkedHashSet<Bean1a>(Arrays.asList(new Bean1a[] { b1a, b1b })); b1Collection.setBeanArray(colb1); - final BeanWithBeanArray2 b2Array = BeanUtils.createBean(BeanWithBeanArray2.class, b1Collection); + final BeanWithBeanArray2 b2Array = + BeanUtils.createBean(BeanWithBeanArray2.class, b1Collection); final Bean2a[] arrayb2 = b2Array.getBeanArray(); assertNotNull(arrayb2); assertEquals(colb1.size(), arrayb2.length); @@ -859,7 +865,8 @@ public final class BeanUtilsTest assertBeanArraysAreEqual(arrayb1, arrayb2); } - private final static void assertBeanArraysAreEqual(final Bean1a[] arrayb1, final Bean2a[] arrayb2) + private final static void assertBeanArraysAreEqual(final Bean1a[] arrayb1, + final Bean2a[] arrayb2) { assertEquals(arrayb1.length, arrayb2.length); for (int i = 0; i < arrayb1.length; ++i) @@ -877,7 +884,8 @@ public final class BeanUtilsTest final Collection<Bean1a> colb1 = new LinkedHashSet<Bean1a>(Arrays.asList(new Bean1a[] { b1a, b1b })); b1Collection.setBeanArray(colb1); - final BeanWithBeanCollection2 b2Collection = BeanUtils.createBean(BeanWithBeanCollection2.class, b1Collection); + final BeanWithBeanCollection2 b2Collection = + BeanUtils.createBean(BeanWithBeanCollection2.class, b1Collection); final Collection<Bean2a> colb2 = b2Collection.getBeanArray(); assertNotNull(colb2); assertBeanCollectionsAreEqual(colb1, colb2); @@ -955,7 +963,7 @@ public final class BeanUtilsTest assertEquals(msg, b2.getI(), b1.getI()); assertEquals(msg, b2.getS(), b1.getS()); } - + private static interface IFoo { public String getFoo(); @@ -996,30 +1004,32 @@ public final class BeanUtilsTest { final FooBean tofuBean = new FooBean(); tofuBean.setFoo("some tofu"); - final BarBean toFooBean = BeanUtils.createBean(BarBean.class, tofuBean, new BeanUtils.Converter() - { - @SuppressWarnings("unused") - public String convertToBar(FooBean foo) - { - return StringUtils.replace(foo.getFoo(), "tofu", "to Foo"); - } - }); + final BarBean toFooBean = + BeanUtils.createBean(BarBean.class, tofuBean, new BeanUtils.Converter() + { + @SuppressWarnings("unused") + public String convertToBar(FooBean foo) + { + return StringUtils.replace(foo.getFoo(), "tofu", "to Foo"); + } + }); assertEquals("some to Foo", toFooBean.getBar()); } - + @Test public void testConverterWithArgumentOfInterfaceType() { final FooBean tofuBean = new FooBean(); tofuBean.setFoo("some tofu"); - final BarBean toFooBean = BeanUtils.createBean(BarBean.class, tofuBean, new BeanUtils.Converter() - { - @SuppressWarnings("unused") - public String convertToBar(IFoo foo) - { - return StringUtils.replace(foo.getFoo(), "tofu", "to Foo"); - } - }); + final BarBean toFooBean = + BeanUtils.createBean(BarBean.class, tofuBean, new BeanUtils.Converter() + { + @SuppressWarnings("unused") + public String convertToBar(IFoo foo) + { + return StringUtils.replace(foo.getFoo(), "tofu", "to Foo"); + } + }); assertEquals("some to Foo", toFooBean.getBar()); } } \ No newline at end of file diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ClassUtilsTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ClassUtilsTest.java index edb37833088..4c92f4f0c11 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ClassUtilsTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ClassUtilsTest.java @@ -89,8 +89,8 @@ public final class ClassUtilsTest { assertEquals("testGetCurrentMethod", ClassUtils.getCurrentMethod().getName()); // Border cases - assertEquals(new SameMethodName().getMethodName(), new SameMethodName().getMethodName(new Object(), - new Object())); + assertEquals(new SameMethodName().getMethodName(), new SameMethodName().getMethodName( + new Object(), new Object())); } private final static class SameMethodName @@ -128,7 +128,9 @@ public final class ClassUtilsTest @Test public void testCreateWithDefaultConstructor() { - final CharSequence cs = ClassUtils.create(CharSequence.class, StringBuffer.class.getName(), (Object[]) null); + final CharSequence cs = + ClassUtils + .create(CharSequence.class, StringBuffer.class.getName(), (Object[]) null); assertTrue(cs instanceof StringBuffer); assertEquals(0, cs.length()); } @@ -137,7 +139,8 @@ public final class ClassUtilsTest public void testCreateWithPropertiesConstructor() { final Properties properties = new Properties(); - final Appendable appendable = ClassUtils.create(Appendable.class, MyClass.class.getName(), properties); + final Appendable appendable = + ClassUtils.create(Appendable.class, MyClass.class.getName(), properties); assertTrue(appendable instanceof MyClass); assertSame(properties, ((MyClass) appendable).properties); } @@ -151,7 +154,9 @@ public final class ClassUtilsTest fail("AssertionError expected."); } catch (final AssertionError e) { - assertEquals("Class 'java.lang.Integer' does not implements/extends 'java.lang.Float'.", e.getMessage()); + assertEquals( + "Class 'java.lang.Integer' does not implements/extends 'java.lang.Float'.", e + .getMessage()); } } @@ -164,8 +169,9 @@ public final class ClassUtilsTest fail("AssertionError expected."); } catch (final AssertionError e) { - assertEquals("Interface 'java.lang.CharSequence' can not be instanciated as it is an interface.", e - .getMessage()); + assertEquals( + "Interface 'java.lang.CharSequence' can not be instanciated as it is an interface.", + e.getMessage()); } } @@ -174,7 +180,8 @@ public final class ClassUtilsTest { final List<String> list = new ArrayList<String>(); list.add("Hello"); - final Appendable appendable = ClassUtils.create(Appendable.class, MyClass.class.getName(), list); + final Appendable appendable = + ClassUtils.create(Appendable.class, MyClass.class.getName(), list); assertSame(list, ((MyClass) appendable).iterable); } @@ -248,7 +255,8 @@ public final class ClassUtilsTest return null; } - public Appendable append(final CharSequence csq, final int start, final int end) throws IOException + public Appendable append(final CharSequence csq, final int start, final int end) + throws IOException { return null; } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTaskTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTaskTest.java index e987e4851d2..620fbfc9a85 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTaskTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/DirectoryScanningTimerTaskTest.java @@ -43,9 +43,11 @@ import ch.systemsx.cisd.common.logging.LogMonitoringAppender; public class DirectoryScanningTimerTaskTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "DirectoryScanningTimerTaskTest"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "DirectoryScanningTimerTaskTest"); private final static FileFilter ALWAYS_FALSE_FILE_FILTER = new FileFilter() { @@ -55,7 +57,8 @@ public class DirectoryScanningTimerTaskTest } }; - private final static String EXCEPTION_THROWING_FILE_FILTER_MESSAGE = "Exception throwing file filter does its job."; + private final static String EXCEPTION_THROWING_FILE_FILTER_MESSAGE = + "Exception throwing file filter does its job."; private final static FileFilter EXCEPTION_THROWING_FILE_FILTER = new FileFilter() { @@ -108,7 +111,8 @@ public class DirectoryScanningTimerTaskTest @Test public void testFaultyPathsDeletion() { - final File faultyPaths = new File(workingDirectory, DirectoryScanningTimerTask.FAULTY_PATH_FILENAME); + final File faultyPaths = + new File(workingDirectory, DirectoryScanningTimerTask.FAULTY_PATH_FILENAME); CollectionIO.writeIterable(faultyPaths, Collections.singleton("some_path")); new DirectoryScanningTimerTask(workingDirectory, ACCEPT_ALL_FILTER, mockPathHandler); assertEquals(0, faultyPaths.length()); @@ -135,7 +139,8 @@ public class DirectoryScanningTimerTaskTest someFile.createNewFile(); someFile.deleteOnExit(); final DirectoryScanningTimerTask scanner = - new DirectoryScanningTimerTask(workingDirectory, ALWAYS_FALSE_FILE_FILTER, mockPathHandler); + new DirectoryScanningTimerTask(workingDirectory, ALWAYS_FALSE_FILE_FILTER, + mockPathHandler); assertEquals(0, mockPathHandler.handledPaths.size()); scanner.run(); assertEquals(0, mockPathHandler.handledPaths.size()); @@ -144,7 +149,8 @@ public class DirectoryScanningTimerTaskTest @Test public void testManipulateFaultyPaths() throws IOException { - final File faultyPaths = new File(workingDirectory, DirectoryScanningTimerTask.FAULTY_PATH_FILENAME); + final File faultyPaths = + new File(workingDirectory, DirectoryScanningTimerTask.FAULTY_PATH_FILENAME); final File someFile = new File(workingDirectory, "some_file"); someFile.createNewFile(); someFile.deleteOnExit(); @@ -160,7 +166,8 @@ public class DirectoryScanningTimerTaskTest @Test public void testFaultyPaths() throws IOException { - final File faultyPaths = new File(workingDirectory, DirectoryScanningTimerTask.FAULTY_PATH_FILENAME); + final File faultyPaths = + new File(workingDirectory, DirectoryScanningTimerTask.FAULTY_PATH_FILENAME); final File someFile = new File(workingDirectory, "some_file"); final MockPathHandler myPathHandler = new MockPathHandler() { @@ -238,7 +245,8 @@ public class DirectoryScanningTimerTaskTest final File dir = new File(workingDirectory, "testMissingDirectory"); dir.mkdir(); final LogMonitoringAppender appender = - LogMonitoringAppender.addAppender(LogCategory.NOTIFY, "Failed to get listing of directory"); + LogMonitoringAppender.addAppender(LogCategory.NOTIFY, + "Failed to get listing of directory"); try { // The directory needs to exist when the scanner is created, otherwise the self-test will fail. @@ -260,7 +268,8 @@ public class DirectoryScanningTimerTaskTest final File dir = new File(workingDirectory, "testMissingDirectory"); dir.mkdir(); final LogMonitoringAppender appender = - LogMonitoringAppender.addAppender(LogCategory.NOTIFY, "Failed to get listing of directory"); + LogMonitoringAppender.addAppender(LogCategory.NOTIFY, + "Failed to get listing of directory"); try { // The directory needs to exist when the scanner is created, otherwise the self-test will fail. @@ -289,14 +298,17 @@ public class DirectoryScanningTimerTaskTest file.createNewFile(); file.deleteOnExit(); final LogMonitoringAppender appender1 = - LogMonitoringAppender.addAppender(LogCategory.NOTIFY, "Failed to get listing of directory"); + LogMonitoringAppender.addAppender(LogCategory.NOTIFY, + "Failed to get listing of directory"); final LogMonitoringAppender appender2 = - LogMonitoringAppender.addAppender(LogCategory.NOTIFY, EXCEPTION_THROWING_FILE_FILTER_MESSAGE); + LogMonitoringAppender.addAppender(LogCategory.NOTIFY, + EXCEPTION_THROWING_FILE_FILTER_MESSAGE); try { // The directory needs to exist when the scanner is created, otherwise the self-test will fail. final DirectoryScanningTimerTask scanner = - new DirectoryScanningTimerTask(dir, EXCEPTION_THROWING_FILE_FILTER, mockPathHandler); + new DirectoryScanningTimerTask(dir, EXCEPTION_THROWING_FILE_FILTER, + mockPathHandler); scanner.run(); appender1.verifyLogHasHappened(); appender2.verifyLogHasHappened(); @@ -315,9 +327,11 @@ public class DirectoryScanningTimerTaskTest final File dir = new File(workingDirectory, "testSuppressLogging"); dir.mkdir(); final LogMonitoringAppender appenderNotifyError = - LogMonitoringAppender.addAppender(LogCategory.NOTIFY, "Failed to get listing of directory"); + LogMonitoringAppender.addAppender(LogCategory.NOTIFY, + "Failed to get listing of directory"); final LogMonitoringAppender appenderOperationError = - LogMonitoringAppender.addAppender(LogCategory.OPERATION, "Failed to get listing of directory"); + LogMonitoringAppender.addAppender(LogCategory.OPERATION, + "Failed to get listing of directory"); final LogMonitoringAppender appenderOK = LogMonitoringAppender.addAppender(LogCategory.NOTIFY, "' is available again"); try @@ -325,7 +339,8 @@ public class DirectoryScanningTimerTaskTest final int numberOfErrorsToIgnore = 2; // The directory needs to exist when the scanner is created, otherwise the self-test will fail. final DirectoryScanningTimerTask scanner = - new DirectoryScanningTimerTask(dir, ACCEPT_ALL_FILTER, mockPathHandler, numberOfErrorsToIgnore); + new DirectoryScanningTimerTask(dir, ACCEPT_ALL_FILTER, mockPathHandler, + numberOfErrorsToIgnore); dir.delete(); assert dir.exists() == false; // First error -> ignored @@ -358,7 +373,8 @@ public class DirectoryScanningTimerTaskTest @Test public void testDoNotLogDirectoryAvailableWhenNoErrorWasLogged() throws IOException { - final File dir = new File(workingDirectory, "testDoNotLogDirectoryAvailableWhenNoErrorWasLogged"); + final File dir = + new File(workingDirectory, "testDoNotLogDirectoryAvailableWhenNoErrorWasLogged"); dir.mkdir(); final LogMonitoringAppender appender = LogMonitoringAppender.addAppender(LogCategory.NOTIFY, "' is available again."); @@ -367,7 +383,8 @@ public class DirectoryScanningTimerTaskTest final int numberOfErrorsToIgnore = 2; // The directory needs to exist when the scanner is created, otherwise the self-test will fail. final DirectoryScanningTimerTask scanner = - new DirectoryScanningTimerTask(dir, ACCEPT_ALL_FILTER, mockPathHandler, numberOfErrorsToIgnore); + new DirectoryScanningTimerTask(dir, ACCEPT_ALL_FILTER, mockPathHandler, + numberOfErrorsToIgnore); dir.delete(); assert dir.exists() == false; // First error -> ignored diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ExceptionUtilsTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ExceptionUtilsTest.java index de5fe663a0f..e24581d8f77 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ExceptionUtilsTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/ExceptionUtilsTest.java @@ -41,8 +41,9 @@ import ch.systemsx.cisd.common.exceptions.UserFailureException; public final class ExceptionUtilsTest { - private final void checkReturnedClientSafeException(final String message, final Exception rootException, - final Exception clientSafeException, final boolean clientSafe) + private final void checkReturnedClientSafeException(final String message, + final Exception rootException, final Exception clientSafeException, + final boolean clientSafe) { if (clientSafe) { @@ -53,7 +54,8 @@ public final class ExceptionUtilsTest assertTrue(clientSafeException instanceof MasqueradingException); } assertEquals(message, clientSafeException.getMessage()); - assertTrue(Arrays.equals(rootException.getStackTrace(), clientSafeException.getStackTrace())); + assertTrue(Arrays + .equals(rootException.getStackTrace(), clientSafeException.getStackTrace())); if (rootException.getCause() != null) { assertTrue(clientSafeException.getCause() != null); @@ -78,7 +80,8 @@ public final class ExceptionUtilsTest { final String message = "Oooops!"; final UserFailureException exception = new UserFailureException(message); - final Exception clientSafeException = ExceptionUtils.createMasqueradingExceptionIfNeeded(exception); + final Exception clientSafeException = + ExceptionUtils.createMasqueradingExceptionIfNeeded(exception); checkReturnedClientSafeException(message, exception, clientSafeException, true); } @@ -87,7 +90,8 @@ public final class ExceptionUtilsTest { final String message = "Oooops!"; final Exception exception = new SAXException(message); - final Exception clientSafeException = ExceptionUtils.createMasqueradingExceptionIfNeeded(exception); + final Exception clientSafeException = + ExceptionUtils.createMasqueradingExceptionIfNeeded(exception); checkReturnedClientSafeException(message, exception, clientSafeException, false); } @@ -97,18 +101,19 @@ public final class ExceptionUtilsTest final String userFailureText = "Oooops!"; final UserFailureException userFailureException = new UserFailureException(userFailureText); final String runtimeText = "Oooops! I did it again..."; - final RuntimeException runtimeException = new RuntimeException(runtimeText, userFailureException); + final RuntimeException runtimeException = + new RuntimeException(runtimeText, userFailureException); final String unsupportedOperationText = "Wishiiiii!"; final UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException(unsupportedOperationText, runtimeException); final Exception clientSafeException = ExceptionUtils.createMasqueradingExceptionIfNeeded(unsupportedOperationException); - checkReturnedClientSafeException(unsupportedOperationText, unsupportedOperationException, clientSafeException, - true); - checkReturnedClientSafeException(runtimeText, runtimeException, (Exception) clientSafeException.getCause(), - true); - checkReturnedClientSafeException(userFailureText, userFailureException, (Exception) clientSafeException - .getCause().getCause(), true); + checkReturnedClientSafeException(unsupportedOperationText, unsupportedOperationException, + clientSafeException, true); + checkReturnedClientSafeException(runtimeText, runtimeException, + (Exception) clientSafeException.getCause(), true); + checkReturnedClientSafeException(userFailureText, userFailureException, + (Exception) clientSafeException.getCause().getCause(), true); } @Test @@ -119,13 +124,16 @@ public final class ExceptionUtilsTest final String runtimeText = "Oooops! I did it again..."; final RuntimeException runtimeException = new RuntimeException(runtimeText, saxException); final String digestExceptionText = "Wishiiiii!"; - final DigestException digestException = new DigestException(digestExceptionText, runtimeException); - final Exception clientSafeException = ExceptionUtils.createMasqueradingExceptionIfNeeded(digestException); - checkReturnedClientSafeException(digestExceptionText, digestException, clientSafeException, false); - checkReturnedClientSafeException(runtimeText, runtimeException, (Exception) clientSafeException.getCause(), - true); - checkReturnedClientSafeException(saxExceptionText, saxException, (Exception) clientSafeException.getCause() - .getCause(), false); + final DigestException digestException = + new DigestException(digestExceptionText, runtimeException); + final Exception clientSafeException = + ExceptionUtils.createMasqueradingExceptionIfNeeded(digestException); + checkReturnedClientSafeException(digestExceptionText, digestException, clientSafeException, + false); + checkReturnedClientSafeException(runtimeText, runtimeException, + (Exception) clientSafeException.getCause(), true); + checkReturnedClientSafeException(saxExceptionText, saxException, + (Exception) clientSafeException.getCause().getCause(), false); } @Test @@ -133,8 +141,10 @@ public final class ExceptionUtilsTest { final String text = "Oooops!"; final IOException ioException = new IOException(text); - final RuntimeException checkedExceptionTunnel = CheckedExceptionTunnel.wrapIfNecessary(ioException); - final Exception clientSafeException = ExceptionUtils.createMasqueradingExceptionIfNeeded(checkedExceptionTunnel); + final RuntimeException checkedExceptionTunnel = + CheckedExceptionTunnel.wrapIfNecessary(ioException); + final Exception clientSafeException = + ExceptionUtils.createMasqueradingExceptionIfNeeded(checkedExceptionTunnel); assertNotSame(clientSafeException, checkedExceptionTunnel); assertNotSame(clientSafeException, ioException); assertTrue(clientSafeException instanceof MasqueradingException); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesDeleteRecursivelyTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesDeleteRecursivelyTest.java index d66650a69d2..1571f733af0 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesDeleteRecursivelyTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesDeleteRecursivelyTest.java @@ -180,7 +180,8 @@ public final class FileUtilitiesDeleteRecursivelyTest extends AbstractFileSystem { public boolean accept(File pathname) { - return pathname.getName().equals("file1a") || pathname.getName().equals("file3"); + return pathname.getName().equals("file1a") + || pathname.getName().equals("file3"); } }, null); checkDirectories(true); diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesLastChangedTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesLastChangedTest.java index ac0742c593c..5cff1cfc264 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesLastChangedTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesLastChangedTest.java @@ -38,22 +38,26 @@ import static org.testng.AssertJUnit.*; public class FileUtilitiesLastChangedTest { - private static final File workingDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File workingDirectory = + new File("targets" + File.separator + "unit-test-wd"); @DataProvider(name = "testLastChanged") public Object[][] getDirectories() { return new Object[][] { - { ".fsLastChangedCheckerTestDirectory", ".fsLastChangedCheckerTestDirectory" }, { ".fsLastChangedCheckerTestDirectory", - ".fsLastChangedCheckerTestDirectory" + File.separator + "1" }, + ".fsLastChangedCheckerTestDirectory" }, { ".fsLastChangedCheckerTestDirectory", - ".fsLastChangedCheckerTestDirectory" + File.separator + "1" + File.separator + 2 }, + ".fsLastChangedCheckerTestDirectory" + File.separator + "1" }, { ".fsLastChangedCheckerTestDirectory", - ".fsLastChangedCheckerTestDirectory" + File.separator + "1" + File.separator + 2 - + File.separator + 3 } }; + ".fsLastChangedCheckerTestDirectory" + File.separator + "1" + + File.separator + 2 }, + { + ".fsLastChangedCheckerTestDirectory", + ".fsLastChangedCheckerTestDirectory" + File.separator + "1" + + File.separator + 2 + File.separator + 3 } }; } private void restALittleBit() @@ -83,20 +87,21 @@ public class FileUtilitiesLastChangedTest testDir.deleteOnExit(); if (testDir.exists() && testDir.isDirectory() == false) { - throw EnvironmentFailureException.fromTemplate("Directory '%s' exists and is not a directory.", testDir - .getPath()); + throw EnvironmentFailureException.fromTemplate( + "Directory '%s' exists and is not a directory.", testDir.getPath()); } final File createDir = new File(workingDirectory, dirToCreate); if (createDir.exists() && FileUtilities.deleteRecursively(createDir) == false) { - throw EnvironmentFailureException.fromTemplate("Directory '%s' exists and cannot be deleted.", createDir - .getPath()); + throw EnvironmentFailureException.fromTemplate( + "Directory '%s' exists and cannot be deleted.", createDir.getPath()); } createDir.deleteOnExit(); final long now = System.currentTimeMillis(); if (createDir.mkdir() == false) { - throw new EnvironmentFailureException("Can't make directory " + createDir.getPath() + "."); + throw new EnvironmentFailureException("Can't make directory " + createDir.getPath() + + "."); } final long lastChanged = FileUtilities.lastChanged(testDir); final long diff = Math.abs(lastChanged - now); @@ -127,7 +132,7 @@ public class FileUtilitiesLastChangedTest assertEquals(1000L, FileUtilities.lastChanged(dirA, false, 999L)); assertEquals(1000L, FileUtilities.lastChanged(dirA, true, 999L)); } - + @Test public void testLastChangedRelative() throws IOException { @@ -142,9 +147,11 @@ public class FileUtilitiesLastChangedTest final long fakedModTime2 = now - 30000L; fileB.setLastModified(fakedModTime1); dirA.setLastModified(fakedModTime2); - final long diff1 = Math.abs(fakedModTime2 - FileUtilities.lastChangedRelative(dirA, false, 31000L)); + final long diff1 = + Math.abs(fakedModTime2 - FileUtilities.lastChangedRelative(dirA, false, 31000L)); assertTrue("Difference to big: " + diff1 + " ms", diff1 < 1000L); - final long diff2 = Math.abs(fakedModTime1 - FileUtilities.lastChangedRelative(dirA, false, 11000L)); + final long diff2 = + Math.abs(fakedModTime1 - FileUtilities.lastChangedRelative(dirA, false, 11000L)); assertTrue("Difference to big: " + diff2 + " ms", diff2 < 1000L); } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesTest.java index 68e3079d203..68bf4da94de 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileUtilitiesTest.java @@ -85,7 +85,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase // --- clean before checking results // Unfortunately, with JDK 5 there is no portable way to set a file or directory read/write, once // it has been set read-only, thus this test 'requires_unix' for the time being. - Runtime.getRuntime().exec(String.format("/bin/chmod u+w %s", readOnlyDirectory.getPath())).waitFor(); + Runtime.getRuntime().exec(String.format("/bin/chmod u+w %s", readOnlyDirectory.getPath())) + .waitFor(); if (readOnlyDirectory.canWrite() == false) { // Can't use assert here since we expect an AssertationError @@ -103,7 +104,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase assertEquals(47110000, sourceFile.lastModified()); File destinationFile = new File(workingDirectory, "destination.txt"); FileUtilities.copyFileTo(sourceFile, destinationFile, true); - assertEquals(FileUtilities.loadToString(sourceFile), FileUtilities.loadToString(destinationFile)); + assertEquals(FileUtilities.loadToString(sourceFile), FileUtilities + .loadToString(destinationFile)); assertEquals(47110000, destinationFile.lastModified()); } @@ -138,7 +140,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase Throwable cause = e.getCause(); assertTrue(cause instanceof IOException); String message = cause.getMessage(); - assertTrue("Exception message not as expected: " + message, cause.getMessage().startsWith(dir.toString())); + assertTrue("Exception message not as expected: " + message, cause.getMessage() + .startsWith(dir.toString())); } } @@ -157,7 +160,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase Throwable cause = e.getCause(); assertTrue(cause instanceof IOException); String message = cause.getMessage(); - assertTrue("Exception message not as expected: " + message, cause.getMessage().startsWith(file.toString())); + assertTrue("Exception message not as expected: " + message, cause.getMessage() + .startsWith(file.toString())); } finally { assert file.delete(); @@ -186,7 +190,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase public void testLoadToStringResource() throws Exception { final String thisFile = - FileUtilities.loadToString(getClass(), "/ch/systemsx/cisd/common/utilities/FileUtilitiesTest.class"); + FileUtilities.loadToString(getClass(), + "/ch/systemsx/cisd/common/utilities/FileUtilitiesTest.class"); assert thisFile != null; assert thisFile.indexOf("FileUtilitiesTest") >= 0; } @@ -255,10 +260,11 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase // Nothing to do here } assertEquals(file, FileUtilities.removePrefixFromFileName(file, null)); - assertEquals(file, FileUtilities.removePrefixFromFileName(file, Constants.IS_FINISHED_PREFIX)); + assertEquals(file, FileUtilities.removePrefixFromFileName(file, + Constants.IS_FINISHED_PREFIX)); file = new File("/tmp/dir/" + Constants.IS_FINISHED_PREFIX + "x.txt"); - assertEquals("/tmp/dir/x.txt", FileUtilities.removePrefixFromFileName(file, Constants.IS_FINISHED_PREFIX) - .getPath()); + assertEquals("/tmp/dir/x.txt", FileUtilities.removePrefixFromFileName(file, + Constants.IS_FINISHED_PREFIX).getPath()); } @Test @@ -295,7 +301,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase String defaultFileName = "abc_[1]"; try { - FileUtilities.createNextNumberedFile(file, Pattern.compile("dummyPattern"), defaultFileName); + FileUtilities.createNextNumberedFile(file, Pattern.compile("dummyPattern"), + defaultFileName); fail("Must contain either '(\\d+)' or ([0-9]+)."); } catch (AssertionError e) { @@ -325,7 +332,9 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase FileUtils.touch(file); newFile = FileUtilities.createNextNumberedFile(file, pattern, "12abc_[1]"); assertEquals(new File(workingDirectory, "12abc_[13]"), newFile); - newFile = FileUtilities.createNextNumberedFile(file, Pattern.compile("xxx(\\d+)xxx"), "12abc_[1]"); + newFile = + FileUtilities.createNextNumberedFile(file, Pattern.compile("xxx(\\d+)xxx"), + "12abc_[1]"); assertEquals(new File(workingDirectory, "12abc_[1]"), newFile); } @@ -341,11 +350,13 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase // Nothing to do here } File file = new File(workingDirectory, "hello"); - assertEquals(workingDirectory.getAbsolutePath() + File.separator + "hello", file.getAbsolutePath()); + assertEquals(workingDirectory.getAbsolutePath() + File.separator + "hello", file + .getAbsolutePath()); // If the given string is the empty string, then the result is the empty abstract pathname. final File rootFile = new File(""); - assertEquals(TARGETS_DIRECTORY + File.separator + UNIT_TEST_WORKING_DIRECTORY + File.separator - + workingDirectory.getName() + File.separator + "hello", FileUtilities.getRelativeFile(rootFile, file)); + assertEquals(TARGETS_DIRECTORY + File.separator + UNIT_TEST_WORKING_DIRECTORY + + File.separator + workingDirectory.getName() + File.separator + "hello", + FileUtilities.getRelativeFile(rootFile, file)); String root = "/temp"; String relativeFile = FileUtilities.getRelativeFile(new File(root), file); assertNull(relativeFile); @@ -364,7 +375,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase public final void testCopyResourceToTempFile() { final String resourceName = "/ch/systemsx/cisd/common/utilities/FileUtilities.class"; - final String absoluteTempFileName = FileUtilities.copyResourceToTempFile(resourceName, "pre", "post"); + final String absoluteTempFileName = + FileUtilities.copyResourceToTempFile(resourceName, "pre", "post"); assertNotNull(absoluteTempFileName); final File tempFile = new File(absoluteTempFileName); final String tempFileName = tempFile.getName(); @@ -372,7 +384,8 @@ public final class FileUtilitiesTest extends AbstractFileSystemTestCase assertTrue(tempFile.length() > 0); assertTrue(tempFileName.startsWith("pre")); assertTrue(tempFileName.endsWith("post")); - assertTrue(Arrays.equals(resourceToByteArray(resourceName), fileToByteArray(absoluteTempFileName))); + assertTrue(Arrays.equals(resourceToByteArray(resourceName), + fileToByteArray(absoluteTempFileName))); } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileWatcherTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileWatcherTest.java index c655fe2ce93..7f1a6603cef 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileWatcherTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/FileWatcherTest.java @@ -42,7 +42,8 @@ import ch.systemsx.cisd.common.logging.BufferedAppender; */ public class FileWatcherTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); private static final File workingDirectory = new File(unitTestRootDirectory, "FileWatcherTest"); @@ -87,14 +88,16 @@ public class FileWatcherTest File file = new File(workingDirectory, "doesNotExist"); assert file.exists() == false; new TestFileWatcher(file).run(); - assertEquals(String.format(FileWatcher.DOES_NOT_EXIST_FORMAT, file), testAppender.getLogContent()); + assertEquals(String.format(FileWatcher.DOES_NOT_EXIST_FORMAT, file), testAppender + .getLogContent()); } @Test public final void testNonChangingFile() { new TestFileWatcher(tmpFile1).run(); - assertEquals(String.format(FileWatcher.HAS_NOT_CHANGED_FORMAT, tmpFile1), testAppender.getLogContent()); + assertEquals(String.format(FileWatcher.HAS_NOT_CHANGED_FORMAT, tmpFile1), testAppender + .getLogContent()); } @Test @@ -104,7 +107,8 @@ public class FileWatcherTest FileWatcher fileWatcher = new TestFileWatcher(tmpFile1); FileUtils.touch(tmpFile1); fileWatcher.run(); - assertEquals(String.format(FileWatcher.HAS_CHANGED_FORMAT, tmpFile1), testAppender.getLogContent()); + assertEquals(String.format(FileWatcher.HAS_CHANGED_FORMAT, tmpFile1), testAppender + .getLogContent()); assertEquals(true, onChangeCalled); } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilterTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilterTest.java index 453d5e3a2b6..690c687c477 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilterTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/NamePrefixFileFilterTest.java @@ -23,14 +23,14 @@ import org.testng.annotations.Test; /** * Test cases for {@link NamePrefixFileFilter}. - * + * * @author Bernd Rinn */ public class NamePrefixFileFilterTest { - + private static final String PREFIX = "PReFiX"; - + @Test public void testNamePrefixShouldOccurAndFound() { diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/OSUtilitiesTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/OSUtilitiesTest.java index e5ebcfa4ed1..07625aa284c 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/OSUtilitiesTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/OSUtilitiesTest.java @@ -36,7 +36,8 @@ import ch.systemsx.cisd.common.logging.LogInitializer; public class OSUtilitiesTest { - private static final File workingDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File workingDirectory = + new File("targets" + File.separator + "unit-test-wd"); @BeforeSuite public void init() diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/PathPrefixPrependerTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/PathPrefixPrependerTest.java index e2bc77e16b2..3730af1b69b 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/PathPrefixPrependerTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/PathPrefixPrependerTest.java @@ -62,9 +62,8 @@ public final class PathPrefixPrependerTest extends AbstractFileSystemTestCase { try { - new PathPrefixPrepender((workingDirectory.getAbsolutePath() + "/absolute"), workingDirectory - .getAbsolutePath() - + "/relative"); + new PathPrefixPrepender((workingDirectory.getAbsolutePath() + "/absolute"), + workingDirectory.getAbsolutePath() + "/relative"); fail("Given prefixes are not valid."); } catch (final ConfigurationFailureException ex) { @@ -102,8 +101,10 @@ public final class PathPrefixPrependerTest extends AbstractFileSystemTestCase // Nothing to do here. } assertEquals(prefixForRelativePathsOrNull + "/", prepender.addPrefixTo("")); - assertEquals(prefixForRelativePathsOrNull + "/choubidou", prepender.addPrefixTo("choubidou")); - assertEquals(prefixForAbsolutePathsOrNull + "/choubidou", prepender.addPrefixTo("/choubidou")); + assertEquals(prefixForRelativePathsOrNull + "/choubidou", prepender + .addPrefixTo("choubidou")); + assertEquals(prefixForAbsolutePathsOrNull + "/choubidou", prepender + .addPrefixTo("/choubidou")); assertEquals(prefixForAbsolutePathsOrNull + "/", prepender.addPrefixTo("/")); } } \ No newline at end of file diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMakerTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMakerTest.java index 066d59af09b..06d1ff15aca 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMakerTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RecursiveHardLinkMakerTest.java @@ -41,7 +41,8 @@ import ch.systemsx.cisd.common.utilities.RecursiveHardLinkMaker; */ public class RecursiveHardLinkMakerTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); private static final File workingDirectory = new File(unitTestRootDirectory, RecursiveHardLinkMakerTest.class.getSimpleName()); @@ -74,7 +75,8 @@ public class RecursiveHardLinkMakerTest final File file = new File(directory, name); file.createNewFile(); assert file.isFile(); - CollectionIO.writeIterable(file, Arrays.asList("test line 1", "test line 2", "test line 3")); + CollectionIO + .writeIterable(file, Arrays.asList("test line 1", "test line 2", "test line 3")); file.deleteOnExit(); return file; } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RegexFileFilterTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RegexFileFilterTest.java index 7be34f36462..1639ec63f7f 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RegexFileFilterTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/RegexFileFilterTest.java @@ -41,9 +41,11 @@ import ch.systemsx.cisd.common.utilities.RegexFileFilter.PathType; public class RegexFileFilterTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "RegexFileFilterTestTest"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "RegexFileFilterTestTest"); @BeforeClass public void init() @@ -69,7 +71,8 @@ public class RegexFileFilterTest createFile("baa"); createFile("bba"); createDirectory("bab"); - Set<File> actual = new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter()))); + Set<File> actual = + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter()))); assert actual.isEmpty(); } @@ -82,17 +85,20 @@ public class RegexFileFilterTest final File f4 = createFile("bba"); createDirectory("bab"); Set<File> actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.FILE, "a.+")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.FILE, "a.+")))); Set<File> expected = new HashSet<File>(Arrays.asList(f1, f2)); assertEquals(expected, actual); actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.FILE, ".a.")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.FILE, ".a.")))); expected = new HashSet<File>(Arrays.asList(f1, f3)); assertEquals(expected, actual); actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.FILE, ".+a")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.FILE, ".+a")))); expected = new HashSet<File>(Arrays.asList(f1, f2, f3, f4)); assertEquals(expected, actual); } @@ -106,20 +112,20 @@ public class RegexFileFilterTest final File d4 = createDirectory("bba"); createFile("bab"); Set<File> actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.DIRECTORY, - "a.+")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.DIRECTORY, "a.+")))); Set<File> expected = new HashSet<File>(Arrays.asList(d1, d2)); assertEquals(expected, actual); actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.DIRECTORY, - ".a.")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.DIRECTORY, ".a.")))); expected = new HashSet<File>(Arrays.asList(d1, d3)); assertEquals(expected, actual); actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.DIRECTORY, - ".+a")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.DIRECTORY, ".+a")))); expected = new HashSet<File>(Arrays.asList(d1, d2, d3, d4)); assertEquals(expected, actual); } @@ -133,15 +139,20 @@ public class RegexFileFilterTest final File d4 = createDirectory("bba"); final File f5 = createFile("bab"); Set<File> actual = - new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.ALL, "a.+")))); + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.ALL, "a.+")))); Set<File> expected = new HashSet<File>(Arrays.asList(f1, d2)); assertEquals(expected, actual); - actual = new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.ALL, ".a.")))); + actual = + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.ALL, ".a.")))); expected = new HashSet<File>(Arrays.asList(f1, f3, f5)); assertEquals(expected, actual); - actual = new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter(PathType.ALL, ".+a")))); + actual = + new HashSet<File>(Arrays.asList(workingDirectory.listFiles(new RegexFileFilter( + PathType.ALL, ".+a")))); expected = new HashSet<File>(Arrays.asList(f1, d2, f3, d4)); assertEquals(expected, actual); } diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/StringUtilitiesTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/StringUtilitiesTest.java index aa93ae098b2..6d0788df83d 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/StringUtilitiesTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/StringUtilitiesTest.java @@ -54,10 +54,11 @@ public class StringUtilitiesTest { final List<String> list = Arrays.asList("one", "two", "three"); assertEquals("one two three", StringUtilities.concatenateWithSpace(list)); - final String brokenDownInLines = String.format("one%1$stwo%1$sthree", System.getProperty("line.separator")); + final String brokenDownInLines = + String.format("one%1$stwo%1$sthree", System.getProperty("line.separator")); assertEquals(brokenDownInLines, StringUtilities.concatenateWithNewLine(list)); } - + @Test public void testComputeMD5Hash() { diff --git a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/TemplateTest.java b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/TemplateTest.java index 96beb89adfa..0dc21fa4718 100644 --- a/common/sourceTest/java/ch/systemsx/cisd/common/utilities/TemplateTest.java +++ b/common/sourceTest/java/ch/systemsx/cisd/common/utilities/TemplateTest.java @@ -22,8 +22,6 @@ import static org.testng.AssertJUnit.fail; import org.testng.annotations.Test; /** - * - * * @author Franz-Josef Elmer */ public class TemplateTest @@ -33,13 +31,13 @@ public class TemplateTest { assertEquals("", new Template("").createText()); } - + @Test public void testWithoutPlaceholders() { assertEquals("hello", new Template("hello").createText()); } - + @Test public void testWithOnePlaceholder() { @@ -47,7 +45,7 @@ public class TemplateTest template.bind("name", "world"); assertEquals("hello world!", template.createText()); } - + @Test public void testWithTwiceTheSamePlaceholder() { @@ -55,7 +53,7 @@ public class TemplateTest template.bind("name", "world"); assertEquals("hello worldworld", template.createText()); } - + @Test public void testWithTwoPlaceholders() { @@ -64,14 +62,14 @@ public class TemplateTest template.bind("name2", "Albert Einstein"); assertEquals("hello world, do you know Albert Einstein?", template.createText()); } - + @Test public void testWithEscaping() { Template template = new Template("hello $${name}. I have 25$."); assertEquals("hello ${name}. I have 25$.", template.createText()); } - + @Test public void testNamelessPlaceholderInTemplate() { @@ -84,7 +82,7 @@ public class TemplateTest assertEquals("Nameless placeholder ${} found.", e.getMessage()); } } - + @Test public void testUnfinishedPlaceholderInTemplate() { @@ -113,7 +111,7 @@ public class TemplateTest assertEquals("Incomplete placeholder detected at the end.", e.getMessage()); } } - + @Test public void testBindUnknownPlaceholder() { @@ -127,7 +125,7 @@ public class TemplateTest assertEquals("Unknown variable 'blabla'.", e.getMessage()); } } - + @Test public void testAttemptToBind() { @@ -136,7 +134,7 @@ public class TemplateTest assertEquals(false, template.attemptToBind("blabla", "blub")); assertEquals("Hi ${name}!", template.createText(false)); } - + @Test public void testIncompleteBinding() { @@ -149,7 +147,7 @@ public class TemplateTest { assertEquals("The following variables are not bound: greeting name ", e.getMessage()); } - + template.bind("greeting", "hello"); assertEquals("hello ${name}!", template.createText(false)); try @@ -161,7 +159,7 @@ public class TemplateTest assertEquals("The following variables are not bound: name ", e.getMessage()); } } - + @Test public void testCreateFreshCopy() { @@ -178,7 +176,7 @@ public class TemplateTest template1.bind("name", "world"); assertEquals("hello world.world!", template1.createText()); assertEquals("hello ${name}.${name}!", template.createText(false)); - + Template template2 = template.createFreshCopy(); template2.bind("name", "universe"); assertEquals("hello universe.universe!", template2.createText()); diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/DataMover.java b/datamover/source/java/ch/systemsx/cisd/datamover/DataMover.java index 3cc78667e50..2b58fdd32e3 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/DataMover.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/DataMover.java @@ -84,7 +84,8 @@ public class DataMover return new DataMover(parameters, factory, localBufferDirs).start(); } - private DataMover(Parameters parameters, IFileSysOperationsFactory factory, LocalBufferDirs bufferDirs) + private DataMover(Parameters parameters, IFileSysOperationsFactory factory, + LocalBufferDirs bufferDirs) { this.parameters = parameters; this.factory = factory; @@ -101,7 +102,8 @@ public class DataMover localProcessor.startup(parameters.getCheckIntervalInternalMillis() / 2L, parameters .getCheckIntervalInternalMillis()); incomingProcess.startup(0L, parameters.getCheckIntervalMillis()); - return createCompoundTerminable(recoveryProcess, outgoingMovingProcess, localProcessor, incomingProcess); + return createCompoundTerminable(recoveryProcess, outgoingMovingProcess, localProcessor, + incomingProcess); } private ITerminable startupRecoveryProcess(final DataMoverProcess localProcessor, @@ -120,7 +122,8 @@ public class DataMover final TriggeringTimerTask recoveryingTimerTask = new TriggeringTimerTask(new File(RECOVERY_MARKER_FIILENAME), recoverable); final Timer recoveryTimer = new Timer("Recovery"); - recoveryTimer.schedule(recoveryingTimerTask, 0, parameters.getCheckIntervalInternalMillis()); + recoveryTimer + .schedule(recoveryingTimerTask, 0, parameters.getCheckIntervalInternalMillis()); return TimerHelper.asTerminable(recoveryTimer); } @@ -132,11 +135,11 @@ public class DataMover private DataMoverProcess createLocalProcessor() { final LocalProcessor localProcessor = - LocalProcessor.create(parameters, bufferDirs.getCopyCompleteDir(), bufferDirs.getReadyToMoveDir(), - bufferDirs.getTempDir(), factory); + LocalProcessor.create(parameters, bufferDirs.getCopyCompleteDir(), bufferDirs + .getReadyToMoveDir(), bufferDirs.getTempDir(), factory); final DirectoryScanningTimerTask localProcessingTask = - new DirectoryScanningTimerTask(bufferDirs.getCopyCompleteDir(), FileUtilities.ACCEPT_ALL_FILTER, - localProcessor); + new DirectoryScanningTimerTask(bufferDirs.getCopyCompleteDir(), + FileUtilities.ACCEPT_ALL_FILTER, localProcessor); return new DataMoverProcess(localProcessingTask, "Local Processor", localProcessor); } @@ -144,8 +147,10 @@ public class DataMover { final FileStore outgoingStore = parameters.getOutgoingStore(factory); final File readyToMoveDir = bufferDirs.getReadyToMoveDir(); - final IFileStore readyToMoveStore = FileStoreFactory.createLocal(readyToMoveDir, "ready-to-move", factory); - final IStoreHandler remoteStoreMover = createRemotePathMover(readyToMoveStore, outgoingStore); + final IFileStore readyToMoveStore = + FileStoreFactory.createLocal(readyToMoveDir, "ready-to-move", factory); + final IStoreHandler remoteStoreMover = + createRemotePathMover(readyToMoveStore, outgoingStore); final DirectoryScanningTimerTask outgoingMovingTask = new DirectoryScanningTimerTask(readyToMoveDir, FileUtilities.ACCEPT_ALL_FILTER, @@ -153,7 +158,8 @@ public class DataMover return new DataMoverProcess(outgoingMovingTask, "Final Destination Mover"); } - // TODO 2007-10-10, Tomasz Pylak: remove this when DirectoryScanningTimerTask will work with IStoreHandler. This is a + // TODO 2007-10-10, Tomasz Pylak: remove this when DirectoryScanningTimerTask will work with IStoreHandler. This is + // a // quick hack. private static IPathHandler asPathHandler(final IStoreHandler storeHandler) { diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/IncomingProcessor.java b/datamover/source/java/ch/systemsx/cisd/datamover/IncomingProcessor.java index 0471e04fc30..482cd6177a3 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/IncomingProcessor.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/IncomingProcessor.java @@ -55,7 +55,8 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory */ private final static int NUMBER_OF_ERRORS_IN_LISTING_IGNORED = 2; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, IncomingProcessor.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, IncomingProcessor.class); private static final ISimpleLogger simpleOperationLog = new Log4jSimpleLogger(operationLog); @@ -73,15 +74,16 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory private final QuietPeriodFileFilter quietPeriodFileFilter; - public static final DataMoverProcess createMovingProcess(Parameters parameters, IFileSysOperationsFactory factory, - LocalBufferDirs bufferDirs) + public static final DataMoverProcess createMovingProcess(Parameters parameters, + IFileSysOperationsFactory factory, LocalBufferDirs bufferDirs) { final IncomingProcessor processor = new IncomingProcessor(parameters, factory, bufferDirs); return processor.create(); } - private IncomingProcessor(Parameters parameters, IFileSysOperationsFactory factory, LocalBufferDirs bufferDirs) + private IncomingProcessor(Parameters parameters, IFileSysOperationsFactory factory, + LocalBufferDirs bufferDirs) { this.parameters = parameters; this.prefixForIncoming = parameters.getPrefixForIncoming(); @@ -102,8 +104,8 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory final IStoreHandler pathHandler = createIncomingMovingPathHandler(); final DirectoryScanningTimerTask movingTask = - new DirectoryScanningTimerTask(createIncomingStoreScanner(), bufferDirs.getCopyInProgressDir(), - pathHandler, NUMBER_OF_ERRORS_IN_LISTING_IGNORED); + new DirectoryScanningTimerTask(createIncomingStoreScanner(), bufferDirs + .getCopyInProgressDir(), pathHandler, NUMBER_OF_ERRORS_IN_LISTING_IGNORED); return new DataMoverProcess(movingTask, "Mover of Incoming Data", this); } @@ -177,7 +179,8 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory private void moveFromLocalIncoming(IExtendedFileStore sourceStore, StoreItem sourceItem) { - sourceStore.tryMoveLocal(sourceItem, bufferDirs.getCopyCompleteDir(), parameters.getPrefixForIncoming()); + sourceStore.tryMoveLocal(sourceItem, bufferDirs.getCopyCompleteDir(), parameters + .getPrefixForIncoming()); } private void moveFromRemoteIncoming(StoreItem sourceItem) @@ -196,7 +199,8 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory tryMoveFromInProgressToFinished(copiedFile, markerFile, bufferDirs.getCopyCompleteDir()); } - private File tryMoveFromInProgressToFinished(File copiedFile, File markerFileOrNull, File copyCompleteDir) + private File tryMoveFromInProgressToFinished(File copiedFile, File markerFileOrNull, + File copyCompleteDir) { final File finalFile = tryMoveLocal(copiedFile, copyCompleteDir, prefixForIncoming); if (finalFile != null) @@ -219,15 +223,18 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory } } - private void moveFromRemoteToLocal(StoreItem sourceItem, IFileStore sourceStore, File localDestDir) + private void moveFromRemoteToLocal(StoreItem sourceItem, IFileStore sourceStore, + File localDestDir) { - createRemotePathMover(sourceStore, FileStoreFactory.createLocal(localDestDir, "local", factory)).handle( - sourceItem); + createRemotePathMover(sourceStore, + FileStoreFactory.createLocal(localDestDir, "local", factory)).handle(sourceItem); } - private IStoreHandler createRemotePathMover(IFileStore sourceDirectory, FileStore destinationDirectory) + private IStoreHandler createRemotePathMover(IFileStore sourceDirectory, + FileStore destinationDirectory) { - return RemoteMonitoredMoverFactory.create(sourceDirectory, destinationDirectory, parameters); + return RemoteMonitoredMoverFactory + .create(sourceDirectory, destinationDirectory, parameters); } private File tryMoveLocal(File sourceFile, File destinationDir, String prefixTemplate) @@ -248,7 +255,8 @@ public class IncomingProcessor implements IRecoverableTimerTaskFactory } if (incomingStore.isRemote()) { - recoverIncomingInProgress(bufferDirs.getCopyInProgressDir(), bufferDirs.getCopyCompleteDir()); + recoverIncomingInProgress(bufferDirs.getCopyInProgressDir(), bufferDirs + .getCopyCompleteDir()); } if (operationLog.isDebugEnabled()) { diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/LocalProcessor.java b/datamover/source/java/ch/systemsx/cisd/datamover/LocalProcessor.java index 29bdb4d7cbf..41136d7962f 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/LocalProcessor.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/LocalProcessor.java @@ -44,13 +44,15 @@ import ch.systemsx.cisd.datamover.filesystem.intf.IRecoverableTimerTaskFactory; */ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactory { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, LocalProcessor.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, LocalProcessor.class); private static final Logger manualInterventionLog = Logger.getLogger("MANUAL_INTERVENTION"); private static final ISimpleLogger simpleOperationLog = new Log4jSimpleLogger(operationLog); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, LocalProcessor.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, LocalProcessor.class); private final Parameters parameters; @@ -84,8 +86,8 @@ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactor this.mover = factory.getMover(); } - public static final LocalProcessor create(Parameters parameters, File inputDir, File outputDir, File bufferDir, - IFileSysOperationsFactory factory) + public static final LocalProcessor create(Parameters parameters, File inputDir, File outputDir, + File bufferDir, IFileSysOperationsFactory factory) { final LocalProcessor handlerAndRecoverable = new LocalProcessor(parameters, inputDir, outputDir, bufferDir, factory); @@ -167,11 +169,13 @@ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactor extraTmpCopy = new File(tempDir, path.getName()); if (extraTmpCopy.exists()) { - operationLog.warn(String.format("Half-finished extra copy directory '%s' exists - removing it.", + operationLog.warn(String.format( + "Half-finished extra copy directory '%s' exists - removing it.", extraTmpCopy.getAbsolutePath())); if (FileUtilities.deleteRecursively(extraTmpCopy) == false) { - notificationLog.error(String.format("Removal of half-finished extra copy directory '%s' failed.", + notificationLog.error(String.format( + "Removal of half-finished extra copy directory '%s' failed.", extraTmpCopy.getAbsolutePath())); return; } @@ -187,8 +191,8 @@ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactor final File movedFile = mover.tryMove(path, outputDir); if (movedFile == null) { - notificationLog.error(String - .format("Moving '%s' to '%s' for final moving process failed.", path, outputDir)); + notificationLog.error(String.format( + "Moving '%s' to '%s' for final moving process failed.", path, outputDir)); return; } @@ -198,7 +202,8 @@ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactor File extraCopy = mover.tryMove(extraTmpCopy, extraCopyDirOrNull); if (extraCopy == null) { - notificationLog.error(String.format("Moving temporary extra copy '%s' to destination '%s' failed.", + notificationLog.error(String.format( + "Moving temporary extra copy '%s' to destination '%s' failed.", extraTmpCopy, extraCopyDirOrNull)); } } @@ -238,8 +243,10 @@ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactor cleansingFilter.add(PathType.FILE, cleansingRegex); } final ISimpleLogger logger = - operationLog.isDebugEnabled() ? new Log4jSimpleLogger(operationLog, Level.DEBUG) : null; - final boolean pathDeleted = FileUtilities.deleteRecursively(resource, cleansingFilter, logger); + operationLog.isDebugEnabled() ? new Log4jSimpleLogger(operationLog, Level.DEBUG) + : null; + final boolean pathDeleted = + FileUtilities.deleteRecursively(resource, cleansingFilter, logger); return pathDeleted; } @@ -282,13 +289,15 @@ public class LocalProcessor implements IPathHandler, IRecoverableTimerTaskFactor operationLog.info(String.format("%s on %s", description, path.getPath())); } } - + private static void logManualIntervention(File path, boolean needsManualIntervention) { if (manualInterventionLog.isInfoEnabled()) { - manualInterventionLog.info(String.format("%s %s [created: %3$tY-%3$tm-%3$td %3$tH:%3$tM:%3$tS]", - needsManualIntervention ? "ATTENTION" : "DEFAULT", path.getAbsolutePath(), path.lastModified())); + manualInterventionLog.info(String.format( + "%s %s [created: %3$tY-%3$tm-%3$td %3$tH:%3$tM:%3$tS]", + needsManualIntervention ? "ATTENTION" : "DEFAULT", path.getAbsolutePath(), path + .lastModified())); } } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/Main.java b/datamover/source/java/ch/systemsx/cisd/datamover/Main.java index 29904733617..d3605bddbb3 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/Main.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/Main.java @@ -42,17 +42,21 @@ import ch.systemsx.cisd.datamover.utils.LocalBufferDirs; public class Main { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, Main.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, Main.class); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, Main.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, Main.class); - private static final UncaughtExceptionHandler loggingExceptionHandler = new UncaughtExceptionHandler() - { - public void uncaughtException(Thread t, Throwable e) - { - notificationLog.error("An exception has occurred [thread: '" + t.getName() + "'].", e); - } - }; + private static final UncaughtExceptionHandler loggingExceptionHandler = + new UncaughtExceptionHandler() + { + public void uncaughtException(Thread t, Throwable e) + { + notificationLog.error("An exception has occurred [thread: '" + t.getName() + + "'].", e); + } + }; private static final Runnable loggingShutdownHook = new Runnable() { @@ -97,28 +101,30 @@ public class Main FileSysOperationsFactory factory = new FileSysOperationsFactory(parameters); stores.add(parameters.getIncomingStore(factory)); FileStore buferStore = - FileStoreFactory.createLocal(parameters.getBufferDirectoryPath(), Parameters.BUFFER_KIND_DESC, - factory); + FileStoreFactory.createLocal(parameters.getBufferDirectoryPath(), + Parameters.BUFFER_KIND_DESC, factory); stores.add(buferStore); stores.add(parameters.getOutgoingStore(factory)); if (parameters.tryGetManualInterventionDir() != null) { FileStore dummyStore = - FileStoreFactory.createLocal(parameters.tryGetManualInterventionDir(), "manual intervention", - factory); + FileStoreFactory.createLocal(parameters.tryGetManualInterventionDir(), + "manual intervention", factory); stores.add(dummyStore); } if (parameters.tryGetExtraCopyDir() != null) { FileStore dummyStore = - FileStoreFactory.createLocal(parameters.tryGetExtraCopyDir(), "extra-copy", factory); + FileStoreFactory.createLocal(parameters.tryGetExtraCopyDir(), "extra-copy", + factory); stores.add(dummyStore); } IPathCopier copyProcess = factory.getCopier(false); SelfTest.check(copyProcess, stores.toArray(new FileStore[] {})); } catch (HighLevelException e) { - System.err.printf(msgStart + " [%s: %s]\n", e.getClass().getSimpleName(), e.getMessage()); + System.err.printf(msgStart + " [%s: %s]\n", e.getClass().getSimpleName(), e + .getMessage()); System.exit(1); } catch (RuntimeException e) { diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/Parameters.java b/datamover/source/java/ch/systemsx/cisd/datamover/Parameters.java index 7333ba8bc4d..d39d702ab3c 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/Parameters.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/Parameters.java @@ -53,9 +53,11 @@ public class Parameters implements ITimingParameters, IFileSysParameters { private static final String SERVICE_PROPERTIES_FILE = "etc/service.properties"; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, Parameters.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, Parameters.class); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, Parameters.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, Parameters.class); /** * The name of the <code>rsync</code> executable to use for copy operations. @@ -266,7 +268,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters @Option(longName = "version", skipForExample = true, usage = "Prints out the version information.") void printVersion(boolean exit) { - System.err.println("Datamover version " + BuildAndEnvironmentInfo.INSTANCE.getFullVersion()); + System.err + .println("Datamover version " + BuildAndEnvironmentInfo.INSTANCE.getFullVersion()); if (exit) { System.exit(0); @@ -277,7 +280,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters + "sent out).") void sendTestNotification(boolean exit) { - notificationLog.info("This is a test notification given due to specifying the --test-notify option."); + notificationLog + .info("This is a test notification given due to specifying the --test-notify option."); if (exit) { System.exit(0); @@ -347,8 +351,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters } } - private static FileStore createStore(File directory, String kind, String hostOrNull, boolean isRemote, - IFileSysOperationsFactory factory) + private static FileStore createStore(File directory, String kind, String hostOrNull, + boolean isRemote, IFileSysOperationsFactory factory) { if (hostOrNull != null) { @@ -413,7 +417,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters Integer.parseInt(serviceProperties.getProperty("inactivity-period", Integer .toString(DEFAULT_INACTIVITY_PERIOD))) * 1000; quietPeriodMillis = - Integer.parseInt(serviceProperties.getProperty("quiet-period", Integer.toString(DEFAULT_QUIET_PERIOD))) * 1000; + Integer.parseInt(serviceProperties.getProperty("quiet-period", Integer + .toString(DEFAULT_QUIET_PERIOD))) * 1000; intervalToWaitAfterFailureMillis = Integer.parseInt(serviceProperties.getProperty("failure-interval", Integer .toString(DEFAULT_INTERVAL_TO_WAIT_AFTER_FAILURES))) * 1000; @@ -421,8 +426,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters Integer.parseInt(serviceProperties.getProperty("max-retries", Integer .toString(DEFAULT_MAXIMAL_NUMBER_OF_RETRIES))); treatIncomingAsRemote = - Boolean.parseBoolean(serviceProperties.getProperty("treat-incoming-as-remote", Boolean - .toString(DEFAULT_TREAT_INCOMING_AS_REMOTE)).trim()); + Boolean.parseBoolean(serviceProperties.getProperty("treat-incoming-as-remote", + Boolean.toString(DEFAULT_TREAT_INCOMING_AS_REMOTE)).trim()); prefixForIncoming = serviceProperties.getProperty("prefix-for-incoming", "").trim(); if (serviceProperties.getProperty("incoming-dir") != null) { @@ -435,7 +440,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters } if (serviceProperties.getProperty("manual-intervention-dir") != null) { - manualInterventionDirectoryOrNull = new File(serviceProperties.getProperty("manual-intervention-dir").trim()); + manualInterventionDirectoryOrNull = + new File(serviceProperties.getProperty("manual-intervention-dir").trim()); } if (serviceProperties.getProperty("outgoing-dir") != null) { @@ -452,7 +458,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters } if (serviceProperties.getProperty("manual-intervention-regex") != null) { - manualInterventionRegex = Pattern.compile(serviceProperties.getProperty("manual-intervention-regex")); + manualInterventionRegex = + Pattern.compile(serviceProperties.getProperty("manual-intervention-regex")); } } @@ -477,7 +484,9 @@ public class Parameters implements ITimingParameters, IFileSysParameters } } catch (Exception ex) { - final String msg = "Could not load the service properties from resource '" + SERVICE_PROPERTIES_FILE + "'."; + final String msg = + "Could not load the service properties from resource '" + + SERVICE_PROPERTIES_FILE + "'."; operationLog.warn(msg, ex); throw new ConfigurationFailureException(msg, ex); } @@ -573,7 +582,8 @@ public class Parameters implements ITimingParameters, IFileSysParameters */ public FileStore getIncomingStore(IFileSysOperationsFactory factory) { - return createStore(incomingDirectory, INCOMING_KIND_DESC, incomingHost, treatIncomingAsRemote, factory); + return createStore(incomingDirectory, INCOMING_KIND_DESC, incomingHost, + treatIncomingAsRemote, factory); } /** @@ -647,45 +657,56 @@ public class Parameters implements ITimingParameters, IFileSysParameters { if (operationLog.isInfoEnabled()) { - operationLog.info(String.format("Incoming directory: '%s'.", incomingDirectory.getAbsolutePath())); + operationLog.info(String.format("Incoming directory: '%s'.", incomingDirectory + .getAbsolutePath())); if (null != incomingHost) { operationLog.info(String.format("Incoming host: '%s'.", incomingHost)); } - operationLog.info(String.format("Is incoming directory remote: %b.", treatIncomingAsRemote)); - operationLog.info(String.format("Buffer directory: '%s'.", bufferDirectory.getAbsolutePath())); - operationLog.info(String.format("Outgoing directory: '%s'.", outgoingDirectory.getAbsolutePath())); + operationLog.info(String.format("Is incoming directory remote: %b.", + treatIncomingAsRemote)); + operationLog.info(String.format("Buffer directory: '%s'.", bufferDirectory + .getAbsolutePath())); + operationLog.info(String.format("Outgoing directory: '%s'.", outgoingDirectory + .getAbsolutePath())); if (null != outgoingHost) { operationLog.info(String.format("Outgoing host: '%s'.", outgoingHost)); } if (null != tryGetManualInterventionDir()) { - operationLog.info(String.format("Manual interventions directory: '%s'.", tryGetManualInterventionDir() - .getAbsolutePath())); + operationLog.info(String.format("Manual interventions directory: '%s'.", + tryGetManualInterventionDir().getAbsolutePath())); } if (null != extraCopyDirectory) { - operationLog.info(String.format("Extra copy directory: '%s'.", extraCopyDirectory.getAbsolutePath())); + operationLog.info(String.format("Extra copy directory: '%s'.", extraCopyDirectory + .getAbsolutePath())); } - operationLog.info(String.format("Check intervall (external): %d s.", getCheckIntervalMillis() / 1000)); + operationLog.info(String.format("Check intervall (external): %d s.", + getCheckIntervalMillis() / 1000)); operationLog.info(String.format("Check intervall (internal): %d s.", getCheckIntervalInternalMillis() / 1000)); operationLog.info(String.format("Quiet period: %d s.", getQuietPeriodMillis() / 1000)); - operationLog.info(String.format("Inactivity (stall) period: %d s.", getInactivityPeriodMillis() / 1000)); + operationLog.info(String.format("Inactivity (stall) period: %d s.", + getInactivityPeriodMillis() / 1000)); operationLog.info(String.format("Intervall to wait after failure: %d s.", getIntervalToWaitAfterFailure() / 1000)); - operationLog.info(String.format("Maximum number of retries: %d.", getMaximalNumberOfRetries())); + operationLog.info(String.format("Maximum number of retries: %d.", + getMaximalNumberOfRetries())); if (tryGetCleansingRegex() != null) { - operationLog.info(String.format("Regular expression used for cleansing before moving: '%s'", + operationLog.info(String.format( + "Regular expression used for cleansing before moving: '%s'", tryGetCleansingRegex().pattern())); } if (tryGetManualInterventionRegex() != null) { - operationLog.info(String.format( - "Regular expression used for deciding whether a path needs manual intervention: '%s'", - tryGetManualInterventionRegex().pattern())); + operationLog + .info(String + .format( + "Regular expression used for deciding whether a path needs manual intervention: '%s'", + tryGetManualInterventionRegex().pattern())); } } } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/SelfTest.java b/datamover/source/java/ch/systemsx/cisd/datamover/SelfTest.java index c6a8739a89c..8b42f3df7de 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/SelfTest.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/SelfTest.java @@ -36,7 +36,8 @@ public class SelfTest { private static final long TIMEOUT_MILLIS = 3000L; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, SelfTest.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, SelfTest.class); static { @@ -58,7 +59,8 @@ public class SelfTest } } - private static void checkPathRecordsContainEachOther(IFileStore[] store) throws ConfigurationFailureException + private static void checkPathRecordsContainEachOther(IFileStore[] store) + throws ConfigurationFailureException { for (int i = 1; i < store.length; ++i) { @@ -66,8 +68,8 @@ public class SelfTest { if (store[i].isParentDirectory(store[j]) || store[j].isParentDirectory(store[i])) { - throw ConfigurationFailureException.fromTemplate("Directory '%s' and '%s' contain each other", - store[i], store[j]); + throw ConfigurationFailureException.fromTemplate( + "Directory '%s' and '%s' contain each other", store[i], store[j]); } } } @@ -91,13 +93,13 @@ public class SelfTest } } catch (HighLevelException e) { - operationLog.error(String.format("Self test failed: [%s: %s]\n", e.getClass().getSimpleName(), e - .getMessage())); + operationLog.error(String.format("Self test failed: [%s: %s]\n", e.getClass() + .getSimpleName(), e.getMessage())); throw e; } catch (RuntimeException e) { - operationLog.error(String.format("Self test failed: [%s: %s]\n", e.getClass().getSimpleName(), e - .getMessage()), e); + operationLog.error(String.format("Self test failed: [%s: %s]\n", e.getClass() + .getSimpleName(), e.getMessage()), e); throw e; } } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileStoreFactory.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileStoreFactory.java index 1e608bb5465..6ec4c3a9caf 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileStoreFactory.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileStoreFactory.java @@ -30,13 +30,15 @@ import ch.systemsx.cisd.datamover.filesystem.store.FileStoreRemoteMounted; public class FileStoreFactory { /** use when file store is on a local host */ - public static final FileStore createLocal(File path, String kind, IFileSysOperationsFactory factory) + public static final FileStore createLocal(File path, String kind, + IFileSysOperationsFactory factory) { return new FileStoreLocal(path, kind, factory); } /** use when file store is on a remote share mounted on local host */ - public static final FileStore createRemoteShare(File path, String kind, IFileSysOperationsFactory factory) + public static final FileStore createRemoteShare(File path, String kind, + IFileSysOperationsFactory factory) { return new FileStoreRemoteMounted(path, kind, factory); } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileSysOperationsFactory.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileSysOperationsFactory.java index a856e41ee80..c3b2bf8ebdf 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileSysOperationsFactory.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/FileSysOperationsFactory.java @@ -92,7 +92,8 @@ public class FileSysOperationsFactory implements IFileSysOperationsFactory // IPathImmutableCopier // - public final File tryCopy(final File file, final File destinationDirectory, final String nameOrNull) + public final File tryCopy(final File file, final File destinationDirectory, + final String nameOrNull) { final Status status = normalCopier.copy(file, destinationDirectory); if (StatusFlag.OK.equals(status.getFlag())) @@ -100,8 +101,8 @@ public class FileSysOperationsFactory implements IFileSysOperationsFactory return new File(destinationDirectory, file.getName()); } else { - notificationLog.error(String.format("Copy of '%s' to '%s' failed: %s.", file.getPath(), - destinationDirectory.getPath(), status)); + notificationLog.error(String.format("Copy of '%s' to '%s' failed: %s.", + file.getPath(), destinationDirectory.getPath(), status)); return null; } } @@ -114,8 +115,8 @@ public class FileSysOperationsFactory implements IFileSysOperationsFactory final File sshExecutable = findSshExecutable(parameters.getSshExecutable()); if (rsyncExecutable != null) { - return new RsyncCopier(rsyncExecutable, sshExecutable, requiresDeletionBeforeCreation, parameters - .isRsyncOverwrite()); + return new RsyncCopier(rsyncExecutable, sshExecutable, requiresDeletionBeforeCreation, + parameters.isRsyncOverwrite()); } else { throw new ConfigurationFailureException("Unable to find a copy engine."); @@ -137,8 +138,8 @@ public class FileSysOperationsFactory implements IFileSysOperationsFactory } if (rsyncExecutable != null && OSUtilities.executableExists(rsyncExecutable) == false) { - throw ConfigurationFailureException.fromTemplate("Cannot find rsync executable '%s'.", rsyncExecutable - .getAbsoluteFile()); + throw ConfigurationFailureException.fromTemplate("Cannot find rsync executable '%s'.", + rsyncExecutable.getAbsoluteFile()); } return rsyncExecutable; } @@ -162,8 +163,8 @@ public class FileSysOperationsFactory implements IFileSysOperationsFactory } if (sshExecutable != null && OSUtilities.executableExists(sshExecutable) == false) { - throw ConfigurationFailureException.fromTemplate("Cannot find ssh executable '%s'.", sshExecutable - .getAbsoluteFile()); + throw ConfigurationFailureException.fromTemplate("Cannot find ssh executable '%s'.", + sshExecutable.getAbsoluteFile()); } return sshExecutable; } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RemoteMonitoredMoverFactory.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RemoteMonitoredMoverFactory.java index 62a77853dc1..3da68cb365f 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RemoteMonitoredMoverFactory.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RemoteMonitoredMoverFactory.java @@ -36,11 +36,13 @@ public class RemoteMonitoredMoverFactory * @param destinationDirectory The directory to move paths to. * @param parameters The timing parameters used for monitoring and reporting stall situations. */ - public static final IStoreHandler create(IFileStore sourceDirectory, FileStore destinationDirectory, - ITimingParameters parameters) + public static final IStoreHandler create(IFileStore sourceDirectory, + FileStore destinationDirectory, ITimingParameters parameters) { final IStoreCopier copier = sourceDirectory.getCopier(destinationDirectory); - final CopyActivityMonitor monitor = new CopyActivityMonitor(destinationDirectory, copier, parameters); - return new RemotePathMover(sourceDirectory, destinationDirectory, copier, monitor, parameters); + final CopyActivityMonitor monitor = + new CopyActivityMonitor(destinationDirectory, copier, parameters); + return new RemotePathMover(sourceDirectory, destinationDirectory, copier, monitor, + parameters); } } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathMover.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathMover.java index 6d192cf2421..cd0bed08beb 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathMover.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathMover.java @@ -36,9 +36,11 @@ import ch.systemsx.cisd.datamover.filesystem.intf.IPathMover; */ class RetryingPathMover implements IPathMover { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, RetryingPathMover.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, RetryingPathMover.class); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, RetryingPathMover.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, RetryingPathMover.class); private final int maxRetriesOnFailure; @@ -63,18 +65,22 @@ class RetryingPathMover implements IPathMover assert prefixTemplate != null; assert sourcePath != null; - final String destinationPath = createDestinationPath(sourcePath, null, destinationDirectory, prefixTemplate); + final String destinationPath = + createDestinationPath(sourcePath, null, destinationDirectory, prefixTemplate); if (operationLog.isInfoEnabled()) { - operationLog.info(String.format("Moving path '%s' to '%s'", sourcePath.getPath(), destinationPath)); + operationLog.info(String.format("Moving path '%s' to '%s'", sourcePath.getPath(), + destinationPath)); } File destFile = new File(destinationPath); final FileRenamingProcess process = - new FileRenamingProcess(maxRetriesOnFailure, millisToSleepOnFailure, sourcePath, destFile); + new FileRenamingProcess(maxRetriesOnFailure, millisToSleepOnFailure, sourcePath, + destFile); new ProcessRunner(process); if (process.isRenamed() == false) { - notificationLog.error(String.format("Moving path '%s' to directory '%s' failed, giving up.", sourcePath, + notificationLog.error(String.format( + "Moving path '%s' to directory '%s' failed, giving up.", sourcePath, destinationDirectory)); return null; } else @@ -102,14 +108,14 @@ class RetryingPathMover implements IPathMover } else { - return destinationDirectory.getAbsolutePath() + File.separator + createPrefix(prefixTemplate) - + sourcePath.getName(); + return destinationDirectory.getAbsolutePath() + File.separator + + createPrefix(prefixTemplate) + sourcePath.getName(); } } private static String createPrefix(String prefixTemplate) { - return StringUtils.replace(prefixTemplate, "%t", DateFormatUtils.format(System.currentTimeMillis(), - "yyyyMMddHHmmss")); + return StringUtils.replace(prefixTemplate, "%t", DateFormatUtils.format(System + .currentTimeMillis(), "yyyyMMddHHmmss")); } } \ No newline at end of file diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathRemover.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathRemover.java index 8ee9658fc90..e3ae9b46dea 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathRemover.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/RetryingPathRemover.java @@ -36,9 +36,11 @@ import ch.systemsx.cisd.datamover.filesystem.intf.IPathRemover; */ final class RetryingPathRemover implements IPathRemover { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, RetryingPathMover.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, RetryingPathMover.class); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, RetryingPathMover.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, RetryingPathMover.class); private final int maxRetriesOnFailure; @@ -50,7 +52,8 @@ final class RetryingPathRemover implements IPathRemover this.millisToSleepOnFailure = millisToSleepOnFailure; } - private final static Status STATUS_FAILED_DELETION = new Status(StatusFlag.FATAL_ERROR, "Failed to remove path."); + private final static Status STATUS_FAILED_DELETION = + new Status(StatusFlag.FATAL_ERROR, "Failed to remove path."); public Status remove(File path) { @@ -72,11 +75,13 @@ final class RetryingPathRemover implements IPathRemover { if (path.exists() == false) { - operationLog.warn(String.format("Path '%s' doesn't exist, so it can't be removed.", path)); + operationLog.warn(String.format( + "Path '%s' doesn't exist, so it can't be removed.", path)); break; } ++failures; - operationLog.warn(String.format("Removing path '%s' failed (attempt %d).", path, failures)); + operationLog.warn(String.format("Removing path '%s' failed (attempt %d).", path, + failures)); if (failures >= maxRetriesOnFailure) { break; diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/FileStore.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/FileStore.java index 37a38bee507..caeda2847de 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/FileStore.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/FileStore.java @@ -44,7 +44,8 @@ public abstract class FileStore implements IFileStore protected final IFileSysOperationsFactory factory; - protected FileStore(File path, String hostOrNull, boolean remote, String kind, IFileSysOperationsFactory factory) + protected FileStore(File path, String hostOrNull, boolean remote, String kind, + IFileSysOperationsFactory factory) { assert path != null; assert kind != null; @@ -144,8 +145,8 @@ public abstract class FileStore implements IFileStore return file.getCanonicalPath() + File.separator; } catch (IOException e) { - throw EnvironmentFailureException.fromTemplate(e, "Cannot determine canonical form of path '%s'", file - .getPath()); + throw EnvironmentFailureException.fromTemplate(e, + "Cannot determine canonical form of path '%s'", file.getPath()); } } @@ -156,8 +157,9 @@ public abstract class FileStore implements IFileStore { FileStore fileStore = (FileStore) obj; boolean sameHost = - (hostOrNull == null ? fileStore.hostOrNull == null : fileStore.hostOrNull != null - && hostOrNull.equals(fileStore.hostOrNull)); + (hostOrNull == null ? fileStore.hostOrNull == null + : fileStore.hostOrNull != null + && hostOrNull.equals(fileStore.hostOrNull)); return sameHost && kind.equals(fileStore.kind) && path.equals(fileStore.path); } else { @@ -232,6 +234,7 @@ public abstract class FileStore implements IFileStore public abstract boolean createNewFile(StoreItem item); - public abstract File tryMoveLocal(StoreItem sourceItem, File destinationDir, String newFilePrefix); + public abstract File tryMoveLocal(StoreItem sourceItem, File destinationDir, + String newFilePrefix); } } \ No newline at end of file diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IExtendedFileStore.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IExtendedFileStore.java index 2d8d199156f..09f4b34daf5 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IExtendedFileStore.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IExtendedFileStore.java @@ -22,7 +22,7 @@ import ch.systemsx.cisd.common.utilities.StoreItem; /** * An {@link IFileStore} with additional capabilites. - * + * * @author Bernd Rinn */ public interface IExtendedFileStore extends IFileStore diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileStore.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileStore.java index 3a22ec57191..89495158338 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileStore.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileStore.java @@ -22,7 +22,7 @@ import ch.systemsx.cisd.common.utilities.StoreItem; /** * An abstraction for a file store. - * + * * @author Bernd Rinn */ public interface IFileStore diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileSysOperationsFactory.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileSysOperationsFactory.java index 71d7c436a69..e7fe4bb220a 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileSysOperationsFactory.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IFileSysOperationsFactory.java @@ -17,7 +17,6 @@ package ch.systemsx.cisd.datamover.filesystem.intf; import ch.systemsx.cisd.common.utilities.IPathImmutableCopier; - /** * A role that provides access to the roles which perform file system operations. * diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IPathMover.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IPathMover.java index 3f01f5e5944..79717330f27 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IPathMover.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IPathMover.java @@ -25,7 +25,7 @@ import java.io.File; */ public interface IPathMover { - + /** * Moves source path (file or directory) to destination directory, putting <var>prefixTemplate</var> in front of * its name, where any occurrence of '%t' in the template is replaced with the current time stamp. @@ -36,6 +36,5 @@ public interface IPathMover * Moves source path (file or directory) to destination directory. */ public File tryMove(File sourcePath, File destinationDir); - } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IRecoverableTimerTaskFactory.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IRecoverableTimerTaskFactory.java index bbdbaa1441f..69dac2d2ef1 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IRecoverableTimerTaskFactory.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/intf/IRecoverableTimerTaskFactory.java @@ -20,7 +20,7 @@ import java.util.TimerTask; /** * A factory for creating {@link TimerTask}s that, when run, perform a recovery operation on the data mover. - * + * * @author Bernd Rinn */ public interface IRecoverableTimerTaskFactory diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitor.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitor.java index e9c1b9db1e8..6a34d041eb6 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitor.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitor.java @@ -43,9 +43,11 @@ import ch.systemsx.cisd.datamover.intf.ITimingParameters; public class CopyActivityMonitor { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, CopyActivityMonitor.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, CopyActivityMonitor.class); - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, CopyActivityMonitor.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, CopyActivityMonitor.class); private final IFileStore destinationStore; @@ -77,7 +79,8 @@ public class CopyActivityMonitor * process gets stuck. * @param timingParameters The {@link ITimingParameters} to get the check interval and the inactivity period from. */ - public CopyActivityMonitor(IFileStore destinationStore, ITerminable copyProcess, ITimingParameters timingParameters) + public CopyActivityMonitor(IFileStore destinationStore, ITerminable copyProcess, + ITimingParameters timingParameters) { assert destinationStore != null; assert copyProcess != null; @@ -129,7 +132,8 @@ public class CopyActivityMonitor private final class ActivityMonitoringTimerTask extends TimerTask { - private static final String TERMINATION_LOG_TEMPLATE = "Terminating %s due to a lack of activity."; + private static final String TERMINATION_LOG_TEMPLATE = + "Terminating %s due to a lack of activity."; private static final String INACTIVITY_REPORT_TEMPLATE = "No progress on copying '%s' to '%s' for %f seconds - network connection might be stalled."; @@ -164,12 +168,14 @@ public class CopyActivityMonitor { if (operationLog.isTraceEnabled()) { - operationLog.trace(String.format("Asking for last change time of '%s' inside '%s'.", - itemToBeCopied, destinationStore)); + operationLog.trace(String.format( + "Asking for last change time of '%s' inside '%s'.", itemToBeCopied, + destinationStore)); } if (destinationStore.exists(itemToBeCopied) == false) { - operationLog.warn(String.format("File or directory '%s' inside '%s' does not (yet?) exist.", + operationLog.warn(String.format( + "File or directory '%s' inside '%s' does not (yet?) exist.", itemToBeCopied, destinationStore)); return; } @@ -177,27 +183,33 @@ public class CopyActivityMonitor lastChanged(destinationStore, itemToBeCopied, monitoredItemLastChanged); if (operationLog.isTraceEnabled()) { - operationLog.trace(String.format( - "Checker reported last changed time of '%s' inside '%s' to be %3$tF %3$tT.", - itemToBeCopied, destinationStore, lastChangedAsFoundByPathChecker)); + operationLog + .trace(String + .format( + "Checker reported last changed time of '%s' inside '%s' to be %3$tF %3$tT.", + itemToBeCopied, destinationStore, + lastChangedAsFoundByPathChecker)); } // This catches the case where since the last check copying a files has been finished (and consequently // the "last changed" time has been set to that of the source file), but copying of the next file has // not yet been started. - final long lastChanged = Math.max(lastChangedAsFoundByPathChecker, monitoredItemLastChanged); + final long lastChanged = + Math.max(lastChangedAsFoundByPathChecker, monitoredItemLastChanged); final long now = System.currentTimeMillis(); if (lastChanged > now) // That can happen if the system clock of the data producer is screwed up. { - machineLog.error(String.format("Found \"last changed time\" in the future (%1$tF %1$tT), " - + "check system clock of data producer.", lastChanged)); + machineLog.error(String.format( + "Found \"last changed time\" in the future (%1$tF %1$tT), " + + "check system clock of data producer.", lastChanged)); } monitoredItemLastChanged = lastChanged; final long noProgressSinceMillis = now - lastChanged; if (noProgressSinceMillis > inactivityPeriodMillis) { - machineLog.error(String.format(INACTIVITY_REPORT_TEMPLATE, itemToBeCopied, destinationStore, - noProgressSinceMillis / 1000.0f)); - operationLog.warn(String.format(TERMINATION_LOG_TEMPLATE, terminable.getClass().getName())); + machineLog.error(String.format(INACTIVITY_REPORT_TEMPLATE, itemToBeCopied, + destinationStore, noProgressSinceMillis / 1000.0f)); + operationLog.warn(String.format(TERMINATION_LOG_TEMPLATE, terminable.getClass() + .getName())); terminable.terminate(); stop(); } @@ -227,11 +239,12 @@ public class CopyActivityMonitor minusSafetyMargin(inactivityPeriodMillis))); final long timeoutMillis = Math.min(checkIntervallMillis * 3, inactivityPeriodMillis); final Long lastChanged = - ConcurrencyUtilities.tryGetResult(lastChangedFuture, timeoutMillis, simpleMachineLog, - "Check for recent paths"); + ConcurrencyUtilities.tryGetResult(lastChangedFuture, timeoutMillis, + simpleMachineLog, "Check for recent paths"); if (lastChanged == null) { - operationLog.error(String.format("Could not determine \"last changed time\" of %s: time out.", item)); + operationLog.error(String.format( + "Could not determine \"last changed time\" of %s: time out.", item)); return lastLastChanged; } return lastChanged; @@ -251,24 +264,30 @@ public class CopyActivityMonitor { if (machineLog.isTraceEnabled()) { - machineLog.trace("Starting quick check for recent paths on '" + item + "'."); + machineLog.trace("Starting quick check for recent paths on '" + item + + "'."); } try { - final long lastChanged = store.lastChangedRelative(item, stopWhenYoungerThan); + final long lastChanged = + store.lastChangedRelative(item, stopWhenYoungerThan); if (machineLog.isTraceEnabled()) { - machineLog.trace(String.format( - "Finishing quick check for recent paths on '%s', found to be %2$tF %2$tT.", - item, lastChanged)); + machineLog + .trace(String + .format( + "Finishing quick check for recent paths on '%s', found to be %2$tF %2$tT.", + item, lastChanged)); } return lastChanged; } catch (RuntimeException ex) { if (machineLog.isTraceEnabled()) { - final Throwable th = (ex instanceof CheckedExceptionTunnel) ? ex.getCause() : ex; - machineLog.trace("Failed on quick check for recent paths on '" + item + "'.", th); + final Throwable th = + (ex instanceof CheckedExceptionTunnel) ? ex.getCause() : ex; + machineLog.trace("Failed on quick check for recent paths on '" + + item + "'.", th); } throw ex; } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/RemotePathMover.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/RemotePathMover.java index cdf3814952e..aa7e6defedc 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/RemotePathMover.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/RemotePathMover.java @@ -45,29 +45,37 @@ public final class RemotePathMover implements IStoreHandler private static final String START_COPYING_PATH_TEMPLATE = "Start copying path '%s' to '%s'."; - private static final String START_COPYING_PATH_RETRY_TEMPLATE = "Start copying path '%s' to '%s' [retry: %d]."; + private static final String START_COPYING_PATH_RETRY_TEMPLATE = + "Start copying path '%s' to '%s' [retry: %d]."; - private static final String FINISH_COPYING_PATH_TEMPLATE = "Finish copying path '%s' to '%s' [time: %.2f s]."; + private static final String FINISH_COPYING_PATH_TEMPLATE = + "Finish copying path '%s' to '%s' [time: %.2f s]."; private static final String REMOVED_PATH_TEMPLATE = "Removed path '%s'."; - private static final String COPYING_PATH_TO_REMOTE_FAILED = "Copying path '%s' to remote directory '%s' failed: %s"; + private static final String COPYING_PATH_TO_REMOTE_FAILED = + "Copying path '%s' to remote directory '%s' failed: %s"; private static final String MOVING_PATH_TO_REMOTE_FAILED_TEMPLATE = "Moving path '%s' to remote directory '%s' failed."; - private static final String REMOVING_LOCAL_PATH_FAILED_TEMPLATE = "Removing local path '%s' failed (%s)."; + private static final String REMOVING_LOCAL_PATH_FAILED_TEMPLATE = + "Removing local path '%s' failed (%s)."; - private static final String FAILED_TO_CREATE_FILE_TEMPLATE = "Failed to create file '%s' in '%s'"; + private static final String FAILED_TO_CREATE_FILE_TEMPLATE = + "Failed to create file '%s' in '%s'"; private static final String FAILED_TO_COPY_FILE_TO_REMOTE_TEMPLATE = "Failed to copy file '%s' from '%s' to remote (%s)"; - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, RemotePathMover.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, RemotePathMover.class); - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, RemotePathMover.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, RemotePathMover.class); - private static final Logger notificationLog = LogFactory.getLogger(LogCategory.NOTIFY, RemotePathMover.class); + private static final Logger notificationLog = + LogFactory.getLogger(LogCategory.NOTIFY, RemotePathMover.class); private final IFileStore sourceDirectory; @@ -89,19 +97,21 @@ public final class RemotePathMover implements IStoreHandler * @param copier Copies items from source to destination * @param monitor The activity monitor to inform about actions. * @param timingParameters The timing parameters used for monitoring and reporting stall situations. - * * @throws ConfigurationFailureException If the destination directory is not fully accessible. */ - public RemotePathMover(IFileStore sourceDirectory, IFileStore destinationDirectory, IStoreCopier copier, - CopyActivityMonitor monitor, ITimingParameters timingParameters) throws ConfigurationFailureException + public RemotePathMover(IFileStore sourceDirectory, IFileStore destinationDirectory, + IStoreCopier copier, CopyActivityMonitor monitor, ITimingParameters timingParameters) + throws ConfigurationFailureException { assert sourceDirectory != null; assert destinationDirectory != null; assert monitor != null; assert timingParameters != null; - assert sourceDirectory.tryAsExtended() != null || destinationDirectory.tryAsExtended() != null; + assert sourceDirectory.tryAsExtended() != null + || destinationDirectory.tryAsExtended() != null; - final String errorMsg = destinationDirectory.tryCheckDirectoryFullyAccessible(TIMEOUT_DESTINATION_MILLIS); + final String errorMsg = + destinationDirectory.tryCheckDirectoryFullyAccessible(TIMEOUT_DESTINATION_MILLIS); if (StringUtils.isNotBlank(errorMsg)) { throw new ConfigurationFailureException(errorMsg); @@ -124,9 +134,11 @@ public final class RemotePathMover implements IStoreHandler // This is a recovery situation: we have been interrupted removing the path and now finish the job. if (operationLog.isInfoEnabled()) { - operationLog.info(String.format( - "Detected recovery situation: '%s' has been interrupted in deletion phase, finishing up.", - getSrcPath(item))); + operationLog + .info(String + .format( + "Detected recovery situation: '%s' has been interrupted in deletion phase, finishing up.", + getSrcPath(item))); } removeAndMark(item); return; @@ -138,12 +150,12 @@ public final class RemotePathMover implements IStoreHandler { if (tryCount > 0) // This is a retry { - operationLog.info(String.format(START_COPYING_PATH_RETRY_TEMPLATE, getSrcPath(item), - destinationDirectory, tryCount)); + operationLog.info(String.format(START_COPYING_PATH_RETRY_TEMPLATE, + getSrcPath(item), destinationDirectory, tryCount)); } else { - operationLog.info(String - .format(START_COPYING_PATH_TEMPLATE, getSrcPath(item), destinationDirectory)); + operationLog.info(String.format(START_COPYING_PATH_TEMPLATE, getSrcPath(item), + destinationDirectory)); } } // TODO 2008-03-17, Bernd Rinn: There needs to be a limit for how often we take this exit without sending @@ -166,8 +178,8 @@ public final class RemotePathMover implements IStoreHandler return; } else { - operationLog.warn(String.format(COPYING_PATH_TO_REMOTE_FAILED, getSrcPath(item), destinationDirectory, - copyStatus)); + operationLog.warn(String.format(COPYING_PATH_TO_REMOTE_FAILED, getSrcPath(item), + destinationDirectory, copyStatus)); if (StatusFlag.FATAL_ERROR.equals(copyStatus.getFlag())) { break; @@ -188,8 +200,8 @@ public final class RemotePathMover implements IStoreHandler } } while (true); - notificationLog.error(String.format(MOVING_PATH_TO_REMOTE_FAILED_TEMPLATE, getSrcPath(item), - destinationDirectory)); + notificationLog.error(String.format(MOVING_PATH_TO_REMOTE_FAILED_TEMPLATE, + getSrcPath(item), destinationDirectory)); } private Status copyAndMonitor(StoreItem item) @@ -208,7 +220,8 @@ public final class RemotePathMover implements IStoreHandler private boolean checkTargetAvailable() { - final String msg = destinationDirectory.tryCheckDirectoryFullyAccessible(TIMEOUT_DESTINATION_MILLIS); + final String msg = + destinationDirectory.tryCheckDirectoryFullyAccessible(TIMEOUT_DESTINATION_MILLIS); if (msg != null) { machineLog.error(msg); @@ -225,8 +238,8 @@ public final class RemotePathMover implements IStoreHandler if (Status.OK.equals(removalStatus) == false) { - notificationLog.error(String.format(REMOVING_LOCAL_PATH_FAILED_TEMPLATE, getSrcPath(sourceItem), - removalStatus)); + notificationLog.error(String.format(REMOVING_LOCAL_PATH_FAILED_TEMPLATE, + getSrcPath(sourceItem), removalStatus)); } else if (operationLog.isInfoEnabled()) { operationLog.info(String.format(REMOVED_PATH_TEMPLATE, getSrcPath(sourceItem))); @@ -235,19 +248,22 @@ public final class RemotePathMover implements IStoreHandler private boolean isDeletionInProgress(StoreItem item) { - StoreItem markDeletionInProgressMarkerFile = MarkerFile.createDeletionInProgressMarker(item); + StoreItem markDeletionInProgressMarkerFile = + MarkerFile.createDeletionInProgressMarker(item); return getDeletionMarkerStore().exists(markDeletionInProgressMarkerFile); } private StoreItem tryMarkAsDeletionInProgress(StoreItem item) { - final StoreItem markDeletionInProgressMarkerFile = MarkerFile.createDeletionInProgressMarker(item); + final StoreItem markDeletionInProgressMarkerFile = + MarkerFile.createDeletionInProgressMarker(item); if (createFileInside(getDeletionMarkerStore(), markDeletionInProgressMarkerFile)) { return markDeletionInProgressMarkerFile; } else { - machineLog.error(String.format("Cannot create deletion-in-progress marker file for path '%s' [%s]", item, + machineLog.error(String.format( + "Cannot create deletion-in-progress marker file for path '%s' [%s]", item, markDeletionInProgressMarkerFile)); return null; } @@ -260,8 +276,8 @@ public final class RemotePathMover implements IStoreHandler final Status status = getDeletionMarkerStore().delete(markerOrNull); if (status.equals(Status.OK) == false) { - machineLog.error(String.format("Cannot remove marker file '%s'", getPath(destinationDirectory, - markerOrNull))); + machineLog.error(String.format("Cannot remove marker file '%s'", getPath( + destinationDirectory, markerOrNull))); } } } @@ -295,7 +311,8 @@ public final class RemotePathMover implements IStoreHandler } } - private boolean markOnSourceLocalAndCopyToRemoteDestination(IExtendedFileStore sourceFileStore, StoreItem markerFile) + private boolean markOnSourceLocalAndCopyToRemoteDestination(IExtendedFileStore sourceFileStore, + StoreItem markerFile) { try { @@ -309,8 +326,8 @@ public final class RemotePathMover implements IStoreHandler return true; } else { - machineLog.error(String.format(FAILED_TO_COPY_FILE_TO_REMOTE_TEMPLATE, markerFile, sourceFileStore, - copyStatus.toString())); + machineLog.error(String.format(FAILED_TO_COPY_FILE_TO_REMOTE_TEMPLATE, markerFile, + sourceFileStore, copyStatus.toString())); return false; } } finally diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopier.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopier.java index 72e107ce370..b6b274de944 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopier.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopier.java @@ -51,22 +51,26 @@ public class RsyncCopier implements IPathCopier /** * The {@link Status} returned if the process was terminated by {@link Process#destroy()}. */ - protected static final Status TERMINATED_STATUS = new Status(StatusFlag.RETRIABLE_ERROR, "Process was terminated."); + protected static final Status TERMINATED_STATUS = + new Status(StatusFlag.RETRIABLE_ERROR, "Process was terminated."); - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, RsyncCopier.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, RsyncCopier.class); - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, RsyncCopier.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, RsyncCopier.class); - private static final Status INTERRUPTED_STATUS = new Status(StatusFlag.RETRIABLE_ERROR, "Process was interrupted."); + private static final Status INTERRUPTED_STATUS = + new Status(StatusFlag.RETRIABLE_ERROR, "Process was interrupted."); private final String rsyncExecutable; private final RsyncVersion rsyncVersion; - + private final String sshExecutable; private final List<String> additionalCmdLineFlags; - + private final boolean overwrite; /** @@ -91,8 +95,9 @@ public class RsyncCopier implements IPathCopier * directories on the remote side will be deleted before starting the copy process (no overwriting of * paths). */ - public RsyncCopier(File rsyncExecutable, File sshExecutableOrNull, - boolean destinationDirectoryRequiresDeletionBeforeCreation, boolean overwrite, String... cmdLineFlags) + public RsyncCopier(File rsyncExecutable, File sshExecutableOrNull, + boolean destinationDirectoryRequiresDeletionBeforeCreation, boolean overwrite, + String... cmdLineFlags) { assert rsyncExecutable != null && rsyncExecutable.exists(); assert sshExecutableOrNull == null || rsyncExecutable.exists(); @@ -100,7 +105,8 @@ public class RsyncCopier implements IPathCopier this.rsyncExecutable = rsyncExecutable.getAbsolutePath(); this.rsyncVersion = RsyncVersionChecker.getVersion(rsyncExecutable.getAbsolutePath()); this.sshExecutable = (sshExecutableOrNull != null) ? sshExecutableOrNull.getPath() : null; - this.destinationDirectoryRequiresDeletionBeforeCreation = destinationDirectoryRequiresDeletionBeforeCreation; + this.destinationDirectoryRequiresDeletionBeforeCreation = + destinationDirectoryRequiresDeletionBeforeCreation; this.copyProcessReference = new AtomicReference<Process>(null); this.overwrite = overwrite; if (cmdLineFlags.length > 0) @@ -111,17 +117,18 @@ public class RsyncCopier implements IPathCopier this.additionalCmdLineFlags = null; } } - + private boolean rsyncSupportsAppend() { assert rsyncVersion != null; - + return rsyncVersion.isNewerOrEqual(2, 6, 7); } - + private boolean isOverwriteMode() { - return overwrite || destinationDirectoryRequiresDeletionBeforeCreation || (rsyncSupportsAppend() == false); + return overwrite || destinationDirectoryRequiresDeletionBeforeCreation + || (rsyncSupportsAppend() == false); } public Status copy(File sourcePath, File destinationDirectory) @@ -151,8 +158,8 @@ public class RsyncCopier implements IPathCopier try { final ProcessBuilder copyProcessBuilder = - new ProcessBuilder(createCommandLine(sourcePath, sourceHostOrNull, destinationDirectory, - destinationHostOrNull)); + new ProcessBuilder(createCommandLine(sourcePath, sourceHostOrNull, + destinationDirectory, destinationHostOrNull)); copyProcessBuilder.redirectErrorStream(true); if (operationLog.isDebugEnabled()) { @@ -167,7 +174,8 @@ public class RsyncCopier implements IPathCopier } catch (IOException e) { machineLog.error(String.format("Cannot execute rsync binary %s", rsyncExecutable), e); - return new Status(StatusFlag.FATAL_ERROR, String.format("ProcessBuilder: %s", e.getMessage())); + return new Status(StatusFlag.FATAL_ERROR, String.format("ProcessBuilder: %s", e + .getMessage())); } catch (InterruptedException e) { // Shouldn't happen because this is called in a timer, anyway, it's just another error condition. @@ -189,11 +197,12 @@ public class RsyncCopier implements IPathCopier } } - private List<String> createCommandLine(File sourcePath, String sourceHost, File destinationDirectory, - String destinationHost) + private List<String> createCommandLine(File sourcePath, String sourceHost, + File destinationDirectory, String destinationHost) { assert sourcePath != null && (sourceHost != null || sourcePath.exists()); - assert destinationDirectory != null && (destinationHost != null || destinationDirectory.isDirectory()); + assert destinationDirectory != null + && (destinationHost != null || destinationDirectory.isDirectory()); assert (destinationHost != null && sshExecutable != null) || (destinationHost == null); assert (sourceHost != null && sshExecutable != null) || (sourceHost == null); @@ -286,8 +295,10 @@ public class RsyncCopier implements IPathCopier private static void logRsyncExitValue(final Process copyProcess) { final int exitValue = copyProcess.exitValue(); - final List<String> processOutput = ProcessExecutionHelper.readProcessOutputLines(copyProcess, machineLog); - ProcessExecutionHelper.logProcessExecution("rsync", exitValue, processOutput, operationLog, machineLog); + final List<String> processOutput = + ProcessExecutionHelper.readProcessOutputLines(copyProcess, machineLog); + ProcessExecutionHelper.logProcessExecution("rsync", exitValue, processOutput, operationLog, + machineLog); } /** @@ -322,29 +333,33 @@ public class RsyncCopier implements IPathCopier { if (OSUtilities.executableExists(rsyncExecutable)) { - throw new ConfigurationFailureException(String.format("Rsync executable '%s' is invalid.", - rsyncExecutable)); + throw new ConfigurationFailureException(String.format( + "Rsync executable '%s' is invalid.", rsyncExecutable)); } else { - throw new ConfigurationFailureException(String.format("Rsync executable '%s' does not exist.", - rsyncExecutable)); + throw new ConfigurationFailureException(String.format( + "Rsync executable '%s' does not exist.", rsyncExecutable)); } } if (rsyncVersion.isNewerOrEqual(2, 6, 0) == false) { throw new ConfigurationFailureException(String.format( - "Rsync executable '%s' is too old (required: 2.6.0, found: %s)", rsyncExecutable, rsyncVersion - .getVersionString())); + "Rsync executable '%s' is too old (required: 2.6.0, found: %s)", + rsyncExecutable, rsyncVersion.getVersionString())); } if (machineLog.isInfoEnabled()) { - machineLog.info(String.format("Using rsync executable '%s', version %s, mode: %s", rsyncExecutable, - rsyncVersion.getVersionString(), (isOverwriteMode() ? "overwrite" : "append"))); + machineLog.info(String.format("Using rsync executable '%s', version %s, mode: %s", + rsyncExecutable, rsyncVersion.getVersionString(), + (isOverwriteMode() ? "overwrite" : "append"))); } if (rsyncVersion.isRsyncPreReleaseVersion()) { - machineLog.warn(String.format("The rsync executable '%s' is a pre-release version. It is not recommended " - + "to use such a version in a production environment.", rsyncExecutable)); + machineLog.warn(String + .format( + "The rsync executable '%s' is a pre-release version. It is not recommended " + + "to use such a version in a production environment.", + rsyncExecutable)); } } @@ -355,7 +370,8 @@ public class RsyncCopier implements IPathCopier final String destination = buildPath(destinationHost, destinationDirectory, true); final ProcessBuilder listProcessBuilder = - new ProcessBuilder(rsyncExecutable, "--rsh", getSshExecutableArgument(sshExecutable), destination) + new ProcessBuilder(rsyncExecutable, "--rsh", + getSshExecutableArgument(sshExecutable), destination) .redirectErrorStream(true); if (operationLog.isDebugEnabled()) { diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncVersionChecker.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncVersionChecker.java index ea829269ab0..8ab9621ba03 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncVersionChecker.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncVersionChecker.java @@ -34,9 +34,11 @@ import ch.systemsx.cisd.common.process.ProcessResult; final class RsyncVersionChecker { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, RsyncVersionChecker.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, RsyncVersionChecker.class); - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, RsyncVersionChecker.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, RsyncVersionChecker.class); /** * The class holding the version information about an <code>rsync</code> binary. @@ -69,8 +71,8 @@ final class RsyncVersionChecker */ private final boolean rsyncPreReleaseVersion; - private RsyncVersion(String rsyncVersion, int rsyncMajorVersion, int rsyncMinorVersion, int rsyncPatchVersion, - boolean rsyncPreReleaseVersion) + private RsyncVersion(String rsyncVersion, int rsyncMajorVersion, int rsyncMinorVersion, + int rsyncPatchVersion, boolean rsyncPreReleaseVersion) { this.rsyncVersion = rsyncVersion; this.rsyncMajorVersion = rsyncMajorVersion; @@ -110,7 +112,7 @@ final class RsyncVersionChecker { return rsyncPatchVersion; } - + /** * @return <code>true</code>, if this version is a pre-release version. */ @@ -120,7 +122,7 @@ final class RsyncVersionChecker } /** - * @return <code>true</code>, if this version is newer or as new the minimal version specified. + * @return <code>true</code>, if this version is newer or as new the minimal version specified. */ public boolean isNewerOrEqual(int minMajorVerson, int minMinorVersion, int minPatchLevel) { @@ -188,8 +190,8 @@ final class RsyncVersionChecker } } - return new RsyncVersion(rsyncVersion, rsyncMajorVersion, rsyncMinorVersion, rsyncPatchVersion, - preReleaseVersion); + return new RsyncVersion(rsyncVersion, rsyncMajorVersion, rsyncMinorVersion, + rsyncPatchVersion, preReleaseVersion); } private static String tryGetRsyncVersion(String rsyncExecutableToCheck) diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/store/FileStoreLocal.java b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/store/FileStoreLocal.java index dedb0ab2512..b2ae61feab8 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/store/FileStoreLocal.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/filesystem/store/FileStoreLocal.java @@ -42,7 +42,8 @@ import ch.systemsx.cisd.datamover.filesystem.intf.FileStore.ExtendedFileStore; */ public class FileStoreLocal extends ExtendedFileStore { - private static final Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, FileStoreLocal.class); + private static final Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, FileStoreLocal.class); private final IPathMover mover; @@ -72,11 +73,12 @@ public class FileStoreLocal extends ExtendedFileStore { return FileUtilities.lastChanged(getChildFile(item), true, stopWhenFindYounger); } - + @Override public long lastChangedRelative(StoreItem item, long stopWhenFindYoungerRelative) { - return FileUtilities.lastChangedRelative(getChildFile(item), true, stopWhenFindYoungerRelative); + return FileUtilities.lastChangedRelative(getChildFile(item), true, + stopWhenFindYoungerRelative); } @Override @@ -85,8 +87,9 @@ public class FileStoreLocal extends ExtendedFileStore final boolean available = FileUtilities.isAvailable(getPath(), timeOutMillis); if (available == false) { - return String.format("Path '%s' which is supposed to be a %s directory is not available.", getPath(), - getDescription()); + return String.format( + "Path '%s' which is supposed to be a %s directory is not available.", + getPath(), getDescription()); } return FileUtilities.checkDirectoryFullyAccessible(getPath(), getDescription()); } @@ -95,7 +98,8 @@ public class FileStoreLocal extends ExtendedFileStore public IStoreCopier getCopier(FileStore destinationDirectory) { boolean requiresDeletion = false; - final IStoreCopier simpleCopier = constructStoreCopier(destinationDirectory, requiresDeletion); + final IStoreCopier simpleCopier = + constructStoreCopier(destinationDirectory, requiresDeletion); if (requiresDeletionBeforeCreation(destinationDirectory, simpleCopier)) { requiresDeletion = true; @@ -176,7 +180,8 @@ public class FileStoreLocal extends ExtendedFileStore * @return <code>true</code> if the <var>simpleCopier</var> on the file system where the * <var>destinationDirectory</var> resides requires deleting an existing file before it can be overwritten. */ - protected boolean requiresDeletionBeforeCreation(IFileStore destinationDirectory, final IStoreCopier simpleCopier) + protected boolean requiresDeletionBeforeCreation(IFileStore destinationDirectory, + final IStoreCopier simpleCopier) { StoreItem item = MarkerFile.createRequiresDeletionBeforeCreationMarker(); createNewFile(item); @@ -210,18 +215,22 @@ public class FileStoreLocal extends ExtendedFileStore } } - private static void logCopierOverwriteState(IFileStore destinationDirectory, boolean requiresDeletion) + private static void logCopierOverwriteState(IFileStore destinationDirectory, + boolean requiresDeletion) { if (machineLog.isInfoEnabled()) { if (requiresDeletion) { - machineLog.info(String.format( - "Copier on directory '%s' requires deletion before creation of existing files.", - destinationDirectory)); + machineLog + .info(String + .format( + "Copier on directory '%s' requires deletion before creation of existing files.", + destinationDirectory)); } else { - machineLog.info(String.format("Copier on directory '%s' works with overwriting existing files.", + machineLog.info(String.format( + "Copier on directory '%s' works with overwriting existing files.", destinationDirectory)); } } diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/utils/LocalBufferDirs.java b/datamover/source/java/ch/systemsx/cisd/datamover/utils/LocalBufferDirs.java index 36cca1ee348..204429aa5f7 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/utils/LocalBufferDirs.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/utils/LocalBufferDirs.java @@ -35,8 +35,8 @@ public class LocalBufferDirs private final File tempDir; - public LocalBufferDirs(File bufferDir, String copyInProgressDirName, String copyCompleteDirName, - String readyToMoveDirName, String tempDirName) + public LocalBufferDirs(File bufferDir, String copyInProgressDirName, + String copyCompleteDirName, String readyToMoveDirName, String tempDirName) { this.copyInProgressDir = ensureDirectoryExists(bufferDir, copyInProgressDirName); this.copyCompleteDir = ensureDirectoryExists(bufferDir, copyCompleteDirName); diff --git a/datamover/source/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilter.java b/datamover/source/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilter.java index a978d026c18..34bc833fe3c 100644 --- a/datamover/source/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilter.java +++ b/datamover/source/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilter.java @@ -51,9 +51,11 @@ public class QuietPeriodFileFilter private static final String TIME_FORMAT_TEMPLATE = "%#$tY-%#$tm-%#$td %#$tH:%#$tM:%#$tS"; - private final static Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, QuietPeriodFileFilter.class); + private final static Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, QuietPeriodFileFilter.class); - private final static Logger machineLog = LogFactory.getLogger(LogCategory.MACHINE, QuietPeriodFileFilter.class); + private final static Logger machineLog = + LogFactory.getLogger(LogCategory.MACHINE, QuietPeriodFileFilter.class); private final long quietPeriodMillis; @@ -205,12 +207,13 @@ public class QuietPeriodFileFilter } // @Private - static String getClockProblemLogMessage(final String pathname, final long oldCheck, final long oldLastChanged, - final long newCheck, final long newLastChanged) + static String getClockProblemLogMessage(final String pathname, final long oldCheck, + final long oldLastChanged, final long newCheck, final long newLastChanged) { - return String.format("Last modification time of path '%1$s' jumped back: check at " + getTimeFormat(2) - + " -> last modification time " + getTimeFormat(3) + ", check at later time " + getTimeFormat(4) - + " -> last modification time " + getTimeFormat(5) + " (which is %6$d ms younger)", pathname, oldCheck, + return String.format("Last modification time of path '%1$s' jumped back: check at " + + getTimeFormat(2) + " -> last modification time " + getTimeFormat(3) + + ", check at later time " + getTimeFormat(4) + " -> last modification time " + + getTimeFormat(5) + " (which is %6$d ms younger)", pathname, oldCheck, oldLastChanged, newCheck, newLastChanged, (oldLastChanged - newLastChanged)); } diff --git a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/MainTest.java b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/MainTest.java index c84356861fe..edd44429965 100644 --- a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/MainTest.java +++ b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/MainTest.java @@ -60,9 +60,11 @@ public class MainTest private static final int QUIET_PERIOD = 2; - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, MainTest.class.getSimpleName()); + private static final File workingDirectory = + new File(unitTestRootDirectory, MainTest.class.getSimpleName()); @BeforeClass(alwaysRun = true) public void init() @@ -121,8 +123,8 @@ public class MainTest // ----------------- higher level assertions - private static void assertSampleStructMovedWithCopy(ExternalDirs dirs, LocalBufferDirs bufferDirs, - FileStructEngine structEngine) throws IOException + private static void assertSampleStructMovedWithCopy(ExternalDirs dirs, + LocalBufferDirs bufferDirs, FileStructEngine structEngine) throws IOException { assertSampleStructMoved(dirs, bufferDirs, structEngine); structEngine.assertSampleStructureExists(dirs.extraCopy); @@ -135,15 +137,15 @@ public class MainTest assertSampleStructInOutgoing(dirs, structEngine); } - private static void assertSampleStructInOutgoing(ExternalDirs dirs, FileStructEngine structEngine) - throws IOException + private static void assertSampleStructInOutgoing(ExternalDirs dirs, + FileStructEngine structEngine) throws IOException { structEngine.assertSampleStructureExists(dirs.outgoing); structEngine.assertSampleStructFinishMarkerExists(dirs.outgoing); } - private static void assertSampleStructMovedWithCopy(ExternalDirs dirs, LocalBufferDirs bufferDirs) - throws IOException + private static void assertSampleStructMovedWithCopy(ExternalDirs dirs, + LocalBufferDirs bufferDirs) throws IOException { assertEmptyIncomingAndBufferDir(dirs, bufferDirs); assertSampleStructInOutgoing(dirs); @@ -158,7 +160,8 @@ public class MainTest assertEquals(2, dirs.outgoing.list().length); } - private static void assertEmptyIncomingAndBufferDir(ExternalDirs dirs, LocalBufferDirs bufferDirs) + private static void assertEmptyIncomingAndBufferDir(ExternalDirs dirs, + LocalBufferDirs bufferDirs) { assertEmptyDir(dirs.incoming); assertEmptyBufferDirs(bufferDirs); @@ -206,16 +209,18 @@ public class MainTest private static ArrayList<String> getDefaultParameters(ExternalDirs dirs) { - return createList("--incoming-dir", dirs.incoming.getPath(), "--buffer-dir", dirs.buffer.getPath(), - "--outgoing-dir", dirs.outgoing.getPath(), "--check-interval", Integer.toString(CHECK_INTERVAL), - "--check-interval-internal", Integer.toString(CHECK_INTERVAL_INTERNAL), "--quiet-period", Integer - .toString(QUIET_PERIOD), "--treat-incoming-as-remote"); + return createList("--incoming-dir", dirs.incoming.getPath(), "--buffer-dir", dirs.buffer + .getPath(), "--outgoing-dir", dirs.outgoing.getPath(), "--check-interval", Integer + .toString(CHECK_INTERVAL), "--check-interval-internal", Integer + .toString(CHECK_INTERVAL_INTERNAL), "--quiet-period", Integer + .toString(QUIET_PERIOD), "--treat-incoming-as-remote"); } - private static ArrayList<String> getManualInterventionParameters(ExternalDirs dirs, String filteredName) + private static ArrayList<String> getManualInterventionParameters(ExternalDirs dirs, + String filteredName) { - return createList("--manual-intervention-dir", dirs.manualIntervDir.getPath(), "--manual-intervention-regex", - filteredName); + return createList("--manual-intervention-dir", dirs.manualIntervDir.getPath(), + "--manual-intervention-regex", filteredName); } private static ArrayList<String> getCleansingParameters(String cleansingStruct) @@ -257,8 +262,8 @@ public class MainTest return createParameters(list); } - private static Parameters createParametersWithFilter(ExternalDirs dirs, String manualIntervName, - String cleansingStruct) + private static Parameters createParametersWithFilter(ExternalDirs dirs, + String manualIntervName, String cleansingStruct) { ArrayList<String> list = getDefaultParameters(dirs); list.addAll(getExtraCopyParameters(dirs)); @@ -269,8 +274,8 @@ public class MainTest private static LocalBufferDirs createBufferDirs(Parameters parameters) { - return new LocalBufferDirs(parameters.getBufferDirectoryPath(), "test-copy-in-progress", "test-copy-complete", - "test-ready-to-move", "test-temp"); + return new LocalBufferDirs(parameters.getBufferDirectoryPath(), "test-copy-in-progress", + "test-copy-complete", "test-ready-to-move", "test-temp"); } private static interface IFSPreparator @@ -279,7 +284,8 @@ public class MainTest void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception; } - private static void performGenericTest(IFSPreparator preparator, long millisToWaitForPrep) throws Exception + private static void performGenericTest(IFSPreparator preparator, long millisToWaitForPrep) + throws Exception { ExternalDirs dirs = new ExternalDirs(workingDirectory); Parameters parameters = createDefaultParametersWithExtraCopy(dirs); @@ -297,21 +303,23 @@ public class MainTest assertSampleStructMovedWithCopy(dirs, bufferDirs); } - private static void runDataMover(Parameters parameters, LocalBufferDirs bufferDirs) throws InterruptedException + private static void runDataMover(Parameters parameters, LocalBufferDirs bufferDirs) + throws InterruptedException { runDataMover(parameters, bufferDirs, DATA_MOVER_COMPLETION_TIME); } - private static void runDataMover(Parameters parameters, LocalBufferDirs bufferDirs, long dataMoverCompleteionTime) - throws InterruptedException + private static void runDataMover(Parameters parameters, LocalBufferDirs bufferDirs, + long dataMoverCompleteionTime) throws InterruptedException { ITerminable terminable = Main.startupServer(parameters, bufferDirs); Thread.sleep(dataMoverCompleteionTime); assertTrue(terminable.terminate()); } - private static void runDataMover(ExternalDirs dirs, Parameters parameters, LocalBufferDirs bufferDirs, - IFSPreparator preparator, long millisToWaitForPrep) throws Exception + private static void runDataMover(ExternalDirs dirs, Parameters parameters, + LocalBufferDirs bufferDirs, IFSPreparator preparator, long millisToWaitForPrep) + throws Exception { ITerminable terminable = Main.startupServer(parameters, bufferDirs); Thread.sleep(millisToWaitForPrep); @@ -342,7 +350,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(dirs.incoming); createSampleStructure(bufferDirs.getCopyInProgressDir()); @@ -357,7 +366,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(dirs.incoming); createPartialSampleStructure(bufferDirs.getCopyInProgressDir()); @@ -372,7 +382,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getCopyInProgressDir()); } @@ -386,7 +397,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getCopyInProgressDir()); createSampleFinishedMarkerFile(bufferDirs.getCopyInProgressDir()); @@ -401,7 +413,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getCopyCompleteDir()); createSampleFinishedMarkerFile(bufferDirs.getCopyInProgressDir()); @@ -416,7 +429,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getCopyInProgressDir()); createPartialSampleStructure(dirs.incoming); @@ -432,7 +446,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getCopyCompleteDir()); } @@ -446,7 +461,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getCopyCompleteDir()); createPartialSampleStructure(bufferDirs.getTempDir()); @@ -461,7 +477,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getTempDir()); createSampleStructure(bufferDirs.getReadyToMoveDir()); @@ -473,11 +490,13 @@ public class MainTest { "slow" }, dataProvider = "delays") // recovery after failure during local processing, extra copy created in temp-dir, data moved to read-to-move, // outgoing processing has not started. It tests also outgoing process recovery. - public void testRecoveryLocalProcessingExtraCopyInTmpAndReadyToMove(long delay) throws Exception + public void testRecoveryLocalProcessingExtraCopyInTmpAndReadyToMove(long delay) + throws Exception { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(bufferDirs.getTempDir()); createSampleStructure(bufferDirs.getReadyToMoveDir()); @@ -492,7 +511,8 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(dirs.extraCopy); createSampleStructure(bufferDirs.getReadyToMoveDir()); @@ -508,15 +528,16 @@ public class MainTest { performGenericTest(new IFSPreparator() { - public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) throws Exception + public void prepareState(ExternalDirs dirs, LocalBufferDirs bufferDirs) + throws Exception { createSampleStructure(dirs.incoming); } }, delay); } - private FileStructEngine[] createAllThreadsPartialStruct(ExternalDirs dirs, LocalBufferDirs bufferDirs) - throws Exception + private FileStructEngine[] createAllThreadsPartialStruct(ExternalDirs dirs, + LocalBufferDirs bufferDirs) throws Exception { FileStructEngine[] structs = new FileStructEngine[6]; int c = 0; @@ -567,7 +588,8 @@ public class MainTest } // checks recovery mode when all threads need recovery, but no restart is made - public void testRecoveryAllThreadsPartial(Parameters parameters, ExternalDirs dirs) throws Exception + public void testRecoveryAllThreadsPartial(Parameters parameters, ExternalDirs dirs) + throws Exception { LocalBufferDirs bufferDirs = createBufferDirs(parameters); @@ -697,8 +719,8 @@ public class MainTest FileStructEngine cleansinStruct = new FileStructEngine("test2"); Parameters parameters = - createParametersWithFilter(dirs, manualIntervStruct.getMainStructName(), cleansinStruct - .getSampleCleansingRegExp()); + createParametersWithFilter(dirs, manualIntervStruct.getMainStructName(), + cleansinStruct.getSampleCleansingRegExp()); LocalBufferDirs bufferDirs = createBufferDirs(parameters); manualIntervStruct.createSampleStructure(dirs.incoming); diff --git a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/ParametersTest.java b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/ParametersTest.java index 20f46e25594..8524dfd8036 100644 --- a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/ParametersTest.java +++ b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/ParametersTest.java @@ -103,7 +103,8 @@ public class ParametersTest { final String localDataDir = ".." + File.separator + "test_it_data"; final Parameters parameters = parse("--incoming-dir", localDataDir); - assertEquals(createIncomingStore(localDataDir, null, parameters), getIncomingStore(parameters)); + assertEquals(createIncomingStore(localDataDir, null, parameters), + getIncomingStore(parameters)); } @Test @@ -125,7 +126,8 @@ public class ParametersTest public void testDefaultCheckIntervalInternal() throws Exception { final Parameters parameters = parse(); - assertEquals(1000 * Parameters.DEFAULT_CHECK_INTERVAL_INTERNAL, parameters.getCheckIntervalInternalMillis()); + assertEquals(1000 * Parameters.DEFAULT_CHECK_INTERVAL_INTERNAL, parameters + .getCheckIntervalInternalMillis()); } @Test @@ -147,14 +149,16 @@ public class ParametersTest public void testDefaultMaximalNumberOfRetries() throws Exception { final Parameters parameters = parse(); - assertEquals(Parameters.DEFAULT_MAXIMAL_NUMBER_OF_RETRIES, parameters.getMaximalNumberOfRetries()); + assertEquals(Parameters.DEFAULT_MAXIMAL_NUMBER_OF_RETRIES, parameters + .getMaximalNumberOfRetries()); } @Test public void testDefaultInactivityPeriod() throws Exception { final Parameters parameters = parse(); - assertEquals(1000 * Parameters.DEFAULT_INACTIVITY_PERIOD, parameters.getInactivityPeriodMillis()); + assertEquals(1000 * Parameters.DEFAULT_INACTIVITY_PERIOD, parameters + .getInactivityPeriodMillis()); } @Test @@ -183,7 +187,8 @@ public class ParametersTest public void testSetCheckIntervalInternalLong() throws Exception { final int checkInterval = 1; - final Parameters parameters = parse("--check-interval-internal", Integer.toString(checkInterval)); + final Parameters parameters = + parse("--check-interval-internal", Integer.toString(checkInterval)); assertEquals(1000 * checkInterval, parameters.getCheckIntervalInternalMillis()); } @@ -231,10 +236,13 @@ public class ParametersTest final String localTempDir = "l" + File.separator + "tmp"; final String remoteDataDir = "rrr"; final Parameters parameters = - parse("--incoming-dir", localDataDir, "--buffer-dir", localTempDir, "--outgoing-dir", remoteDataDir); - assertEquals(createIncomingStore(localDataDir, null, parameters), getIncomingStore(parameters)); + parse("--incoming-dir", localDataDir, "--buffer-dir", localTempDir, + "--outgoing-dir", remoteDataDir); + assertEquals(createIncomingStore(localDataDir, null, parameters), + getIncomingStore(parameters)); assertEquals(localTempDir, parameters.getBufferDirectoryPath().getPath()); - assertEquals(createOutgoingStore(remoteDataDir, null, parameters), getOutgoingStore(parameters)); + assertEquals(createOutgoingStore(remoteDataDir, null, parameters), + getOutgoingStore(parameters)); } @Test @@ -250,14 +258,17 @@ public class ParametersTest final String extraCopyDir = "xxx"; final Parameters parameters = - parse("--incoming-dir", localDataDir, "--buffer-dir", localTempDir, "--outgoing-dir", remoteDataDir, - "--outgoing-host", remoteHost, "--check-interval", Integer.toString(checkIntervall), - "--quiet-period", Integer.toString(quietPeriod), "--treat-incoming-as-remote", + parse("--incoming-dir", localDataDir, "--buffer-dir", localTempDir, + "--outgoing-dir", remoteDataDir, "--outgoing-host", remoteHost, + "--check-interval", Integer.toString(checkIntervall), "--quiet-period", + Integer.toString(quietPeriod), "--treat-incoming-as-remote", "--incoming-host", remoteIncomingHost, "--extra-copy-dir", extraCopyDir, "--rsync-overwrite"); - IFileStore incomingStoreExpected = createIncomingStore(localDataDir, remoteIncomingHost, parameters); + IFileStore incomingStoreExpected = + createIncomingStore(localDataDir, remoteIncomingHost, parameters); IFileStore incomingStore = getIncomingStore(parameters); - IFileStore outgoingStoreExpected = createOutgoingStore(remoteDataDir, remoteHost, parameters); + IFileStore outgoingStoreExpected = + createOutgoingStore(remoteDataDir, remoteHost, parameters); IFileStore outgoingStore = getOutgoingStore(parameters); assertEquals(incomingStoreExpected, incomingStore); diff --git a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/SelfTestTest.java b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/SelfTestTest.java index 28041f8d94f..246c795d07e 100644 --- a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/SelfTestTest.java +++ b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/SelfTestTest.java @@ -41,7 +41,8 @@ import ch.systemsx.cisd.datamover.testhelper.FileOperationsUtil; public class SelfTestTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); private static final File workingDirectory = new File(unitTestRootDirectory, "SelfTestTest"); @@ -98,12 +99,14 @@ public class SelfTestTest throw new AssertionError(); } - public Status copyFromRemote(File sourcePath, String sourceHost, File destinationDirectory) + public Status copyFromRemote(File sourcePath, String sourceHost, + File destinationDirectory) { throw new AssertionError(); } - public Status copyToRemote(File sourcePath, File destinationDirectory, String destinationHost) + public Status copyToRemote(File sourcePath, File destinationDirectory, + String destinationHost) { throw new AssertionError(); } @@ -118,7 +121,8 @@ public class SelfTestTest return true; } - public void check() throws EnvironmentFailureException, ConfigurationFailureException + public void check() throws EnvironmentFailureException, + ConfigurationFailureException { } @@ -133,7 +137,8 @@ public class SelfTestTest public void testHappyCaseWithRemoteHost() { final String outgoingHost = "some_remote_host"; - final FileStore remoteHostOutgoingStore = createRemoteStore(outgoingDirectory, outgoingHost, "outgoing"); + final FileStore remoteHostOutgoingStore = + createRemoteStore(outgoingDirectory, outgoingHost, "outgoing"); SelfTest.check(mockCopier, remoteHostOutgoingStore); } @@ -155,18 +160,21 @@ public class SelfTestTest public void testNonExistentPaths() { final File nonExistentIncomingDirectory = new File(workingDirectory, "data"); - final FileStore nonExistentIncomingStore = createLocalStore(nonExistentIncomingDirectory, "incoming"); + final FileStore nonExistentIncomingStore = + createLocalStore(nonExistentIncomingDirectory, "incoming"); SelfTest.check(mockCopier, nonExistentIncomingStore, bufferStore, outgoingStore); } private FileStore createRemoteStore(File path, String host, String description) { - return FileStoreFactory.createRemoteHost(path, host, description, FileOperationsUtil.createTestFatory()); + return FileStoreFactory.createRemoteHost(path, host, description, FileOperationsUtil + .createTestFatory()); } private static FileStore createLocalStore(File path, String description) { - return FileStoreFactory.createLocal(path, description, FileOperationsUtil.createTestFatory()); + return FileStoreFactory.createLocal(path, description, FileOperationsUtil + .createTestFatory()); } } diff --git a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitorTest.java b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitorTest.java index 28734f0f15c..f047b4cf5bc 100644 --- a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitorTest.java +++ b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/CopyActivityMonitorTest.java @@ -51,13 +51,16 @@ import static org.testng.AssertJUnit.*; public class CopyActivityMonitorTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); - private static final File workingDirectory = new File(unitTestRootDirectory, "CopyActivityMonitorTest"); + private static final File workingDirectory = + new File(unitTestRootDirectory, "CopyActivityMonitorTest"); private static final int INACTIVITY_PERIOD_MILLIS = 50; - private final StoringUncaughtExceptionHandler exceptionHandler = new StoringUncaughtExceptionHandler(); + private final StoringUncaughtExceptionHandler exceptionHandler = + new StoringUncaughtExceptionHandler(); // //////////////////////////////////////// // Some mock and dummy implementations. @@ -98,12 +101,12 @@ public class CopyActivityMonitorTest private final class HappyPathLastChangedChecker implements ILastChangedChecker { private final long stopWhenFindYoungerRelativeExpected; - + public HappyPathLastChangedChecker(long stopWhenFindYoungerRelativeExpected) { this.stopWhenFindYoungerRelativeExpected = stopWhenFindYoungerRelativeExpected; } - + public long lastChangedRelative(StoreItem item, long stopWhenFindYoungerRelative) { assertEquals(stopWhenFindYoungerRelativeExpected, stopWhenFindYoungerRelative); @@ -161,7 +164,8 @@ public class CopyActivityMonitorTest return asFileStore(directory, checker, factory); } - private IFileStore asFileStore(File directory, final ILastChangedChecker checker, IFileSysOperationsFactory factory) + private IFileStore asFileStore(File directory, final ILastChangedChecker checker, + IFileSysOperationsFactory factory) { final FileStoreLocal localImpl = new FileStoreLocal(directory, "input-test", factory); return new FileStore(directory, null, false, "input-test", factory) @@ -261,9 +265,11 @@ public class CopyActivityMonitorTest final ITerminable dummyTerminable = new DummyTerminable(); final long inactivityPeriodMillis = 5000L; final ITimingParameters parameters = new MyTimingParameters(0, inactivityPeriodMillis); - final ILastChangedChecker checker = new HappyPathLastChangedChecker(inactivityPeriodMillis - 1000L); + final ILastChangedChecker checker = + new HappyPathLastChangedChecker(inactivityPeriodMillis - 1000L); final CopyActivityMonitor monitor = - new CopyActivityMonitor(asFileStore(workingDirectory, checker), dummyTerminable, parameters); + new CopyActivityMonitor(asFileStore(workingDirectory, checker), dummyTerminable, + parameters); StoreItem item = createDirectoryInside(workingDirectory); monitor.start(item); Thread.sleep(INACTIVITY_PERIOD_MILLIS * 15); @@ -278,7 +284,8 @@ public class CopyActivityMonitorTest final MockTerminable copyProcess = new MockTerminable(); final ITimingParameters parameters = new MyTimingParameters(0); final CopyActivityMonitor monitor = - new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, parameters); + new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, + parameters); StoreItem item = createDirectoryInside(workingDirectory); monitor.start(item); Thread.sleep(INACTIVITY_PERIOD_MILLIS * 15); @@ -322,7 +329,8 @@ public class CopyActivityMonitorTest final MockTerminable copyProcess = new MockTerminable(); final ITimingParameters parameters = new MyTimingParameters(0); final CopyActivityMonitor monitor = - new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, parameters); + new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, + parameters); StoreItem item = createDirectoryInside(workingDirectory); monitor.start(item); Thread.sleep(INACTIVITY_PERIOD_MILLIS * 15); @@ -342,15 +350,17 @@ public class CopyActivityMonitorTest { "slow" }) public void testActivityMonitorTimedOut() throws Throwable { - final PathLastChangedCheckerDelayed checker = new PathLastChangedCheckerDelayed(INACTIVITY_PERIOD_MILLIS); + final PathLastChangedCheckerDelayed checker = + new PathLastChangedCheckerDelayed(INACTIVITY_PERIOD_MILLIS); final MockTerminable copyProcess = new MockTerminable(); final ITimingParameters parameters = new MyTimingParameters(0); final CopyActivityMonitor monitor = - new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, parameters); + new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, + parameters); final StoreItem item = createDirectoryInside(workingDirectory); final LogMonitoringAppender appender = - LogMonitoringAppender.addAppender(LogCategory.OPERATION, - String.format("Could not determine \"last changed time\" of %s: time out.", item)); + LogMonitoringAppender.addAppender(LogCategory.OPERATION, String.format( + "Could not determine \"last changed time\" of %s: time out.", item)); monitor.start(item); Thread.sleep(INACTIVITY_PERIOD_MILLIS * 15); monitor.stop(); @@ -364,11 +374,13 @@ public class CopyActivityMonitorTest { "slow" }) public void testActivityMonitorOnceTimedOutTheOK() throws Throwable { - final PathLastChangedCheckerDelayed checker = new PathLastChangedCheckerDelayed(INACTIVITY_PERIOD_MILLIS, 0L); + final PathLastChangedCheckerDelayed checker = + new PathLastChangedCheckerDelayed(INACTIVITY_PERIOD_MILLIS, 0L); final MockTerminable copyProcess = new MockTerminable(); final ITimingParameters parameters = new MyTimingParameters(0); final CopyActivityMonitor monitor = - new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, parameters); + new CopyActivityMonitor(asFileStore(workingDirectory, checker), copyProcess, + parameters); final StoreItem item = createDirectoryInside(workingDirectory); monitor.start(item); Thread.sleep(INACTIVITY_PERIOD_MILLIS * 15); diff --git a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopierTest.java b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopierTest.java index 07a7b5589b9..545ce6d1f91 100644 --- a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopierTest.java +++ b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/filesystem/remote/rsync/RsyncCopierTest.java @@ -45,7 +45,8 @@ import ch.systemsx.cisd.common.utilities.FileUtilities; public class RsyncCopierTest { - private static final File unitTestRootDirectory = new File("targets" + File.separator + "unit-test-wd"); + private static final File unitTestRootDirectory = + new File("targets" + File.separator + "unit-test-wd"); private static final File workingDirectory = new File(unitTestRootDirectory, "RsyncCopierTest"); @@ -53,7 +54,8 @@ public class RsyncCopierTest private final File destinationDirectory = new File(workingDirectory, "b"); - private final StoringUncaughtExceptionHandler exceptionHandler = new StoringUncaughtExceptionHandler(); + private final StoringUncaughtExceptionHandler exceptionHandler = + new StoringUncaughtExceptionHandler(); @BeforeClass public void init() @@ -79,16 +81,18 @@ public class RsyncCopierTest destinationDirectory.deleteOnExit(); } - private File createRsync(String rsyncVersion, String... additionalLines) throws IOException, InterruptedException + private File createRsync(String rsyncVersion, String... additionalLines) throws IOException, + InterruptedException { final File rsyncBinary = new File(workingDirectory, "rsync"); rsyncBinary.delete(); final List<String> lines = new ArrayList<String>(); - lines.addAll(Arrays.asList("#! /bin/sh", "if [ \"$1\" = \"--version\" ]; then ", String.format( - " echo \"rsync version %s\"", rsyncVersion), "exit 0", "fi")); + lines.addAll(Arrays.asList("#! /bin/sh", "if [ \"$1\" = \"--version\" ]; then ", String + .format(" echo \"rsync version %s\"", rsyncVersion), "exit 0", "fi")); lines.addAll(Arrays.asList(additionalLines)); CollectionIO.writeIterable(rsyncBinary, lines); - Runtime.getRuntime().exec(String.format("/bin/chmod +x %s", rsyncBinary.getPath())).waitFor(); + Runtime.getRuntime().exec(String.format("/bin/chmod +x %s", rsyncBinary.getPath())) + .waitFor(); rsyncBinary.deleteOnExit(); return rsyncBinary; } @@ -138,7 +142,8 @@ public class RsyncCopierTest { final File parametersLogFile = new File(workingDirectory, "parameters.log"); final File loggingRsyncBinary = - createRsync("2.6.7", String.format("echo \"$@\" > %s", parametersLogFile.getAbsolutePath())); + createRsync("2.6.7", String.format("echo \"$@\" > %s", parametersLogFile + .getAbsolutePath())); final RsyncCopier copier = new RsyncCopier(loggingRsyncBinary, null, false, false); copier.copy(sourceFile, destinationDirectory); String rsyncParameters = FileUtilities.loadToString(parametersLogFile); @@ -152,7 +157,8 @@ public class RsyncCopierTest { final File parametersLogFile = new File(workingDirectory, "parameters.log"); final File loggingRsyncBinary = - createRsync("2.6.6", String.format("echo \"$@\" > %s", parametersLogFile.getAbsolutePath())); + createRsync("2.6.6", String.format("echo \"$@\" > %s", parametersLogFile + .getAbsolutePath())); final RsyncCopier copier = new RsyncCopier(loggingRsyncBinary, null, false, false); copier.copy(sourceFile, destinationDirectory); String rsyncParameters = FileUtilities.loadToString(parametersLogFile); @@ -166,7 +172,8 @@ public class RsyncCopierTest { final File parametersLogFile = new File(workingDirectory, "parameters.log"); final File loggingRsyncBinary = - createRsync("2.6.7", String.format("echo \"$@\" > %s", parametersLogFile.getAbsolutePath())); + createRsync("2.6.7", String.format("echo \"$@\" > %s", parametersLogFile + .getAbsolutePath())); final RsyncCopier copier = new RsyncCopier(loggingRsyncBinary, null, false, true); copier.copy(sourceFile, destinationDirectory); String rsyncParameters = FileUtilities.loadToString(parametersLogFile); diff --git a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilterTest.java b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilterTest.java index 20889472a08..c6f5a748009 100644 --- a/datamover/sourceTest/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilterTest.java +++ b/datamover/sourceTest/java/ch/systemsx/cisd/datamover/utils/QuietPeriodFileFilterTest.java @@ -86,7 +86,8 @@ public class QuietPeriodFileFilterTest public void testGetTimeFormat() { assertEquals("%0$tY-%0$tm-%0$td %0$tH:%0$tM:%0$tS", QuietPeriodFileFilter.getTimeFormat(0)); - assertEquals("%17$tY-%17$tm-%17$td %17$tH:%17$tM:%17$tS", QuietPeriodFileFilter.getTimeFormat(17)); + assertEquals("%17$tY-%17$tm-%17$td %17$tH:%17$tM:%17$tS", QuietPeriodFileFilter + .getTimeFormat(17)); } @Test @@ -96,7 +97,8 @@ public class QuietPeriodFileFilterTest "Last modification time of path 'bla' jumped back: check at 1970-01-01 01:00:01 -> " + "last modification time 1970-01-01 01:00:50, check at later time 1970-01-01 01:00:10 -> " + "last modification time 1970-01-01 01:00:30 (which is 20000 ms younger)"; - assertEquals(expected, QuietPeriodFileFilter.getClockProblemLogMessage("bla", 1000L, 50000L, 10000L, 30000L)); + assertEquals(expected, QuietPeriodFileFilter.getClockProblemLogMessage("bla", 1000L, + 50000L, 10000L, 30000L)); } @Test @@ -268,7 +270,8 @@ public class QuietPeriodFileFilterTest // calls to get the required number of calls for clean up allowing(timeProvider).getCurrentTimeMillis(); will(returnValue(nowMillis2)); - allowing(fileStore).lastChanged(with(same(ITEM)), with(greaterThanOrEqualTo(0L))); + allowing(fileStore).lastChanged(with(same(ITEM)), + with(greaterThanOrEqualTo(0L))); will(returnValue(pathLastChangedMillis2)); } }); diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBMigrationEngine.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBMigrationEngine.java index 255dbaf6f49..fa1d63856ec 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBMigrationEngine.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBMigrationEngine.java @@ -33,25 +33,29 @@ import ch.systemsx.cisd.common.logging.LogFactory; */ public class DBMigrationEngine { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, DBMigrationEngine.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, DBMigrationEngine.class); /** * Creates or migrates a database specified in the context for/to the specified version. * * @return the SQL script provider. */ - public static ISqlScriptProvider createOrMigrateDatabaseAndGetScriptProvider(DatabaseConfigurationContext context, - String databaseVersion) + public static ISqlScriptProvider createOrMigrateDatabaseAndGetScriptProvider( + DatabaseConfigurationContext context, String databaseVersion) { assert context != null : "Unspecified database configuration context."; assert StringUtils.isNotBlank(databaseVersion) : "Unspecified database version."; - final ch.systemsx.cisd.dbmigration.IDAOFactory migrationDAOFactory = context.createDAOFactory(); + final ch.systemsx.cisd.dbmigration.IDAOFactory migrationDAOFactory = + context.createDAOFactory(); final String scriptFolder = context.getScriptFolder(); String databaseEngineCode = context.getDatabaseEngineCode(); - final ISqlScriptProvider sqlScriptProvider = new SqlScriptProvider(scriptFolder, databaseEngineCode); + final ISqlScriptProvider sqlScriptProvider = + new SqlScriptProvider(scriptFolder, databaseEngineCode); final DBMigrationEngine migrationEngine = - new DBMigrationEngine(migrationDAOFactory, sqlScriptProvider, context.isCreateFromScratch()); + new DBMigrationEngine(migrationDAOFactory, sqlScriptProvider, context + .isCreateFromScratch()); migrationEngine.migrateTo(databaseVersion); return sqlScriptProvider; } @@ -71,7 +75,8 @@ public class DBMigrationEngine * * @param shouldCreateFromScratch If <code>true</code> the database should be dropped and created from scratch. */ - public DBMigrationEngine(IDAOFactory daoFactory, ISqlScriptProvider scriptProvider, boolean shouldCreateFromScratch) + public DBMigrationEngine(IDAOFactory daoFactory, ISqlScriptProvider scriptProvider, + boolean shouldCreateFromScratch) { adminDAO = daoFactory.getDatabaseDAO(); logDAO = daoFactory.getDatabaseVersionLogDAO(); @@ -121,8 +126,8 @@ public class DBMigrationEngine final String databaseName = adminDAO.getDatabaseName(); if (operationLog.isInfoEnabled()) { - operationLog.info("Trying to migrate database '" + databaseName + "' from version " - + databaseVersion + " to " + version + "."); + operationLog.info("Trying to migrate database '" + databaseName + + "' from version " + databaseVersion + " to " + version + "."); } } migrate(databaseVersion, version); @@ -131,8 +136,9 @@ public class DBMigrationEngine final String databaseName = adminDAO.getDatabaseName(); if (operationLog.isInfoEnabled()) { - operationLog.info("Database '" + databaseName + "' successfully migrated from version " - + databaseVersion + " to " + version + "."); + operationLog.info("Database '" + databaseName + + "' successfully migrated from version " + databaseVersion + " to " + + version + "."); } } } else @@ -161,7 +167,9 @@ public class DBMigrationEngine } if (entry.getRunStatus() != LogEntry.RunStatus.SUCCESS) { - String message = "Inconsistent database: Last creation/migration didn't succeed. Last log entry: " + entry; + String message = + "Inconsistent database: Last creation/migration didn't succeed. Last log entry: " + + entry; operationLog.error(message); throw new EnvironmentFailureException(message); } @@ -182,7 +190,8 @@ public class DBMigrationEngine if (operationLog.isInfoEnabled()) { String databaseName = adminDAO.getDatabaseName(); - operationLog.info("Database '" + databaseName + "' version " + version + " has been successfully created."); + operationLog.info("Database '" + databaseName + "' version " + version + + " has been successfully created."); } } @@ -232,8 +241,8 @@ public class DBMigrationEngine { final String databaseName = adminDAO.getDatabaseName(); final String message = - "Cannot migrate database '" + databaseName + "' from version " + version + " to " + nextVersion - + " because of missing migration script."; + "Cannot migrate database '" + databaseName + "' from version " + version + + " to " + nextVersion + " because of missing migration script."; operationLog.error(message); throw new EnvironmentFailureException(message); } @@ -241,8 +250,8 @@ public class DBMigrationEngine scriptExecutor.execute(migrationScript, true, logDAO); if (operationLog.isInfoEnabled()) { - operationLog.info("Successfully migrated from version " + version + " to " + nextVersion + " in " - + (System.currentTimeMillis() - time) + " msec"); + operationLog.info("Successfully migrated from version " + version + " to " + + nextVersion + " in " + (System.currentTimeMillis() - time) + " msec"); } version = nextVersion; } while (version.equals(toVersion) == false); diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBScriptFormatter.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBScriptFormatter.java index 87042be954f..1478f1a08f5 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBScriptFormatter.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBScriptFormatter.java @@ -50,52 +50,49 @@ public class DBScriptFormatter private static enum StatementClass { - CREATE_DOMAIN("Creating domains", "CREATE DOMAIN "), - CREATE_TABLE("Creating tables", "CREATE TABLE "), - CREATE_SEQUENCE("Creating sequences", "CREATE SEQUENCE ", + CREATE_DOMAIN("Creating domains", "CREATE DOMAIN "), CREATE_TABLE("Creating tables", + "CREATE TABLE "), CREATE_SEQUENCE("Creating sequences", "CREATE SEQUENCE ", new ILineProcessor() { public String process(String line) { - return StringUtils.replace(line, " NO MAXVALUE NO MINVALUE NO CYCLE", ""); + return StringUtils.replace(line, " NO MAXVALUE NO MINVALUE NO CYCLE", + ""); } - }), - PRIMARY_KEY_CONSTRAINTS("Creating primary key constraints", new ILineMatcher() - { - public boolean match(String line) - { - return Pattern.matches("ALTER TABLE .+ PRIMARY KEY.+", line); - } - }, null), - UNIQUE_CONSTRAINTS("Creating unique constraints", new ILineMatcher() - { - public boolean match(String line) - { - return Pattern.matches("ALTER TABLE .+ UNIQUE.+", line); - } - }, null), - FOREIGN_KEY_CONSTRAINTS("Creating foreign key constraints", new ILineMatcher() - { - public boolean match(String line) - { - return Pattern.matches("ALTER TABLE .+ FOREIGN KEY.+", line); - } - }, null), - CHECK_CONSTRAINTS("Creating check constraints", new ILineMatcher() - { - public boolean match(String line) + }), PRIMARY_KEY_CONSTRAINTS("Creating primary key constraints", + new ILineMatcher() + { + public boolean match(String line) + { + return Pattern.matches("ALTER TABLE .+ PRIMARY KEY.+", line); + } + }, null), UNIQUE_CONSTRAINTS("Creating unique constraints", new ILineMatcher() { - return Pattern.matches("ALTER TABLE .+ CHECK.+", line); - } - }, null), - CREATE_INDEX("Creating indices", "CREATE INDEX "), - MISC("Miscellaneous", new ILineMatcher() + public boolean match(String line) + { + return Pattern.matches("ALTER TABLE .+ UNIQUE.+", line); + } + }, null), FOREIGN_KEY_CONSTRAINTS("Creating foreign key constraints", + new ILineMatcher() + { + public boolean match(String line) + { + return Pattern.matches("ALTER TABLE .+ FOREIGN KEY.+", line); + } + }, null), CHECK_CONSTRAINTS("Creating check constraints", new ILineMatcher() { public boolean match(String line) { - return true; + return Pattern.matches("ALTER TABLE .+ CHECK.+", line); } - }, null); + }, null), CREATE_INDEX("Creating indices", "CREATE INDEX "), MISC("Miscellaneous", + new ILineMatcher() + { + public boolean match(String line) + { + return true; + } + }, null); private ILineMatcher matcher; @@ -108,7 +105,8 @@ public class DBScriptFormatter this(comment, prefix, null); } - StatementClass(final String comment, final String prefix, final ILineProcessor processorOrNull) + StatementClass(final String comment, final String prefix, + final ILineProcessor processorOrNull) { this(comment, new ILineMatcher() { @@ -116,11 +114,11 @@ public class DBScriptFormatter { return line.startsWith(prefix); } - }, - processorOrNull); + }, processorOrNull); } - StatementClass(final String comment, final ILineMatcher matcher, final ILineProcessor processorOrNull) + StatementClass(final String comment, final ILineMatcher matcher, + final ILineProcessor processorOrNull) { this.comment = comment; this.matcher = matcher; @@ -131,7 +129,7 @@ public class DBScriptFormatter { return comment; } - + public boolean matches(String statement) { return matcher.match(statement); @@ -154,7 +152,8 @@ public class DBScriptFormatter { break; } - if (trimmedScriptLine.substring(COMMENT.length()).trim().toUpperCase().startsWith("CREATING")) + if (trimmedScriptLine.substring(COMMENT.length()).trim().toUpperCase().startsWith( + "CREATING")) { continue; } @@ -162,7 +161,8 @@ public class DBScriptFormatter } } - private static List<String> getOrCreateList(Map<StatementClass, List<String>> map, StatementClass key) + private static List<String> getOrCreateList(Map<StatementClass, List<String>> map, + StatementClass key) { List<String> list = map.get(key); if (list == null) @@ -216,7 +216,8 @@ public class DBScriptFormatter System.exit(1); } - final PrintWriter out = new PrintWriter(new FileOutputStream(new File(args[0] + ".formatted"))); + final PrintWriter out = + new PrintWriter(new FileOutputStream(new File(args[0] + ".formatted"))); final String sqlScript = FileUtilities.loadToString(new File(args[0])); final List<String> sqlStatements = DBUtilities.splitSqlStatements(sqlScript); diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBUtilities.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBUtilities.java index 876372b3470..98eb23e2d23 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBUtilities.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DBUtilities.java @@ -102,11 +102,12 @@ public final class DBUtilities return statements; } - private final static void addToStatements(final List<String> statements, final StringBuilder statement) + private final static void addToStatements(final List<String> statements, + final StringBuilder statement) { final String statementStr = - statement.toString().trim().replaceAll("\\s+", " ").replaceAll("\\)(\\w)", ") $1").replaceAll("\\s+;", - ";"); + statement.toString().trim().replaceAll("\\s+", " ").replaceAll("\\)(\\w)", ") $1") + .replaceAll("\\s+;", ";"); statements.add(statementStr); statement.setLength(0); } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseConfigurationContext.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseConfigurationContext.java index d97a2e2d88a..be5b60aebde 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseConfigurationContext.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseConfigurationContext.java @@ -236,7 +236,8 @@ public class DatabaseConfigurationContext implements DisposableBean if (adminDataSource == null) { adminDataSource = - dataSourceFactory.createDataSource(getDriver(), getAdminURL(), getAdminUser(), getAdminPassword()); + dataSourceFactory.createDataSource(getDriver(), getAdminURL(), getAdminUser(), + getAdminPassword()); } return adminDataSource; } @@ -471,7 +472,8 @@ public class DatabaseConfigurationContext implements DisposableBean * @param databaseEngineCode New value. * @throws ConfigurationFailureException If there is no such database engine. */ - public final void setDatabaseEngineCode(String databaseEngineCode) throws ConfigurationFailureException + public final void setDatabaseEngineCode(String databaseEngineCode) + throws ConfigurationFailureException { this.databaseEngine = DatabaseEngine.getEngineForCode(databaseEngineCode); } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseEngine.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseEngine.java index 2bca8602b8a..0ff7a5bbfca 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseEngine.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseEngine.java @@ -38,9 +38,9 @@ import ch.systemsx.cisd.dbmigration.postgresql.PostgreSQLDAOFactory; */ public enum DatabaseEngine { - POSTGRESQL("postgresql", "org.postgresql.Driver", PostgreSQLDAOFactory.class, new DefaultLobHandler(), - new PostgreSQLSequencerHandler(), "jdbc:postgresql:{0}", "jdbc:postgresql:{0}{1}", "//localhost/", - "postgres"), + POSTGRESQL("postgresql", "org.postgresql.Driver", PostgreSQLDAOFactory.class, + new DefaultLobHandler(), new PostgreSQLSequencerHandler(), "jdbc:postgresql:{0}", + "jdbc:postgresql:{0}{1}", "//localhost/", "postgres"), H2("h2", "org.h2.Driver", H2DAOFactory.class, new DefaultLobHandler(), new PostgreSQLSequencerHandler(), "jdbc:h2:{0}{1};DB_CLOSE_DELAY=-1", @@ -70,8 +70,8 @@ public enum DatabaseEngine @SuppressWarnings("unchecked") DatabaseEngine(String code, String driver, Class<?> daoFactoryClass, LobHandler lobHandler, - ISequencerHandler sequenceHandler, String adminUrlTemplate, String urlTemplate, String defaultURLHostPart, - String defaultAdminUser) + ISequencerHandler sequenceHandler, String adminUrlTemplate, String urlTemplate, + String defaultURLHostPart, String defaultAdminUser) { assert code != null; assert driver != null; @@ -94,7 +94,8 @@ public enum DatabaseEngine this.daoFactoryClass = (Class<ch.systemsx.cisd.dbmigration.IDAOFactory>) daoFactoryClass; try { - this.daoFactoryConstructor = this.daoFactoryClass.getConstructor(DatabaseConfigurationContext.class); + this.daoFactoryConstructor = + this.daoFactoryClass.getConstructor(DatabaseConfigurationContext.class); } catch (NoSuchMethodException ex) { throw new Error("No constructor", ex); @@ -149,7 +150,8 @@ public enum DatabaseEngine */ public final String getAdminURL(String urlHostPartOrNull, String databaseName) { - final String hostPartUrl = (urlHostPartOrNull == null) ? defaultURLHostPart : urlHostPartOrNull; + final String hostPartUrl = + (urlHostPartOrNull == null) ? defaultURLHostPart : urlHostPartOrNull; final String url = MessageFormat.format(adminUrlTemplate, hostPartUrl, databaseName); return url; } @@ -167,7 +169,8 @@ public enum DatabaseEngine */ public final String getURL(String urlHostPartOrNull, String databaseName) { - final String hostPartUrl = (urlHostPartOrNull == null) ? defaultURLHostPart : urlHostPartOrNull; + final String hostPartUrl = + (urlHostPartOrNull == null) ? defaultURLHostPart : urlHostPartOrNull; final String url = MessageFormat.format(urlTemplate, hostPartUrl, databaseName); return url; } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseVersionLogDAO.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseVersionLogDAO.java index d52e6ab9942..79f86a65e99 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseVersionLogDAO.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/DatabaseVersionLogDAO.java @@ -66,8 +66,8 @@ public class DatabaseVersionLogDAO extends SimpleJdbcDaoSupport implements IData private static final String DB_VERSION = "db_version"; private static final String SELECT_LAST_ENTRY = - "select * from " + DB_VERSION_LOG + " where " + RUN_STATUS_TIMESTAMP + " in (select max(" - + RUN_STATUS_TIMESTAMP + ") from " + DB_VERSION_LOG + ")"; + "select * from " + DB_VERSION_LOG + " where " + RUN_STATUS_TIMESTAMP + + " in (select max(" + RUN_STATUS_TIMESTAMP + ") from " + DB_VERSION_LOG + ")"; private static final class LogEntryRowMapper implements ParameterizedRowMapper<LogEntry> { @@ -87,7 +87,8 @@ public class DatabaseVersionLogDAO extends SimpleJdbcDaoSupport implements IData logEntry.setRunStatusTimestamp(rs.getDate(RUN_STATUS_TIMESTAMP)); try { - logEntry.setModuleCode(new String(lobHandler.getBlobAsBytes(rs, MODULE_CODE), ENCODING)); + logEntry.setModuleCode(new String(lobHandler.getBlobAsBytes(rs, MODULE_CODE), + ENCODING)); } catch (UnsupportedEncodingException ex) { throw new CheckedExceptionTunnel(ex); @@ -140,73 +141,83 @@ public class DatabaseVersionLogDAO extends SimpleJdbcDaoSupport implements IData public LogEntry getLastEntry() { SimpleJdbcTemplate template = getSimpleJdbcTemplate(); - List<LogEntry> entries = template.query(SELECT_LAST_ENTRY, new LogEntryRowMapper(lobHandler)); + List<LogEntry> entries = + template.query(SELECT_LAST_ENTRY, new LogEntryRowMapper(lobHandler)); return entries.size() == 0 ? null : entries.get(entries.size() - 1); } /** - * Inserts a new entry into the version log with {@link LogEntry.RunStatus#START}. + * Inserts a new entry into the version log with {@link LogEntry.RunStatus#START}. * * @param moduleScript The script of the module to be logged. */ public void logStart(final Script moduleScript) { JdbcTemplate template = getJdbcTemplate(); - PreparedStatementCallback callback = new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) - { - @Override - protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException - { - ps.setString(1, moduleScript.getVersion()); - ps.setString(2, moduleScript.getName()); - ps.setString(3, LogEntry.RunStatus.START.toString()); - ps.setTimestamp(4, new Timestamp(System.currentTimeMillis())); - lobCreator.setBlobAsBytes(ps, 5, getAsByteArray(moduleScript.getCode())); - } - }; - template.execute("insert into " + DB_VERSION_LOG + " (" + DB_VERSION + "," + MODULE_NAME + "," + RUN_STATUS - + "," + RUN_STATUS_TIMESTAMP + "," + MODULE_CODE + ") values (?,?,?,?,?)", callback); + PreparedStatementCallback callback = + new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) + { + @Override + protected void setValues(PreparedStatement ps, LobCreator lobCreator) + throws SQLException + { + ps.setString(1, moduleScript.getVersion()); + ps.setString(2, moduleScript.getName()); + ps.setString(3, LogEntry.RunStatus.START.toString()); + ps.setTimestamp(4, new Timestamp(System.currentTimeMillis())); + lobCreator + .setBlobAsBytes(ps, 5, getAsByteArray(moduleScript.getCode())); + } + }; + template.execute("insert into " + DB_VERSION_LOG + " (" + DB_VERSION + "," + MODULE_NAME + + "," + RUN_STATUS + "," + RUN_STATUS_TIMESTAMP + "," + MODULE_CODE + + ") values (?,?,?,?,?)", callback); } /** - * Update log entry specified by version and module name to {@link LogEntry.RunStatus#SUCCESS}. + * Update log entry specified by version and module name to {@link LogEntry.RunStatus#SUCCESS}. * * @param moduleScript The script of the successfully applied module. */ public void logSuccess(final Script moduleScript) { SimpleJdbcTemplate template = getSimpleJdbcTemplate(); - template.update("update " + DB_VERSION_LOG + " SET " + RUN_STATUS + " = ? , " + RUN_STATUS_TIMESTAMP + " = ? " - + "where " + DB_VERSION + " = ? and " + MODULE_NAME + " = ?", LogEntry.RunStatus.SUCCESS.toString(), - new Date(System.currentTimeMillis()), moduleScript.getVersion(), moduleScript.getName()); + template.update("update " + DB_VERSION_LOG + " SET " + RUN_STATUS + " = ? , " + + RUN_STATUS_TIMESTAMP + " = ? " + "where " + DB_VERSION + " = ? and " + + MODULE_NAME + " = ?", LogEntry.RunStatus.SUCCESS.toString(), new Date(System + .currentTimeMillis()), moduleScript.getVersion(), moduleScript.getName()); } /** - * Update log entry specified by version and module name to {@link LogEntry.RunStatus#FAILED}. + * Update log entry specified by version and module name to {@link LogEntry.RunStatus#FAILED}. * * @param moduleScript Script of the failed module. - * @param runException Exception causing the failure. + * @param runException Exception causing the failure. */ public void logFailure(final Script moduleScript, Throwable runException) { final StringWriter stringWriter = new StringWriter(); runException.printStackTrace(new PrintWriter(stringWriter)); JdbcTemplate template = getJdbcTemplate(); - PreparedStatementCallback callback = new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) - { - @Override - protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException - { - ps.setString(1, LogEntry.RunStatus.FAILED.toString()); - ps.setTimestamp(2, new Timestamp(System.currentTimeMillis())); - lobCreator.setBlobAsBytes(ps, 3, getAsByteArray(stringWriter.toString())); - ps.setString(4, moduleScript.getVersion()); - ps.setString(5, moduleScript.getName()); - } - }; - template.execute("update " + DB_VERSION_LOG + " SET " + RUN_STATUS + " = ?, " + RUN_STATUS_TIMESTAMP + " = ?, " - + RUN_EXCEPTION + " = ? where " + DB_VERSION + " = ? and " + MODULE_NAME + " = ?", callback); + PreparedStatementCallback callback = + new AbstractLobCreatingPreparedStatementCallback(this.lobHandler) + { + @Override + protected void setValues(PreparedStatement ps, LobCreator lobCreator) + throws SQLException + { + ps.setString(1, LogEntry.RunStatus.FAILED.toString()); + ps.setTimestamp(2, new Timestamp(System.currentTimeMillis())); + lobCreator.setBlobAsBytes(ps, 3, + getAsByteArray(stringWriter.toString())); + ps.setString(4, moduleScript.getVersion()); + ps.setString(5, moduleScript.getName()); + } + }; + template.execute("update " + DB_VERSION_LOG + " SET " + RUN_STATUS + " = ?, " + + RUN_STATUS_TIMESTAMP + " = ?, " + RUN_EXCEPTION + " = ? where " + DB_VERSION + + " = ? and " + MODULE_NAME + " = ?", callback); } } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDataSourceFactory.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDataSourceFactory.java index 6ffd2c0057d..70d4c850bd4 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDataSourceFactory.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDataSourceFactory.java @@ -20,7 +20,7 @@ import javax.sql.DataSource; /** * Factory for a {@link DataSource}. - * + * * @author Franz-Josef Elmer */ public interface IDataSourceFactory diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseAdminDAO.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseAdminDAO.java index 71b4df96b92..8b90956d0ae 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseAdminDAO.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseAdminDAO.java @@ -20,7 +20,7 @@ import java.io.File; /** * Interface for administration of a database. - * + * * @author Franz-Josef Elmer */ public interface IDatabaseAdminDAO @@ -29,28 +29,28 @@ public interface IDatabaseAdminDAO * Returns the name of the database to be created / dropped. */ public String getDatabaseName(); - + /** * Returns the complete URL of the database to be created / dropped. */ public String getDatabaseURL(); - + /** - * Creates the owner/user of the database. Implementation should handle the case of already existing owner/user + * Creates the owner/user of the database. Implementation should handle the case of already existing owner/user * gracefully. */ public void createOwner(); - + /** * Creates the database and the 'database_version_logs' table. */ public void createDatabase(); - + /** * Restores the database from previously created dump. */ public void restoreDatabaseFromDump(File dumpFolder, String version); - + /** * Drops the database. */ diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseVersionLogDAO.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseVersionLogDAO.java index c624460c137..b7fa568c305 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseVersionLogDAO.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/IDatabaseVersionLogDAO.java @@ -19,10 +19,9 @@ package ch.systemsx.cisd.dbmigration; import ch.systemsx.cisd.common.Script; import ch.systemsx.cisd.common.db.ISqlScriptExecutionLogger; - /** * Interface for a Data Access Object for the database version log. - * + * * @author Franz-Josef Elmer */ public interface IDatabaseVersionLogDAO extends ISqlScriptExecutionLogger @@ -31,17 +30,17 @@ public interface IDatabaseVersionLogDAO extends ISqlScriptExecutionLogger * Returns <code>true</code> if the database instance with database version log can be connected. */ public boolean canConnectToDatabase(); - + /** * Creates the table DATABASE_VERSION_LOG by using the specified script. */ public void createTable(Script script); - + /** * Returns the last log entry found. * * @return <code>null</code> if log is empty. */ public LogEntry getLastEntry(); - + } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/LogEntry.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/LogEntry.java index cc587f9f0c5..db7702b1baf 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/LogEntry.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/LogEntry.java @@ -20,7 +20,7 @@ import java.util.Date; /** * Log entry of DATABASE_VERSION_LOG. - * + * * @author Franz-Josef Elmer */ public class LogEntry @@ -30,14 +30,19 @@ public class LogEntry { START, SUCCESS, FAILED, UNKNOWN } - + private String version; + private String moduleName; + private RunStatus runStatus; + private Date runStatusTimestamp; + private String moduleCode; + private String runException; - + /** * Returns moduleCode. * @@ -47,7 +52,7 @@ public class LogEntry { return moduleCode; } - + /** * Sets moduleCode. * @@ -57,7 +62,7 @@ public class LogEntry { this.moduleCode = moduleCode; } - + /** * Returns moduleName. * @@ -67,7 +72,7 @@ public class LogEntry { return moduleName; } - + /** * Sets moduleName. * @@ -77,7 +82,7 @@ public class LogEntry { this.moduleName = moduleName; } - + /** * Returns runException. * @@ -87,7 +92,7 @@ public class LogEntry { return runException; } - + /** * Sets runException. * @@ -97,7 +102,7 @@ public class LogEntry { this.runException = runException; } - + /** * Returns runStatus. * @@ -107,7 +112,7 @@ public class LogEntry { return runStatus; } - + /** * Sets runStatus based its string representation. If the argument does not match one of the valid constants. * {@link RunStatus#UNKNOWN} will be used. @@ -120,7 +125,7 @@ public class LogEntry runStatus = RunStatus.UNKNOWN; } } - + /** * Sets runStatus. * @@ -130,7 +135,7 @@ public class LogEntry { this.runStatus = runStatus; } - + /** * Returns runStatusTimestamp. * @@ -140,7 +145,7 @@ public class LogEntry { return runStatusTimestamp; } - + /** * Sets runStatusTimestamp. * @@ -150,7 +155,7 @@ public class LogEntry { this.runStatusTimestamp = runStatusTimestamp; } - + /** * Returns version. * @@ -160,7 +165,7 @@ public class LogEntry { return version; } - + /** * Sets version. * @@ -176,13 +181,13 @@ public class LogEntry { StringBuilder builder = new StringBuilder(); builder.append("Version:").append(version).append(", Module:").append(moduleName); - builder.append(", Run status:").append(runStatus).append(", Time stamp:").append(runStatusTimestamp); + builder.append(", Run status:").append(runStatus).append(", Time stamp:").append( + runStatusTimestamp); if (runStatus == RunStatus.FAILED && runException != null) { builder.append(", Exception:").append(runException); } return builder.toString(); } - - + } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/MassUploadFileType.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/MassUploadFileType.java index 61a8bb26e15..719537ccde6 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/MassUploadFileType.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/MassUploadFileType.java @@ -17,21 +17,21 @@ package ch.systemsx.cisd.dbmigration; /** - * File type enumeration. - * + * File type enumeration. + * * @author Franz-Josef Elmer */ public enum MassUploadFileType { CSV(".csv"), TSV(".tsv"); - + private final String fileType; private MassUploadFileType(String fileType) { this.fileType = fileType; } - + /** * Returns the file type string including the '.'. */ @@ -41,7 +41,7 @@ public enum MassUploadFileType } /** - * Returns <code>true</code> if the specify file is of this type. + * Returns <code>true</code> if the specify file is of this type. */ public boolean isOfType(String fileName) { diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutor.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutor.java index 146000dc98e..f080d13f2a0 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutor.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutor.java @@ -40,7 +40,8 @@ import ch.systemsx.cisd.common.logging.LogFactory; */ public class SqlScriptExecutor extends JdbcDaoSupport implements ISqlScriptExecutor { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, SqlScriptExecutor.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, SqlScriptExecutor.class); /** Gives better error messages, but is a lot slower. */ private final boolean singleStepMode; @@ -51,7 +52,8 @@ public class SqlScriptExecutor extends JdbcDaoSupport implements ISqlScriptExecu this.singleStepMode = singleStepMode; } - public void execute(Script sqlScript, boolean honorSingleStepMode, ISqlScriptExecutionLogger loggerOrNull) + public void execute(Script sqlScript, boolean honorSingleStepMode, + ISqlScriptExecutionLogger loggerOrNull) { if (loggerOrNull != null) { @@ -70,12 +72,12 @@ public class SqlScriptExecutor extends JdbcDaoSupport implements ISqlScriptExecu execute(sqlStatement); } catch (BadSqlGrammarException ex2) { - throw new BadSqlGrammarException(getTask(ex2), lastSqlStatement + ">-->" + sqlStatement - + "<--<", getCause(ex2)); + throw new BadSqlGrammarException(getTask(ex2), lastSqlStatement + ">-->" + + sqlStatement + "<--<", getCause(ex2)); } catch (UncategorizedSQLException ex2) { - throw new UncategorizedSQLException(getTask(ex2), lastSqlStatement + ">-->" + sqlStatement - + "<--<", getCause(ex2)); + throw new UncategorizedSQLException(getTask(ex2), lastSqlStatement + ">-->" + + sqlStatement + "<--<", getCause(ex2)); } lastSqlStatement = sqlStatement; } @@ -89,8 +91,8 @@ public class SqlScriptExecutor extends JdbcDaoSupport implements ISqlScriptExecu } } catch (Throwable t) { - operationLog.error("Executing script '" + sqlScript.getName() + "', version " + sqlScript.getVersion() - + " failed.", t); + operationLog.error("Executing script '" + sqlScript.getName() + "', version " + + sqlScript.getVersion() + " failed.", t); if (loggerOrNull != null) { loggerOrNull.logFailure(sqlScript, t); @@ -109,7 +111,7 @@ public class SqlScriptExecutor extends JdbcDaoSupport implements ISqlScriptExecu { getJdbcTemplate().execute(script); } - + private String getTask(BadSqlGrammarException ex) { final String marker = "; bad SQL grammar ["; diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptProvider.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptProvider.java index 99cd7224b83..dee4b81952c 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptProvider.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/SqlScriptProvider.java @@ -40,7 +40,8 @@ public class SqlScriptProvider implements ISqlScriptProvider private static final String SQL_FILE_TYPE = ".sql"; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, SqlScriptProvider.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, SqlScriptProvider.class); private final String genericScriptFolder; @@ -142,10 +143,12 @@ public class SqlScriptProvider implements ISqlScriptProvider private Script tryLoadScript(String scriptName, String scriptVersion, String prefix) { - Script script = tryPrimLoadScript(specificScriptFolder + "/" + prefix, scriptName, scriptVersion); + Script script = + tryPrimLoadScript(specificScriptFolder + "/" + prefix, scriptName, scriptVersion); if (script == null) { - script = tryPrimLoadScript(genericScriptFolder + "/" + prefix, scriptName, scriptVersion); + script = + tryPrimLoadScript(genericScriptFolder + "/" + prefix, scriptName, scriptVersion); } return script; } @@ -160,7 +163,8 @@ public class SqlScriptProvider implements ISqlScriptProvider File file = new File(scriptFolder, scriptName); if (operationLog.isDebugEnabled()) { - operationLog.debug("Resource '" + resource + "' could not be found. Trying '" + file.getPath() + "'."); + operationLog.debug("Resource '" + resource + "' could not be found. Trying '" + + file.getPath() + "'."); } if (file.exists() == false) { diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2AdminDAO.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2AdminDAO.java index 2a460040380..ae42f4e8d38 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2AdminDAO.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2AdminDAO.java @@ -51,20 +51,23 @@ public class H2AdminDAO extends SimpleJdbcDaoSupport implements IDatabaseAdminDA private static final String DROP_ALL_OBJECTS_SQL = "drop all objects;"; private static final String SQL_FILE_TYPE = ".sql"; - + private static final Pattern dbDirPartPattern = Pattern.compile(".*:file:(.*?)/.*"); private static final String CREATE_TABLE_DATABASE_VERSION_LOGS_SQL = - "create table " + DatabaseVersionLogDAO.DB_VERSION_LOG + " (db_version varchar(4) not null, " + "create table " + + DatabaseVersionLogDAO.DB_VERSION_LOG + + " (db_version varchar(4) not null, " + "module_name varchar(250), run_status varchar(10), run_status_timestamp timestamp, " + "module_code bytea, run_exception bytea);"; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, H2AdminDAO.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, H2AdminDAO.class); private final String databaseName; - + private final String databaseDir; - + private final String databaseURL; private final ISqlScriptExecutor scriptExecutor; @@ -80,8 +83,8 @@ public class H2AdminDAO extends SimpleJdbcDaoSupport implements IDatabaseAdminDA * @param databaseName Name of the database. * @param databaseURL URL of the database. */ - public H2AdminDAO(DataSource dataSource, ISqlScriptExecutor scriptExecutor, IMassUploader massUploader, - String databaseName, String databaseURL) + public H2AdminDAO(DataSource dataSource, ISqlScriptExecutor scriptExecutor, + IMassUploader massUploader, String databaseName, String databaseURL) { this.scriptExecutor = scriptExecutor; this.massUploader = massUploader; @@ -165,7 +168,8 @@ public class H2AdminDAO extends SimpleJdbcDaoSupport implements IDatabaseAdminDA operationLog.error(message); throw new ConfigurationFailureException(message); } - final Script script = new Script(scriptFile.getPath(), FileUtilities.loadToString(scriptFile), version); + final Script script = + new Script(scriptFile.getPath(), FileUtilities.loadToString(scriptFile), version); return script; } @@ -176,13 +180,15 @@ public class H2AdminDAO extends SimpleJdbcDaoSupport implements IDatabaseAdminDA { if (operationLog.isDebugEnabled()) { - operationLog.debug("Searching for mass upload files in directory '" + dumpFolder.getAbsolutePath() + "'."); + operationLog.debug("Searching for mass upload files in directory '" + + dumpFolder.getAbsolutePath() + "'."); } String[] csvFiles = dumpFolder.list(new FilenameFilter() { public boolean accept(File dir, String name) { - return MassUploadFileType.CSV.isOfType(name) || MassUploadFileType.TSV.isOfType(name); + return MassUploadFileType.CSV.isOfType(name) + || MassUploadFileType.TSV.isOfType(name); } }); if (csvFiles == null) diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2MassUploader.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2MassUploader.java index 41a49c57ccc..0cf45133bd2 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2MassUploader.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2MassUploader.java @@ -55,7 +55,8 @@ import ch.systemsx.cisd.dbmigration.IMassUploader; */ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploader { - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, H2MassUploader.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, H2MassUploader.class); private final ISequenceNameMapper sequenceNameMapper; @@ -77,7 +78,8 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade final BitSet isBinaryColumn; - MassUploadRecord(final File massUploadFile, final String tableName, final BitSet isBinaryColumn) + MassUploadRecord(final File massUploadFile, final String tableName, + final BitSet isBinaryColumn) { this.massUploadFile = massUploadFile; this.tableName = tableName; @@ -90,21 +92,26 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade String task = "Get database metadata"; try { - final List<MassUploadRecord> massUploadRecords = new ArrayList<MassUploadRecord>(massUploadFiles.length); + final List<MassUploadRecord> massUploadRecords = + new ArrayList<MassUploadRecord>(massUploadFiles.length); final DatabaseMetaData dbMetaData = getConnection().getMetaData(); try { for (final File massUploadFile : massUploadFiles) { final String[] splitName = StringUtils.split(massUploadFile.getName(), "="); - assert splitName.length == 2 : "Missing '=' in name of file '" + massUploadFile.getName() + "'."; + assert splitName.length == 2 : "Missing '=' in name of file '" + + massUploadFile.getName() + "'."; final String tableNameWithExtension = splitName[1]; final boolean tsvFileType = TSV.isOfType(tableNameWithExtension); - assert tsvFileType : "Not a " + TSV.getFileType() + " file: " + massUploadFile.getName(); + assert tsvFileType : "Not a " + TSV.getFileType() + " file: " + + massUploadFile.getName(); final String tableName = - tableNameWithExtension.substring(0, tableNameWithExtension.lastIndexOf('.')); + tableNameWithExtension.substring(0, tableNameWithExtension + .lastIndexOf('.')); final BitSet isBinaryColumn = findBinaryColumns(dbMetaData, tableName); - massUploadRecords.add(new MassUploadRecord(massUploadFile, tableName, isBinaryColumn)); + massUploadRecords.add(new MassUploadRecord(massUploadFile, tableName, + isBinaryColumn)); } } finally { @@ -131,8 +138,8 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade { if (operationLog.isInfoEnabled()) { - operationLog.info("Perform mass upload of file '" + record.massUploadFile + "' to table '" - + record.tableName + "'."); + operationLog.info("Perform mass upload of file '" + record.massUploadFile + + "' to table '" + record.tableName + "'."); } final List<String[]> rows = readTSVFile(record.massUploadFile); final int numberOfRows = rows.size(); @@ -154,7 +161,8 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade return numberOfRows; } - public void setValues(final PreparedStatement ps, final int rowNo) throws SQLException + public void setValues(final PreparedStatement ps, final int rowNo) + throws SQLException { for (int colNo = 0; colNo < numberOfColumns; ++colNo) { @@ -203,7 +211,8 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade private final List<String[]> readTSVFile(final File tsvFile) throws IOException { final List<String[]> result = new ArrayList<String[]>(); - final BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtils.openInputStream(tsvFile))); + final BufferedReader reader = + new BufferedReader(new InputStreamReader(FileUtils.openInputStream(tsvFile))); try { String line = reader.readLine(); @@ -219,8 +228,8 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade } if (numberOfColumns != cols.length) { - throw new IllegalArgumentException("line '" + line + "', cols found: " + cols.length - + ", cols expected: " + numberOfColumns); + throw new IllegalArgumentException("line '" + line + "', cols found: " + + cols.length + ", cols expected: " + numberOfColumns); } for (int i = 0; i < cols.length; ++i) { @@ -251,19 +260,22 @@ public class H2MassUploader extends SimpleJdbcDaoSupport implements IMassUploade } try { - final long maxId = getSimpleJdbcTemplate().queryForLong(String.format("select max(id) from %s", tableName)); + final long maxId = + getSimpleJdbcTemplate().queryForLong( + String.format("select max(id) from %s", tableName)); final long newSequenceValue = maxId + 1; if (operationLog.isInfoEnabled()) { - operationLog.info("Updating sequence " + sequenceName + " for table " + tableName + " to value " - + newSequenceValue); + operationLog.info("Updating sequence " + sequenceName + " for table " + tableName + + " to value " + newSequenceValue); } getJdbcTemplate().execute( - String.format("alter sequence %s restart with %d", sequenceName, newSequenceValue)); + String.format("alter sequence %s restart with %d", sequenceName, + newSequenceValue)); } catch (final DataAccessException ex) { - operationLog.error("Failed to set new value for sequence '" + sequenceName + "' of table '" + tableName - + "'.", ex); + operationLog.error("Failed to set new value for sequence '" + sequenceName + + "' of table '" + tableName + "'.", ex); } } } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2StoredProcedures.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2StoredProcedures.java index ef9beab1906..1d8e022aa4f 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2StoredProcedures.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/h2/H2StoredProcedures.java @@ -32,18 +32,20 @@ public class H2StoredProcedures * Renames the sequence <var>oldName</var> into <var>newName</var> ensuring the <code>NEXTVAL()</code> will * return the right value. * - * @return The next value the sequence will deliver. + * @return The next value the sequence will deliver. */ - public static int renameSequence(Connection conn, String oldName, String newName) throws SQLException + public static int renameSequence(Connection conn, String oldName, String newName) + throws SQLException { - final ResultSet rs = conn.createStatement().executeQuery(String.format("SELECT NEXTVAL('%s')", oldName)); + final ResultSet rs = + conn.createStatement().executeQuery(String.format("SELECT NEXTVAL('%s')", oldName)); if (rs.first() == false) { throw new SQLException("Cannot get next value of sequence '" + oldName + "'"); } final int currSeqVal = rs.getInt(1); rs.close(); - conn.createStatement().execute("CREATE SEQUENCE " + newName + " START WITH " + currSeqVal); + conn.createStatement().execute("CREATE SEQUENCE " + newName + " START WITH " + currSeqVal); conn.createStatement().execute("DROP SEQUENCE " + oldName); return currSeqVal; } diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparator.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparator.java index c7bba5b658f..580c761ab81 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparator.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparator.java @@ -50,14 +50,16 @@ public class DumpPreparator { private static final Set<String> FILTERED_SCHEMA_LINES = new LinkedHashSet<String>(Arrays.asList("SET client_encoding = 'UTF8';", - "COMMENT ON SCHEMA public IS 'Standard public schema';", "CREATE PROCEDURAL LANGUAGE plpgsql;")); + "COMMENT ON SCHEMA public IS 'Standard public schema';", + "CREATE PROCEDURAL LANGUAGE plpgsql;")); public static void main(String[] args) throws IOException { if (args.length < 1) { - System.out.println("Usage: java ch.systemsx.cisd.dbmigration.postgresql.DumpPreparator " - + "<main folder> [<dump file>]"); + System.out + .println("Usage: java ch.systemsx.cisd.dbmigration.postgresql.DumpPreparator " + + "<main folder> [<dump file>]"); System.exit(1); } File destination = new File(args[0]); @@ -104,7 +106,8 @@ public class DumpPreparator BufferedReader reader = new BufferedReader(dumpReader); String line; State state = State.SCHEMA; - UploadFileManager uploadFileManager = new UploadFileManager(destinationFolder, FILTERED_SCHEMA_LINES); + UploadFileManager uploadFileManager = + new UploadFileManager(destinationFolder, FILTERED_SCHEMA_LINES); while ((line = reader.readLine()) != null) { if (line.length() != 0 && line.startsWith("--") == false) @@ -141,7 +144,8 @@ public class DumpPreparator manager.createUploadFile(matcher.group(1)); } else { - throw new IllegalArgumentException("Couldn't extract table name from the following line: " + line); + throw new IllegalArgumentException( + "Couldn't extract table name from the following line: " + line); } return IN_COPY; } @@ -236,7 +240,8 @@ public class DumpPreparator { if (currentTable == null) { - throw new IllegalStateException("No table created to add the following line: " + line); + throw new IllegalStateException("No table created to add the following line: " + + line); } if (line.startsWith("\\.")) { @@ -250,7 +255,8 @@ public class DumpPreparator { String databaseVersion = getDatabaseVersion(); File folder = createDestinationFolder(); - writeTo(folder, "schema-" + databaseVersion + ".sql", Arrays.asList(schemaScript.toString())); + writeTo(folder, "schema-" + databaseVersion + ".sql", Arrays.asList(schemaScript + .toString())); for (Table table : tables.values()) { List<String> rows = table.getRows(); @@ -259,7 +265,8 @@ public class DumpPreparator writeTo(folder, table.getUploadFileName(), rows); } } - writeTo(folder, "finish-" + databaseVersion + ".sql", Arrays.asList(finishScript.toString())); + writeTo(folder, "finish-" + databaseVersion + ".sql", Arrays.asList(finishScript + .toString())); } private void writeTo(File folder, String fileName, List<String> lines) throws IOException @@ -307,20 +314,21 @@ public class DumpPreparator { if (file.delete() == false) { - throw new IllegalStateException("Couldn't delete file '" + file.getAbsolutePath() - + "' for some unknown reasons."); + throw new IllegalStateException("Couldn't delete file '" + + file.getAbsolutePath() + "' for some unknown reasons."); } } } else { - throw new IllegalStateException("Is not a directory: " + folder.getAbsolutePath()); + throw new IllegalStateException("Is not a directory: " + + folder.getAbsolutePath()); } } else { if (folder.mkdirs() == false) { - throw new IllegalStateException("Couldn't create folder '" + folder.getAbsolutePath() - + "' for some unknown reason."); + throw new IllegalStateException("Couldn't create folder '" + + folder.getAbsolutePath() + "' for some unknown reason."); } } return folder; @@ -340,7 +348,8 @@ public class DumpPreparator Matcher matcher = VERSION_PATTERN.matcher(row); if (matcher.matches() == false) { - throw new IllegalArgumentException("Row does not start with a version number: " + row); + throw new IllegalArgumentException("Row does not start with a version number: " + + row); } String v = matcher.group(1); if (v.compareTo(result) > 0) diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLAdminDAO.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLAdminDAO.java index 89ca545f736..9cb1948abcc 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLAdminDAO.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLAdminDAO.java @@ -52,11 +52,14 @@ public class PostgreSQLAdminDAO extends SimpleJdbcDaoSupport implements IDatabas + "alter database %1$s set default_with_oids = off;"; private static final String CREATE_TABLE_DATABASE_VERSION_LOGS_SQL = - "create table " + DatabaseVersionLogDAO.DB_VERSION_LOG + " (db_version varchar(4) not null, " - + "module_name varchar(250), run_status varchar(10), run_status_timestamp timestamp, " - + "module_code bytea, run_exception bytea);"; + "create table " + + DatabaseVersionLogDAO.DB_VERSION_LOG + + " (db_version varchar(4) not null, " + + "module_name varchar(250), run_status varchar(10), run_status_timestamp timestamp, " + + "module_code bytea, run_exception bytea);"; - private static final Logger operationLog = LogFactory.getLogger(LogCategory.OPERATION, PostgreSQLAdminDAO.class); + private static final Logger operationLog = + LogFactory.getLogger(LogCategory.OPERATION, PostgreSQLAdminDAO.class); private final ISqlScriptExecutor scriptExecutor; @@ -78,8 +81,8 @@ public class PostgreSQLAdminDAO extends SimpleJdbcDaoSupport implements IDatabas * @param databaseName Name of the database. * @param databaseURL URL of the database. */ - public PostgreSQLAdminDAO(DataSource dataSource, ISqlScriptExecutor scriptExecutor, IMassUploader massUploader, - String owner, String databaseName, String databaseURL) + public PostgreSQLAdminDAO(DataSource dataSource, ISqlScriptExecutor scriptExecutor, + IMassUploader massUploader, String owner, String databaseName, String databaseURL) { this.scriptExecutor = scriptExecutor; this.massUploader = massUploader; @@ -145,15 +148,19 @@ public class PostgreSQLAdminDAO extends SimpleJdbcDaoSupport implements IDatabas private void createEmptyDatabase() { - operationLog.info("Try to create empty database '" + databaseName + "' with owner '" + owner + "'."); + operationLog.info("Try to create empty database '" + databaseName + "' with owner '" + + owner + "'."); try { - getJdbcTemplate().execute(String.format(CREATE_DATABASE_SQL_TEMPLATE, databaseName, owner)); + getJdbcTemplate().execute( + String.format(CREATE_DATABASE_SQL_TEMPLATE, databaseName, owner)); } catch (RuntimeException ex) { - if (ex instanceof DataAccessException && DBUtilities.isDuplicateDatabaseException((DataAccessException) ex)) + if (ex instanceof DataAccessException + && DBUtilities.isDuplicateDatabaseException((DataAccessException) ex)) { - operationLog.warn("Cannot create database '" + databaseName + "' since it already exists."); + operationLog.warn("Cannot create database '" + databaseName + + "' since it already exists."); } else { operationLog.error("Failed to create database '" + databaseName + "'.", ex); @@ -198,7 +205,8 @@ public class PostgreSQLAdminDAO extends SimpleJdbcDaoSupport implements IDatabas operationLog.error(message); throw new ConfigurationFailureException(message); } - final Script script = new Script(scriptFile.getPath(), FileUtilities.loadToString(scriptFile), version); + final Script script = + new Script(scriptFile.getPath(), FileUtilities.loadToString(scriptFile), version); return script; } @@ -209,13 +217,15 @@ public class PostgreSQLAdminDAO extends SimpleJdbcDaoSupport implements IDatabas { if (operationLog.isDebugEnabled()) { - operationLog.debug("Searching for mass upload files in directory '" + dumpFolder.getAbsolutePath() + "'."); + operationLog.debug("Searching for mass upload files in directory '" + + dumpFolder.getAbsolutePath() + "'."); } String[] csvFiles = dumpFolder.list(new FilenameFilter() { public boolean accept(File dir, String name) { - return MassUploadFileType.CSV.isOfType(name) || MassUploadFileType.TSV.isOfType(name); + return MassUploadFileType.CSV.isOfType(name) + || MassUploadFileType.TSV.isOfType(name); } }); if (csvFiles == null) diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLDAOFactory.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLDAOFactory.java index 143cda3b204..98b73de749f 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLDAOFactory.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLDAOFactory.java @@ -61,8 +61,9 @@ public class PostgreSQLDAOFactory implements IDAOFactory throw new CheckedExceptionTunnel(ex); } databaseDAO = - new PostgreSQLAdminDAO(context.getAdminDataSource(), sqlScriptExecutor, massUploader, context - .getOwner(), context.getDatabaseName(), context.getDatabaseURL()); + new PostgreSQLAdminDAO(context.getAdminDataSource(), sqlScriptExecutor, + massUploader, context.getOwner(), context.getDatabaseName(), context + .getDatabaseURL()); } public IDatabaseAdminDAO getDatabaseDAO() diff --git a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLMassUploader.java b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLMassUploader.java index 39232c520f0..223996c646b 100644 --- a/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLMassUploader.java +++ b/dbmigration/source/java/ch/systemsx/cisd/dbmigration/postgresql/PostgreSQLMassUploader.java @@ -63,15 +63,16 @@ public class PostgreSQLMassUploader extends SimpleJdbcDaoSupport implements IMas /** * Creates an instance for the specified data source and sequence mapper. */ - public PostgreSQLMassUploader(final DataSource dataSource, final ISequenceNameMapper sequenceNameMapper) - throws SQLException + public PostgreSQLMassUploader(final DataSource dataSource, + final ISequenceNameMapper sequenceNameMapper) throws SQLException { this.dataSource = dataSource; this.sequenceNameMapper = sequenceNameMapper; setDataSource(dataSource); } - private final CopyManager getCopyManager() throws SQLException, NoSuchFieldException, IllegalAccessException + private final CopyManager getCopyManager() throws SQLException, NoSuchFieldException, + IllegalAccessException { if (copyManager == null) { @@ -98,16 +99,19 @@ public class PostgreSQLMassUploader extends SimpleJdbcDaoSupport implements IMas try { final String[] splitName = StringUtils.split(massUploadFile.getName(), "="); - assert splitName.length == 2 : "Missing '=' in name of file '" + massUploadFile.getName() + "'."; + assert splitName.length == 2 : "Missing '=' in name of file '" + + massUploadFile.getName() + "'."; final String tableNameWithExtension = splitName[1]; final boolean csvFileType = CSV.isOfType(tableNameWithExtension); final boolean tsvFileType = TSV.isOfType(tableNameWithExtension); - assert tsvFileType || csvFileType : "Non of expected file types [" + TSV.getFileType() + ", " - + CSV.getFileType() + "]: " + massUploadFile.getName(); - final String tableName = tableNameWithExtension.substring(0, tableNameWithExtension.lastIndexOf('.')); + assert tsvFileType || csvFileType : "Non of expected file types [" + TSV.getFileType() + + ", " + CSV.getFileType() + "]: " + massUploadFile.getName(); + final String tableName = + tableNameWithExtension.substring(0, tableNameWithExtension.lastIndexOf('.')); if (operationLog.isInfoEnabled()) { - operationLog.info("Perform mass upload of file '" + massUploadFile + "' to table '" + tableName + "'."); + operationLog.info("Perform mass upload of file '" + massUploadFile + "' to table '" + + tableName + "'."); } final InputStream is = new FileInputStream(massUploadFile); try @@ -117,7 +121,8 @@ public class PostgreSQLMassUploader extends SimpleJdbcDaoSupport implements IMas getCopyManager().copyIn(tableName, is); } else { - getCopyManager().copyInQuery("COPY " + tableName + " FROM STDIN WITH CSV HEADER", is); + getCopyManager().copyInQuery( + "COPY " + tableName + " FROM STDIN WITH CSV HEADER", is); tables.add(tableName); } } finally @@ -142,26 +147,28 @@ public class PostgreSQLMassUploader extends SimpleJdbcDaoSupport implements IMas // The result returned by setval is just the value of its second argument. final long newSequenceValue = getSimpleJdbcTemplate().queryForLong( - String.format("select setval('%s', max(id)) from %s", sequenceName, tableName)); + String.format("select setval('%s', max(id)) from %s", sequenceName, + tableName)); if (operationLog.isInfoEnabled()) { - operationLog.info("Updating sequence " + sequenceName + " for table " + tableName + " to value " - + newSequenceValue); + operationLog.info("Updating sequence " + sequenceName + " for table " + tableName + + " to value " + newSequenceValue); } } catch (final DataAccessException ex) { - operationLog.error("Failed to set new value for sequence '" + sequenceName + "' of table '" + tableName - + "'.", ex); + operationLog.error("Failed to set new value for sequence '" + sequenceName + + "' of table '" + tableName + "'.", ex); } } - private final PGConnection getPGConnection() throws SQLException, NoSuchFieldException, IllegalAccessException + private final PGConnection getPGConnection() throws SQLException, NoSuchFieldException, + IllegalAccessException { return getPGConnection(dataSource.getConnection()); } - private final PGConnection getPGConnection(final Connection conn) throws SQLException, NoSuchFieldException, - IllegalAccessException + private final PGConnection getPGConnection(final Connection conn) throws SQLException, + NoSuchFieldException, IllegalAccessException { if (conn instanceof PGConnection) { @@ -169,7 +176,8 @@ public class PostgreSQLMassUploader extends SimpleJdbcDaoSupport implements IMas } if (operationLog.isDebugEnabled()) { - operationLog.debug("Found connection of type '" + conn.getClass().getCanonicalName() + "'."); + operationLog.debug("Found connection of type '" + conn.getClass().getCanonicalName() + + "'."); } final Field delegateField = getField(conn.getClass(), "_conn"); if (delegateField == null) diff --git a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBMigrationEngineTest.java b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBMigrationEngineTest.java index 5c747cc32e0..7d0affa9424 100644 --- a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBMigrationEngineTest.java +++ b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBMigrationEngineTest.java @@ -126,20 +126,25 @@ public class DBMigrationEngineTest one(scriptProvider).tryGetSchemaScript(version); expectSuccessfulExecution(new Script("schema", "schema code", version), true); one(scriptProvider).tryGetFunctionScript(version); - expectSuccessfulExecution(new Script("function", "db function code", version), false); + expectSuccessfulExecution(new Script("function", "db function code", version), + false); one(scriptProvider).tryGetDataScript(version); expectSuccessfulExecution(new Script("data", "data code", version), true); one(adminDAO).getDatabaseName(); will(returnValue("my 2. database")); } }); - final DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, true); + final DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, true); migrationEngine.migrateTo(version); - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." - + OSUtilities.LINE_SEPARATOR + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 2. database' version 042 has been successfully created.", logRecorder.getLogContent()); + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Database 'my 2. database' version 042 has been successfully created.", + logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -175,13 +180,17 @@ public class DBMigrationEngineTest will(returnValue("my 2. database")); } }); - final DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, true); + final DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, true); migrationEngine.migrateTo(version); - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." - + OSUtilities.LINE_SEPARATOR + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 2. database' version 042 has been successfully created.", logRecorder.getLogContent()); + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Database 'my 2. database' version 042 has been successfully created.", + logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -190,7 +199,8 @@ public class DBMigrationEngineTest public void testCreateFromScratchButCouldNotCreateOwner() { final String version = "042"; - final BadSqlGrammarException exception = new BadSqlGrammarException("", "", new SQLException("owner")); + final BadSqlGrammarException exception = + new BadSqlGrammarException("", "", new SQLException("owner")); context.checking(new MyExpectations() { { @@ -219,9 +229,11 @@ public class DBMigrationEngineTest { assertSame(exception, e); } - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." - + OSUtilities.LINE_SEPARATOR + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 1. database' does not exist.", logRecorder.getLogContent()); + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Database 'my 1. database' does not exist.", logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -258,12 +270,14 @@ public class DBMigrationEngineTest will(returnValue("my 2. database")); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); migrationEngine.migrateTo(version); assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 2. database' version 042 has been successfully created.", logRecorder.getLogContent()); + + "Database 'my 2. database' version 042 has been successfully created.", + logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -294,19 +308,22 @@ public class DBMigrationEngineTest one(scriptProvider).tryGetSchemaScript(version); expectSuccessfulExecution(new Script("schema", "schema code", version), true); one(scriptProvider).tryGetFunctionScript(version); - expectSuccessfulExecution(new Script("function", "db function code", version), false); + expectSuccessfulExecution(new Script("function", "db function code", version), + false); one(scriptProvider).tryGetDataScript(version); will(returnValue(null)); one(adminDAO).getDatabaseName(); will(returnValue("my 2. database")); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); migrationEngine.migrateTo(version); assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 2. database' version 042 has been successfully created.", logRecorder.getLogContent()); + + "Database 'my 2. database' version 042 has been successfully created.", + logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -337,7 +354,8 @@ public class DBMigrationEngineTest will(returnValue(null)); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); String message = "No schema script found for version 042"; try { @@ -349,8 +367,8 @@ public class DBMigrationEngineTest } assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + "Database 'my 1. database' does not exist." + OSUtilities.LINE_SEPARATOR - + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + message, logRecorder - .getLogContent()); + + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + message, + logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -382,13 +400,15 @@ public class DBMigrationEngineTest will(returnValue("my database URL")); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); migrationEngine.migrateTo(version); - assertEquals("DEBUG OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "No migration needed for database 'my database'. It has the right version (042)." - + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Using database 'my database URL'", + assertEquals( + "DEBUG OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "No migration needed for database 'my database'. It has the right version (042)." + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Using database 'my database URL'", logRecorder.getLogContent()); context.assertIsSatisfied(); @@ -421,28 +441,35 @@ public class DBMigrationEngineTest one(adminDAO).getDatabaseURL(); will(returnValue("my database URL")); one(scriptProvider).tryGetMigrationScript(fromVersion, "100"); - expectSuccessfulExecution(new Script("m-099-100", "code 099 100", toVersion), true); + expectSuccessfulExecution(new Script("m-099-100", "code 099 100", toVersion), + true); one(scriptProvider).tryGetMigrationScript("100", toVersion); - expectSuccessfulExecution(new Script("m-100-101", "code 100 101", toVersion), true); + expectSuccessfulExecution(new Script("m-100-101", "code 100 101", toVersion), + true); one(adminDAO).getDatabaseName(); will(returnValue("my 2. database")); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); migrationEngine.migrateTo(toVersion); String logContent = logRecorder.getLogContent(); logContent = logContent.replaceAll("\\d+ msec", "0 msec"); - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Trying to migrate database 'my 1. database' from version 099 to 101." + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Successfully migrated from version 099 to 100 in 0 msec" + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Successfully migrated from version 100 to 101 in 0 msec" + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Database 'my 2. database' successfully migrated from version 099 to 101." - + OSUtilities.LINE_SEPARATOR - + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Using database 'my database URL'", + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Trying to migrate database 'my 1. database' from version 099 to 101." + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Successfully migrated from version 099 to 100 in 0 msec" + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Successfully migrated from version 100 to 101 in 0 msec" + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + "Database 'my 2. database' successfully migrated from version 099 to 101." + + OSUtilities.LINE_SEPARATOR + + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Using database 'my database URL'", logContent); context.assertIsSatisfied(); @@ -477,7 +504,8 @@ public class DBMigrationEngineTest will(returnValue("my 2. database")); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); String errorMessage = "Cannot migrate database 'my 2. database' from version 099 to 100 because of " @@ -491,9 +519,10 @@ public class DBMigrationEngineTest assertEquals(errorMessage, e.getMessage()); } assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Trying to migrate database 'my 1. database' from version 099 to 101." + OSUtilities.LINE_SEPARATOR - + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + errorMessage, logRecorder - .getLogContent()); + + "Trying to migrate database 'my 1. database' from version 099 to 101." + + OSUtilities.LINE_SEPARATOR + + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + errorMessage, logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -524,9 +553,11 @@ public class DBMigrationEngineTest will(returnValue("my database")); } }); - DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); - String errorMessage = "Cannot revert database 'my database' from version 101 to earlier version 099."; + String errorMessage = + "Cannot revert database 'my database' from version 101 to earlier version 099."; try { migrationEngine.migrateTo(toVersion); @@ -535,8 +566,8 @@ public class DBMigrationEngineTest { assertEquals(errorMessage, e.getMessage()); } - assertEquals("ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + errorMessage, logRecorder - .getLogContent()); + assertEquals("ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + errorMessage, logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -571,9 +602,11 @@ public class DBMigrationEngineTest { assertEquals(message, e.getMessage()); } - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." - + OSUtilities.LINE_SEPARATOR + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + message, logRecorder - .getLogContent()); + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." + + OSUtilities.LINE_SEPARATOR + + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + message, logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -605,7 +638,9 @@ public class DBMigrationEngineTest }); DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, true); - String message = "Inconsistent database: Last creation/migration didn't succeed. Last log entry: " + logEntry; + String message = + "Inconsistent database: Last creation/migration didn't succeed. Last log entry: " + + logEntry; try { migrationEngine.migrateTo("001"); @@ -614,9 +649,11 @@ public class DBMigrationEngineTest { assertEquals(message, e.getMessage()); } - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." - + OSUtilities.LINE_SEPARATOR + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + message, logRecorder - .getLogContent()); + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." + + OSUtilities.LINE_SEPARATOR + + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + message, logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -649,7 +686,9 @@ public class DBMigrationEngineTest }); DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, true); - String message = "Inconsistent database: Last creation/migration didn't succeed. Last log entry: " + logEntry; + String message = + "Inconsistent database: Last creation/migration didn't succeed. Last log entry: " + + logEntry; try { migrationEngine.migrateTo("001"); @@ -658,9 +697,11 @@ public class DBMigrationEngineTest { assertEquals(message, e.getMessage()); } - assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." - + OSUtilities.LINE_SEPARATOR + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + message, logRecorder - .getLogContent()); + assertEquals( + "INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - Dropping database." + + OSUtilities.LINE_SEPARATOR + + "ERROR OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " + + message, logRecorder.getLogContent()); context.assertIsSatisfied(); } @@ -697,7 +738,8 @@ public class DBMigrationEngineTest will(throwException(exception)); } }); - final DBMigrationEngine migrationEngine = new DBMigrationEngine(daoFactory, scriptProvider, false); + final DBMigrationEngine migrationEngine = + new DBMigrationEngine(daoFactory, scriptProvider, false); try { @@ -708,7 +750,8 @@ public class DBMigrationEngineTest assertSame(exception, e); } assertEquals("INFO OPERATION.ch.systemsx.cisd.dbmigration.DBMigrationEngine - " - + "Trying to migrate database 'my database' from version 001 to 002.", logRecorder.getLogContent()); + + "Trying to migrate database 'my database' from version 001 to 002.", logRecorder + .getLogContent()); context.assertIsSatisfied(); } diff --git a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBUtilitiesTest.java b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBUtilitiesTest.java index bdc5057696b..4d4bb05ea61 100644 --- a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBUtilitiesTest.java +++ b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/DBUtilitiesTest.java @@ -61,15 +61,19 @@ public class DBUtilitiesTest @Test public void testSplitSqlStatementsOneStatementOnMultipleLines() { - assertEquals(Arrays.asList("statement part1 statement part2;", "statement2.1 statement2.2;"), DBUtilities - .splitSqlStatements("statement part1 \n statement part2 ;\n statement2.1\nstatement2.2 ; ")); + assertEquals( + Arrays.asList("statement part1 statement part2;", "statement2.1 statement2.2;"), + DBUtilities + .splitSqlStatements("statement part1 \n statement part2 ;\n statement2.1\nstatement2.2 ; ")); } @Test public void testSplitSqlStatementsComments() { - assertEquals(Arrays.asList("statement1 statement2;"), DBUtilities - .splitSqlStatements("statement1 -- comment\n -- just comments; bla\n statement2; -- another comment")); + assertEquals( + Arrays.asList("statement1 statement2;"), + DBUtilities + .splitSqlStatements("statement1 -- comment\n -- just comments; bla\n statement2; -- another comment")); } } diff --git a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutorTest.java b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutorTest.java index 5f5a3815bfc..9ab0004bc75 100644 --- a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutorTest.java +++ b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptExecutorTest.java @@ -43,13 +43,14 @@ public class SqlScriptExecutorTest private class TestSqlScriptExecutor extends SqlScriptExecutor { private final List<String> executions; - + private final Error th; public TestSqlScriptExecutor(boolean singleStepMode) { this(null, singleStepMode); } + public TestSqlScriptExecutor(Error th, boolean singleStepMode) { super(new DelegatingDataSource(), singleStepMode); @@ -90,7 +91,8 @@ public class SqlScriptExecutorTest scriptExecutor.execute(simpleScript1, true, null); scriptExecutor.execute(simpleScript2, true, null); assertEquals(2, scriptExecutor.getExecutions().size()); - assertEquals(Arrays.asList(simpleScriptContent1, simpleScriptContent2), scriptExecutor.getExecutions()); + assertEquals(Arrays.asList(simpleScriptContent1, simpleScriptContent2), scriptExecutor + .getExecutions()); } @Test @@ -104,8 +106,8 @@ public class SqlScriptExecutorTest scriptExecutor.execute(simpleScript1, true, null); scriptExecutor.execute(simpleScript2, true, null); assertEquals(3, scriptExecutor.getExecutions().size()); - assertEquals(Arrays.asList("statement1;", "statement2;", "statement3.1 statement3.2;"), scriptExecutor - .getExecutions()); + assertEquals(Arrays.asList("statement1;", "statement2;", "statement3.1 statement3.2;"), + scriptExecutor.getExecutions()); } @Test @@ -119,13 +121,13 @@ public class SqlScriptExecutorTest final Script simpleScript = new Script("script1", simpleScriptContent, "VERSION"); final ISqlScriptExecutionLogger logger = context.mock(ISqlScriptExecutionLogger.class); context.checking(new Expectations() - { { - one(logger).logStart(simpleScript); - one(logger).logSuccess(simpleScript); - } - - }); + { + one(logger).logStart(simpleScript); + one(logger).logSuccess(simpleScript); + } + + }); scriptExecutor.execute(simpleScript, true, logger); } finally { @@ -137,7 +139,7 @@ public class SqlScriptExecutorTest { private static final long serialVersionUID = 1L; } - + @Test(expectedExceptions = MyError.class) public void testLoggingScriptThrowsException() { @@ -150,13 +152,13 @@ public class SqlScriptExecutorTest final Script simpleScript = new Script("script1", simpleScriptContent, "VERSION"); final ISqlScriptExecutionLogger logger = context.mock(ISqlScriptExecutionLogger.class); context.checking(new Expectations() - { { - one(logger).logStart(simpleScript); - one(logger).logFailure(simpleScript, error); - } - - }); + { + one(logger).logStart(simpleScript); + one(logger).logFailure(simpleScript, error); + } + + }); scriptExecutor.execute(simpleScript, true, logger); } finally { diff --git a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptProviderTest.java b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptProviderTest.java index d3509490e2f..243b58e0c80 100644 --- a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptProviderTest.java +++ b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/SqlScriptProviderTest.java @@ -48,9 +48,11 @@ public class SqlScriptProviderTest private static final String DB_ENGINE_CODE = "dbengine"; - private static final File TEMP_SCHEMA_SCRIPT_ROOT_FOLDER = new File(TEMPORARY_SCHEMA_SCRIPT_FOLDER_NAME); + private static final File TEMP_SCHEMA_SCRIPT_ROOT_FOLDER = + new File(TEMPORARY_SCHEMA_SCRIPT_FOLDER_NAME); - private static final File TEMP_SCHEMA_GENERIC_SCRIPT_FOLDER = new File(TEMP_SCHEMA_SCRIPT_ROOT_FOLDER, "generic"); + private static final File TEMP_SCHEMA_GENERIC_SCRIPT_FOLDER = + new File(TEMP_SCHEMA_SCRIPT_ROOT_FOLDER, "generic"); private static final File TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER = new File(TEMP_SCHEMA_SCRIPT_ROOT_FOLDER, DB_ENGINE_CODE); @@ -73,24 +75,29 @@ public class SqlScriptProviderTest genericSchemaVersionFolder.mkdirs(); specificSchemaVersionFolder.mkdirs(); write(new File(specificSchemaVersionFolder, "schema-" + VERSION + ".sql"), "code: schema"); - write(new File(specificSchemaVersionFolder, "function-" + VERSION + ".sql"), "code: function"); + write(new File(specificSchemaVersionFolder, "function-" + VERSION + ".sql"), + "code: function"); final File migrationFolder = new File(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER, MIGRATION); migrationFolder.mkdir(); - write(new File(migrationFolder, "migration-" + VERSION + "-" + VERSION2 + ".sql"), "code: migration"); + write(new File(migrationFolder, "migration-" + VERSION + "-" + VERSION2 + ".sql"), + "code: migration"); write(new File(specificSchemaVersionFolder, "data-" + VERSION + ".sql"), "code: data"); - sqlScriptProvider = new SqlScriptProvider(TEMPORARY_SCHEMA_SCRIPT_FOLDER_NAME, DB_ENGINE_CODE); + sqlScriptProvider = + new SqlScriptProvider(TEMPORARY_SCHEMA_SCRIPT_FOLDER_NAME, DB_ENGINE_CODE); dumpFile = new File(sqlScriptProvider.getDumpFolder(VERSION), ".DUMP"); } private File createSpecificSchemaFolder() { - final File specificSchemaVersionFolder = new File(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER, VERSION); + final File specificSchemaVersionFolder = + new File(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER, VERSION); return specificSchemaVersionFolder; } private File createGenericSchemaFolder() { - final File specificSchemaVersionFolder = new File(TEMP_SCHEMA_GENERIC_SCRIPT_FOLDER, VERSION); + final File specificSchemaVersionFolder = + new File(TEMP_SCHEMA_GENERIC_SCRIPT_FOLDER, VERSION); return specificSchemaVersionFolder; } @@ -137,28 +144,30 @@ public class SqlScriptProviderTest { final Script script = sqlScriptProvider.tryGetSchemaScript(VERSION); assertNotNull(script); - assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER.getPath() + "/" + VERSION + "/schema-" + VERSION + ".sql", - script.getName()); + assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER.getPath() + "/" + VERSION + "/schema-" + + VERSION + ".sql", script.getName()); assertEquals("code: schema", script.getCode().trim()); } - // Note: we make it dependent on testGetSchemaScript(), because we delete the specific schema script + // Note: we make it dependent on testGetSchemaScript(), because we delete the specific schema script // in this test case and thus testGetSchemaScript() would fail if run after this test case. @Test(dependsOnMethods = "testGetSchemaScript") public void testGetGenericSchemaScript() { - final File specificSchemaScript = new File(createSpecificSchemaFolder(), "schema-" + VERSION + ".sql"); + final File specificSchemaScript = + new File(createSpecificSchemaFolder(), "schema-" + VERSION + ".sql"); specificSchemaScript.delete(); - final File genericSchemaScript = new File(createGenericSchemaFolder(), "schema-" + VERSION + ".sql"); + final File genericSchemaScript = + new File(createGenericSchemaFolder(), "schema-" + VERSION + ".sql"); final String genericSchemaScriptContent = "code: generic schema"; write(genericSchemaScript, genericSchemaScriptContent); final Script script = sqlScriptProvider.tryGetSchemaScript(VERSION); assertNotNull(script); - assertEquals(TEMP_SCHEMA_GENERIC_SCRIPT_FOLDER.getPath() + "/" + VERSION + "/schema-" + VERSION + ".sql", - script.getName()); + assertEquals(TEMP_SCHEMA_GENERIC_SCRIPT_FOLDER.getPath() + "/" + VERSION + "/schema-" + + VERSION + ".sql", script.getName()); assertEquals(genericSchemaScriptContent, script.getCode().trim()); } - + @Test public void testGetNonExistingSchemaScript() { @@ -170,8 +179,8 @@ public class SqlScriptProviderTest { final Script script = sqlScriptProvider.tryGetFunctionScript(VERSION); assertNotNull(script); - assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER.getPath() + "/" + VERSION + "/function-" + VERSION + ".sql", - script.getName()); + assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER.getPath() + "/" + VERSION + "/function-" + + VERSION + ".sql", script.getName()); assertEquals("code: function", script.getCode().trim()); } @@ -185,7 +194,8 @@ public class SqlScriptProviderTest public void testGetDataScript() { Script script = sqlScriptProvider.tryGetDataScript(VERSION); - assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER + "/" + VERSION + "/data-" + VERSION + ".sql", script.getName()); + assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER + "/" + VERSION + "/data-" + VERSION + + ".sql", script.getName()); assertEquals("code: data", script.getCode().trim()); } @@ -199,8 +209,8 @@ public class SqlScriptProviderTest public void testGetMigrationScript() { Script script = sqlScriptProvider.tryGetMigrationScript(VERSION, VERSION2); - assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER.getPath() + "/" + MIGRATION + "/migration-" + VERSION + "-" - + VERSION2 + ".sql", script.getName()); + assertEquals(TEMP_SCHEMA_SPECIFIC_SCRIPT_FOLDER.getPath() + "/" + MIGRATION + "/migration-" + + VERSION + "-" + VERSION2 + ".sql", script.getName()); assertEquals("code: migration", script.getCode().trim()); } diff --git a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/h2/H2TestStoredProcedures.java b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/h2/H2TestStoredProcedures.java index f61903f811d..8bda7836748 100644 --- a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/h2/H2TestStoredProcedures.java +++ b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/h2/H2TestStoredProcedures.java @@ -35,7 +35,8 @@ public class H2TestStoredProcedures { if (actual != expected) { - throw new SQLException(String.format("%s: expected:%d, but actual: %d", message, expected, actual)); + throw new SQLException(String.format("%s: expected:%d, but actual: %d", message, + expected, actual)); } return 0; } @@ -46,12 +47,13 @@ public class H2TestStoredProcedures * * @return 0. */ - public static int assertMinimum(String message, long minExpected, long actual) throws SQLException + public static int assertMinimum(String message, long minExpected, long actual) + throws SQLException { if (actual < minExpected) { - throw new SQLException(String.format("%s: Minimum expected:%d, but actual: %d", message, minExpected, - actual)); + throw new SQLException(String.format("%s: Minimum expected:%d, but actual: %d", + message, minExpected, actual)); } return 0; } diff --git a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparatorTest.java b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparatorTest.java index 9d45b40a3ea..5fa18308984 100644 --- a/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparatorTest.java +++ b/dbmigration/sourceTest/java/ch/systemsx/cisd/dbmigration/postgresql/DumpPreparatorTest.java @@ -27,85 +27,78 @@ import org.testng.annotations.Test; import ch.systemsx.cisd.common.utilities.FileUtilities; /** - * - * * @author Franz-Josef Elmer */ public class DumpPreparatorTest { private static final File TEST_FOLDER = new File("targets/unit-test-wd/dump-preparator"); - - private static final String EXAMPLE = "--\n" + - "-- PostgreSQL database dump\n" + - "--\n" + - "\n" + - "-- Started on 2007-11-28 13:36:10\n" + - "\n" + - "SET client_encoding = \'UTF8\';\n" + - "SET standard_conforming_strings = off;\n" + - "COMMENT ON SCHEMA public IS 'Standard public schema';\n" + - "CREATE PROCEDURAL LANGUAGE plpgsql;\n" + - "--\n" + - "-- TOC entry 1908 (class 0 OID 326942)\n" + - "-- Dependencies: 1374\n" + - "-- Data for Name: data; Type: TABLE DATA; Schema: public; Owner: felmer\n" + - "--\n" + - "\n" + - "COPY data (id, registration_timestamp, obty_id) FROM stdin;\n" + - "\\.\n" + - "\n" + - "\n" + - "--\n" + - "-- TOC entry 1890 (class 0 OID 326868)\n" + - "-- Dependencies: 1356\n" + - "-- Data for Name: data_types; Type: TABLE DATA; Schema: public; Owner: felmer\n" + - "--\n" + - "\n" + - "COPY data_types (id, code, description) FROM stdin;\n" + - "1\tVARCHAR\tVariable length character\n" + - "2\tINTEGER\tInteger\n" + - "3\tREAL\tReal number, i.e. an inexact, variable-precision numeric type\n" + - "\\.\n" + - "\n" + - "\n" + - "--\n" + - "-- TOC entry 1891 (class 0 OID 326873)\n" + - "-- Dependencies: 1357\n" + - "-- Data for Name: data_values; Type: TABLE DATA; Schema: public; Owner: felmer\n" + - "--\n" + - "\n" + - "COPY data_values (id, data_id, saco_id, value) FROM stdin;\n" + - "\\.\n" + - "\n" + - "\n" + - "--\n" + - "-- TOC entry 1887 (class 0 OID 326837)\n" + - "-- Dependencies: 1353\n" + - "-- Data for Name: database_version_logs; Type: TABLE DATA; Schema: public; Owner: felmer\n" + - "--\n" + - "\n" + - "COPY database_version_logs (db_version, module_name, run_status) FROM stdin;\n" + - "011\tsource/sql/postgresql/010/schema-010.sql\tSUCCESS 2007-11-22 08:46:04.25\n" + - "010\tsource/sql/postgresql/010/data-010.sql\tSUCCESS 2007-11-22 08:46:04.53\n" + - "\\.\n" + - "\n" + - "\n" + - "\n" + - "--\n" + - "-- TOC entry 1823 (class 2606 OID 327015)\n" + - "-- Dependencies: 1374 1374\n" + - "-- Name: data_pk; Type: CONSTRAINT; Schema: public; Owner: felmer; Tablespace: \n" + - "--\n" + - "\n" + - "ALTER TABLE ONLY data\n" + - " ADD CONSTRAINT data_pk PRIMARY KEY (id);\n" + - "\n" + - "-- Completed on 2007-11-28 13:36:13\n" + - "\n" + - "--\n" + - "-- PostgreSQL database dump complete\n" + - "--\n"; - + + private static final String EXAMPLE = + "--\n" + + "-- PostgreSQL database dump\n" + + "--\n" + + "\n" + + "-- Started on 2007-11-28 13:36:10\n" + + "\n" + + "SET client_encoding = \'UTF8\';\n" + + "SET standard_conforming_strings = off;\n" + + "COMMENT ON SCHEMA public IS 'Standard public schema';\n" + + "CREATE PROCEDURAL LANGUAGE plpgsql;\n" + + "--\n" + + "-- TOC entry 1908 (class 0 OID 326942)\n" + + "-- Dependencies: 1374\n" + + "-- Data for Name: data; Type: TABLE DATA; Schema: public; Owner: felmer\n" + + "--\n" + + "\n" + + "COPY data (id, registration_timestamp, obty_id) FROM stdin;\n" + + "\\.\n" + + "\n" + + "\n" + + "--\n" + + "-- TOC entry 1890 (class 0 OID 326868)\n" + + "-- Dependencies: 1356\n" + + "-- Data for Name: data_types; Type: TABLE DATA; Schema: public; Owner: felmer\n" + + "--\n" + + "\n" + + "COPY data_types (id, code, description) FROM stdin;\n" + + "1\tVARCHAR\tVariable length character\n" + + "2\tINTEGER\tInteger\n" + + "3\tREAL\tReal number, i.e. an inexact, variable-precision numeric type\n" + + "\\.\n" + + "\n" + + "\n" + + "--\n" + + "-- TOC entry 1891 (class 0 OID 326873)\n" + + "-- Dependencies: 1357\n" + + "-- Data for Name: data_values; Type: TABLE DATA; Schema: public; Owner: felmer\n" + + "--\n" + + "\n" + + "COPY data_values (id, data_id, saco_id, value) FROM stdin;\n" + + "\\.\n" + + "\n" + + "\n" + + "--\n" + + "-- TOC entry 1887 (class 0 OID 326837)\n" + + "-- Dependencies: 1353\n" + + "-- Data for Name: database_version_logs; Type: TABLE DATA; Schema: public; Owner: felmer\n" + + "--\n" + + "\n" + + "COPY database_version_logs (db_version, module_name, run_status) FROM stdin;\n" + + "011\tsource/sql/postgresql/010/schema-010.sql\tSUCCESS 2007-11-22 08:46:04.25\n" + + "010\tsource/sql/postgresql/010/data-010.sql\tSUCCESS 2007-11-22 08:46:04.53\n" + + "\\.\n" + + "\n" + + "\n" + + "\n" + + "--\n" + + "-- TOC entry 1823 (class 2606 OID 327015)\n" + + "-- Dependencies: 1374 1374\n" + + "-- Name: data_pk; Type: CONSTRAINT; Schema: public; Owner: felmer; Tablespace: \n" + + "--\n" + "\n" + "ALTER TABLE ONLY data\n" + + " ADD CONSTRAINT data_pk PRIMARY KEY (id);\n" + "\n" + + "-- Completed on 2007-11-28 13:36:13\n" + "\n" + "--\n" + + "-- PostgreSQL database dump complete\n" + "--\n"; + @Test public void test() throws IOException { @@ -117,16 +110,18 @@ public class DumpPreparatorTest DumpPreparator.createUploadFiles(reader, folder); assertEquals(true, folder.isDirectory()); - assertEquals("SET standard_conforming_strings = off;\n\n", FileUtilities.loadToString(new File(folder, - "schema-011.sql"))); + assertEquals("SET standard_conforming_strings = off;\n\n", FileUtilities + .loadToString(new File(folder, "schema-011.sql"))); assertEquals("1\tVARCHAR\tVariable length character\n" + "2\tINTEGER\tInteger\n" - + "3\tREAL\tReal number, i.e. an inexact, variable-precision numeric type\n", FileUtilities - .loadToString(new File(folder, "002=data_types.tsv"))); - assertEquals("011\tsource/sql/postgresql/010/schema-010.sql\tSUCCESS 2007-11-22 08:46:04.25\n" - + "010\tsource/sql/postgresql/010/data-010.sql\tSUCCESS 2007-11-22 08:46:04.53\n", FileUtilities - .loadToString(new File(folder, "004=database_version_logs.tsv"))); - assertEquals("ALTER TABLE ONLY data\n" + " ADD CONSTRAINT data_pk PRIMARY KEY (id);\n\n", FileUtilities - .loadToString(new File(folder, "finish-011.sql"))); + + "3\tREAL\tReal number, i.e. an inexact, variable-precision numeric type\n", + FileUtilities.loadToString(new File(folder, "002=data_types.tsv"))); + assertEquals( + "011\tsource/sql/postgresql/010/schema-010.sql\tSUCCESS 2007-11-22 08:46:04.25\n" + + "010\tsource/sql/postgresql/010/data-010.sql\tSUCCESS 2007-11-22 08:46:04.53\n", + FileUtilities.loadToString(new File(folder, "004=database_version_logs.tsv"))); + assertEquals( + "ALTER TABLE ONLY data\n" + " ADD CONSTRAINT data_pk PRIMARY KEY (id);\n\n", + FileUtilities.loadToString(new File(folder, "finish-011.sql"))); assertEquals(4, folder.listFiles().length); } } -- GitLab