diff --git a/bitrepository-alarm-service/src/license/THIRD-PARTY.properties b/bitrepository-alarm-service/src/license/THIRD-PARTY.properties index 4f91e7094..f97cbef53 100644 --- a/bitrepository-alarm-service/src/license/THIRD-PARTY.properties +++ b/bitrepository-alarm-service/src/license/THIRD-PARTY.properties @@ -1,6 +1,6 @@ ### # #%L -# Bitrepository Alarm Service +# BitRepository Alarm Service # %% # Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark # %% diff --git a/bitrepository-alarm-service/src/main/assembly/assembly.xml b/bitrepository-alarm-service/src/main/assembly/assembly.xml index 908f02075..bd845407d 100644 --- a/bitrepository-alarm-service/src/main/assembly/assembly.xml +++ b/bitrepository-alarm-service/src/main/assembly/assembly.xml @@ -1,6 +1,6 @@ + xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> Bitrepository integrityservice Bitrepository-integrityservice @@ -33,7 +33,7 @@ javax.ws.rs.Application org.bitrepository.integrityservice.web.IntegrityServiceRestApplication - 1 + 1 Bitrepository-integrityservice diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java index 67e42179c..46b19fd0f 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityDatabaseTestCase.java @@ -21,9 +21,6 @@ */ package org.bitrepository.integrityservice; -import java.math.BigInteger; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileIDsData; import org.bitrepository.bitrepositoryelements.FileIDsData.FileIDsDataItems; @@ -40,6 +37,9 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; +import java.math.BigInteger; +import java.util.List; + public abstract class IntegrityDatabaseTestCase extends ExtendedTestCase { protected Settings settings; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java index 13cd435bc..743a48350 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/IntegrityWorkflowSchedulerTest.java @@ -24,7 +24,7 @@ //import org.bitrepository.common.settings.Settings; //import org.bitrepository.common.settings.TestSettingsProvider; //import org.bitrepository.integrityservice.mocks.MockWorkflow; -//import org.bitrepository.integrityservice.scheduler.TimerbasedScheduler; +//import org.bitrepository.integrityservice.scheduler.TimerBasedScheduler; //import org.bitrepository.integrityservice.scheduler.workflow.Workflow; //import org.jaccept.structure.ExtendedTestCase; //import org.testng.Assert; @@ -48,7 +48,7 @@ // public void testSchedulerContainingWorkflows() { // addDescription("Test that schedulers call all workflow at the given intervals."); // addStep("Setup a scheduler and validate initial state", "No errors and no workflows"); -// TimerbasedScheduler scheduler = new TimerbasedScheduler(settings); +// TimerBasedScheduler scheduler = new TimerBasedScheduler(settings); // Assert.assertEquals(scheduler.getJobs().size(), 0, "Should not be any workflows in the scheduler."); // // addStep("Make a new workflow, add it to the scheduler and extract it afterwards.", @@ -76,7 +76,7 @@ // addStep("Setup the variables and such.", "Should not be able to fail here."); // String taskName = "MockWorkFlow"; // settings.getReferenceSettings().getIntegrityServiceSettings().setSchedulerInterval(INTERVAL); -// TimerbasedScheduler scheduler = new TimerbasedScheduler(settings); +// TimerBasedScheduler scheduler = new TimerBasedScheduler(settings); // // addStep("Create a workflow", "Should not have been called yet been called."); // MockWorkflow workflow = new MockWorkflow(INTERVAL + INTERVAL_DELAY, taskName); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java index c2809a8f1..0d9530b3e 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/FileInfoTest.java @@ -21,14 +21,14 @@ */ package org.bitrepository.integrityservice.cache; -import javax.xml.datatype.DatatypeConstants; -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.common.utils.CalendarUtils; import org.jaccept.structure.ExtendedTestCase; import org.testng.Assert; import org.testng.annotations.Test; +import javax.xml.datatype.DatatypeConstants; +import javax.xml.datatype.XMLGregorianCalendar; + public class FileInfoTest extends ExtendedTestCase { private static final String FILE_ID = "TEST-FILE"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java index 2f47f3380..77d783d7f 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDAOTest.java @@ -24,18 +24,6 @@ */ package org.bitrepository.integrityservice.cache; -import java.math.BigInteger; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileIDsData; import org.bitrepository.bitrepositoryelements.FileIDsData.FileIDsDataItems; @@ -51,6 +39,18 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; + public class IntegrityDAOTest extends IntegrityDatabaseTestCase { String TEST_PILLAR_1 = "MY-TEST-PILLAR-1"; String TEST_PILLAR_2 = "MY-TEST-PILLAR-2"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java index bbccc4bcf..371cef215 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDBToolsTest.java @@ -21,14 +21,6 @@ */ package org.bitrepository.integrityservice.cache; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileIDsData; import org.bitrepository.bitrepositoryelements.FileIDsData.FileIDsDataItems; @@ -45,6 +37,14 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + public class IntegrityDBToolsTest extends IntegrityDatabaseTestCase { String TEST_PILLAR_1 = "MY-TEST-PILLAR-1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java index c04fc3b58..eb2b0c896 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/cache/IntegrityDatabaseTest.java @@ -24,15 +24,6 @@ */ package org.bitrepository.integrityservice.cache; -import static org.mockito.Mockito.mock; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Map; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileIDsData; import org.bitrepository.bitrepositoryelements.FileIDsData.FileIDsDataItems; @@ -47,6 +38,15 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import static org.mockito.Mockito.mock; + public class IntegrityDatabaseTest extends IntegrityDatabaseTestCase { AuditTrailManager auditManager; String TEST_PILLAR_1 = "MY-TEST-PILLAR-1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java index 4b2e8d0d9..91b5ac4a1 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/checking/MaxChecksumAgeProviderTest.java @@ -21,12 +21,12 @@ */ package org.bitrepository.integrityservice.checking; -import java.math.BigInteger; - import org.bitrepository.settings.referencesettings.ObsoleteChecksumSettings; import org.jaccept.structure.ExtendedTestCase; import org.testng.annotations.Test; +import java.math.BigInteger; + import static org.testng.Assert.assertEquals; public class MaxChecksumAgeProviderTest extends ExtendedTestCase{ diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java index 58a0387cb..c39fb3183 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/BasicIntegrityReporterTest.java @@ -22,11 +22,11 @@ package org.bitrepository.integrityservice.reports; -import java.io.File; - import org.jaccept.structure.ExtendedTestCase; import org.testng.annotations.Test; +import java.io.File; + import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java index 52f85fb6d..4d69a810b 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/reports/ExampleReportGenerationTest.java @@ -21,6 +21,9 @@ */ package org.bitrepository.integrityservice.reports; +import org.jaccept.structure.ExtendedTestCase; +import org.testng.annotations.Test; + import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -28,9 +31,6 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; -import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; - public class ExampleReportGenerationTest extends ExtendedTestCase { diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java index 9f1473ff2..081175372 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/stresstest/DatabaseStressTests.java @@ -21,11 +21,6 @@ */ package org.bitrepository.integrityservice.stresstest; -import java.math.BigInteger; -import java.util.Date; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.FileIDsData; import org.bitrepository.bitrepositoryelements.FileIDsData.FileIDsDataItems; import org.bitrepository.bitrepositoryelements.FileIDsDataItem; @@ -47,6 +42,10 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigInteger; +import java.util.Date; + public class DatabaseStressTests extends ExtendedTestCase { private static final String PILLAR_1 = "pillar1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java index 10b49e263..cd9853a7a 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityContributorsTest.java @@ -21,14 +21,12 @@ */ package org.bitrepository.integrityservice.workflow; +import org.testng.Assert; +import org.testng.annotations.Test; + import java.util.Arrays; import java.util.Set; -import javax.validation.constraints.AssertTrue; - -import org.testng.annotations.Test; -import org.testng.Assert; - public class IntegrityContributorsTest { diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java index 6285c4141..e1e8abe2f 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/IntegrityWorkflowManagerTest.java @@ -25,7 +25,7 @@ import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; import org.bitrepository.common.utils.SettingsUtils; -import org.bitrepository.service.scheduler.TimerbasedScheduler; +import org.bitrepository.service.scheduler.TimerBasedScheduler; import org.bitrepository.service.workflow.WorkflowManager; import org.bitrepository.settings.referencesettings.Collections; import org.bitrepository.settings.referencesettings.Schedule; @@ -48,14 +48,14 @@ public class IntegrityWorkflowManagerTest extends ExtendedTestCase { private Settings settings; private WorkflowSettings workflowSettings; - private TimerbasedScheduler scheduler; + private TimerBasedScheduler scheduler; private String collection1ID, collection2ID; private TestWorkflow workflow1, workflow2; @BeforeMethod(alwaysRun = true) public void setup() { - scheduler = mock(TimerbasedScheduler.class); + scheduler = mock(TimerBasedScheduler.class); settings = TestSettingsProvider.reloadSettings(this.getClass().getSimpleName()); workflowSettings = new WorkflowSettings(); WorkflowConfiguration workflowConfiguration = new WorkflowConfiguration(); diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java index f5d2cd176..07ba6c040 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/RepairMissingFilesWorkflowTest.java @@ -21,25 +21,6 @@ */ package org.bitrepository.integrityservice.workflow; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.client.eventhandler.CompleteEvent; import org.bitrepository.client.eventhandler.EventHandler; @@ -61,6 +42,25 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + public class RepairMissingFilesWorkflowTest extends ExtendedTestCase { private static final String PILLAR_1 = "pillar1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java index 41906c8dc..3d1b85b57 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/SaltedChecksumWorkflowTest.java @@ -21,19 +21,6 @@ */ package org.bitrepository.integrityservice.workflow; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.times; - -import java.util.Arrays; - import org.bitrepository.access.getchecksums.conversation.ChecksumsCompletePillarEvent; import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; @@ -60,6 +47,19 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.util.Arrays; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + public class SaltedChecksumWorkflowTest extends ExtendedTestCase { private static final String PILLAR_1 = "pillar1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java index 1078f4a8d..83891a277 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/HandleChecksumValidationStepTest.java @@ -21,14 +21,6 @@ */ package org.bitrepository.integrityservice.workflow.step; -import static org.mockito.Mockito.mock; - -import java.io.File; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileAction; import org.bitrepository.bitrepositoryelements.FileIDsData; @@ -49,6 +41,14 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.io.File; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import static org.mockito.Mockito.mock; + /** * Performs the validation of the integrity for the checksums. */ diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java index aa05f187e..682846310 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/PutFileStepTest.java @@ -21,25 +21,24 @@ */ package org.bitrepository.integrityservice.workflow.step; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -import java.net.URL; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.client.eventhandler.CompleteEvent; import org.bitrepository.client.eventhandler.EventHandler; import org.bitrepository.client.eventhandler.OperationFailedEvent; import org.bitrepository.integrityservice.workflow.IntegrityWorkflowContext; -import org.bitrepository.service.exception.WorkflowAbortedException; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import java.net.URL; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + @SuppressWarnings("rawtypes") public class PutFileStepTest extends WorkflowstepTest { public static final String TEST_PILLAR_1 = "test-pillar-1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java index 3d7f8bc5f..8e4207f23 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateChecksumsStepTest.java @@ -21,22 +21,6 @@ */ package org.bitrepository.integrityservice.workflow.step; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.List; - import org.bitrepository.access.ContributorQuery; import org.bitrepository.access.getchecksums.conversation.ChecksumsCompletePillarEvent; import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; @@ -54,12 +38,26 @@ import org.bitrepository.common.utils.SettingsUtils; import org.bitrepository.integrityservice.cache.IntegrityModel; import org.bitrepository.service.exception.WorkflowAbortedException; -import org.mockito.ArgumentMatchers; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.Assert; import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + @SuppressWarnings("rawtypes") public class UpdateChecksumsStepTest extends WorkflowstepTest { public static final String TEST_PILLAR_1 = "test-pillar-1"; diff --git a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java index 142c0b92e..bc019e992 100644 --- a/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java +++ b/bitrepository-integrity-service/src/test/java/org/bitrepository/integrityservice/workflow/step/UpdateFileIDsStepTest.java @@ -21,20 +21,6 @@ */ package org.bitrepository.integrityservice.workflow.step; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; - import org.bitrepository.access.ContributorQuery; import org.bitrepository.access.getfileids.conversation.FileIDsCompletePillarEvent; import org.bitrepository.bitrepositoryelements.FileIDsData; @@ -49,12 +35,24 @@ import org.bitrepository.client.eventhandler.OperationFailedEvent; import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.service.exception.WorkflowAbortedException; -import org.mockito.ArgumentMatchers; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.testng.Assert; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashSet; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + @SuppressWarnings("rawtypes") public class UpdateFileIDsStepTest extends WorkflowstepTest { public static final String TEST_PILLAR_1 = "test-pillar-1"; diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringService.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringService.java index 10f5cc2f6..626b3583b 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringService.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringService.java @@ -5,25 +5,22 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice; -import java.util.Map; -import javax.jms.JMSException; - import org.bitrepository.access.AccessComponentFactory; import org.bitrepository.access.getstatus.GetStatusClient; import org.bitrepository.common.settings.Settings; @@ -42,68 +39,56 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * The monitoring service. - */ +import javax.jms.JMSException; +import java.util.Map; + public class MonitoringService implements LifeCycledService { private final Logger log = LoggerFactory.getLogger(getClass()); - /** The settings. */ private final Settings settings; - /** The store of collected statuses */ private final StatusStore statusStore; - /** The client for getting statuses. */ - private final GetStatusClient getStatusClient; - /** The alerter for sending alarms */ - private final MonitorAlerter alerter; - /** The status collector */ private final StatusCollector collector; - - /** - * Constructor. - * @param settings The settings. - * @param securityManager The security manager. - */ + public MonitoringService(Settings settings, SecurityManager securityManager) { this.settings = settings; SettingsUtils.initialize(settings); MessageBus messageBus = MessageBusManager.getMessageBus(settings, securityManager); statusStore = new ComponentStatusStore(SettingsUtils.getStatusContributorsForCollection()); - alerter = new BasicMonitoringServiceAlerter(settings, messageBus, AlarmLevel.ERROR, statusStore); - getStatusClient = AccessComponentFactory.getInstance().createGetStatusClient(settings, securityManager, + MonitorAlerter alerter = new BasicMonitoringServiceAlerter(settings, messageBus, AlarmLevel.ERROR, statusStore); + GetStatusClient getStatusClient = AccessComponentFactory.getInstance().createGetStatusClient(settings, securityManager, settings.getReferenceSettings().getMonitoringServiceSettings().getID()); collector = new StatusCollector(getStatusClient, settings, statusStore, alerter); collector.start(); } - + /** * @return The map of the status for the components. */ public Map getStatus() { return statusStore.getStatusMap(); } - + @Override public void start() {} - + /** * @return The maximum number of attempts to retrieve a status from a component before dispatching an alarm. */ public int getMaxRetries() { return settings.getReferenceSettings().getMonitoringServiceSettings().getMaxRetries().intValue(); - } - + } + /** * @return The interval between collecting status from the components. */ public long getCollectionInterval() { return settings.getReferenceSettings().getMonitoringServiceSettings().getCollectionInterval(); } - + @Override public void shutdown() { collector.stop(); MessageBus messageBus = MessageBusManager.getMessageBus(); - if ( messageBus != null) { + if (messageBus != null) { try { messageBus.close(); } catch (JMSException e) { diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringServiceFactory.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringServiceFactory.java index 10d4548b7..50030f19e 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringServiceFactory.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/MonitoringServiceFactory.java @@ -5,30 +5,22 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice; -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Paths; -import java.util.Properties; - import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.XMLFileSettingsLoader; import org.bitrepository.protocol.security.BasicSecurityManager; @@ -37,47 +29,50 @@ import org.bitrepository.service.ServiceSettingsProvider; import org.bitrepository.settings.referencesettings.ServiceType; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.Properties; + /** * The factory for the monitoring service. */ public class MonitoringServiceFactory { - /** The configuration directory containing the settings, et.al.*/ private static String confDir; - /** The private key file containing the security information.*/ private static String privateKeyFile; - /** The properties file holding implementation specifics for the alarm service. */ - private static final String CONFIGFILE = "monitoring.properties"; - /** Property key to tell where to locate the path and filename to the private key file. */ + private static final String CONFIG_FILE = "monitoring.properties"; + /** + * Property key to tell where to locate the path and filename to the private key file. + */ private static final String PRIVATE_KEY_FILE = "org.bitrepository.monitoring-service.privateKeyFile"; - /** The settings. */ private static Settings settings; - /** The security manager.*/ private static SecurityManager securityManager; - /** The implementation of the integrity service.*/ private static MonitoringService monitoringService; + private MonitoringServiceFactory() {} + /** - * Private constructor, use static getINSTANCE method to get instance. - */ - private MonitoringServiceFactory() { } - - /** - * Set the configuration directory. + * Set the configuration directory. * Should only be run at initialization time. - * @param configurationDir FIXME + * + * @param configurationDir The path to the configurations as {@link String} representation. */ public synchronized static void init(String configurationDir) { confDir = configurationDir; } - + /** * Retrieves the settings from the defined location. + * * @return The settings. * @see Settings */ public synchronized static Settings getSettings() { - if(settings == null) { - if(confDir == null) { + if (settings == null) { + if (confDir == null) { throw new IllegalStateException("No configuration directory has been set!"); } loadProperties(); @@ -89,49 +84,50 @@ public synchronized static Settings getSettings() { return settings; } - + /** * Instantiated the security manager for the integrity service. + * * @return The security manager. * @see #getSettings() * @see BasicSecurityManager */ public synchronized static SecurityManager getSecurityManager() { - if(securityManager == null) { + if (securityManager == null) { getSettings(); securityManager = SecurityManagerUtil.getSecurityManager(settings, Paths.get(privateKeyFile), settings.getReferenceSettings().getMonitoringServiceSettings().getID()); } - + return securityManager; } - + /** - * Factory method to get a singleton instance of the SimpleIntegrityService. + * Factory method to get a singleton instance of the SimpleIntegrityService. * Uses the settings and the security manager. + * * @return The SimpleIntegrityService * @see #getSecurityManager() * @see #getSettings() * @see MonitoringService */ public synchronized static MonitoringService getMonitoringService() { - if(monitoringService == null) { + if (monitoringService == null) { getSettings(); getSecurityManager(); monitoringService = new MonitoringService(settings, securityManager); } - + return monitoringService; } - - + /** - * Loads the properties. + * Loads the properties from the configuration directory, that is set using the {@link #init(String)} method. */ private static void loadProperties() { try { Properties properties = new Properties(); - String propertiesFile = confDir + "/" + CONFIGFILE; + String propertiesFile = confDir + "/" + CONFIG_FILE; BufferedReader propertiesReader = new BufferedReader( new InputStreamReader(new FileInputStream(propertiesFile), StandardCharsets.UTF_8)); properties.load(propertiesReader); diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java index 9a184e5a5..68979bc4a 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/BasicMonitoringServiceAlerter.java @@ -5,26 +5,22 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice.alarm; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; import org.bitrepository.bitrepositoryelements.Alarm; import org.bitrepository.bitrepositoryelements.AlarmCode; import org.bitrepository.common.settings.Settings; @@ -34,45 +30,47 @@ import org.bitrepository.service.AlarmDispatcher; import org.bitrepository.settings.referencesettings.AlarmLevel; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * Class for the monitoring service keep a watch on non responding components, and send alarms if needed. */ public class BasicMonitoringServiceAlerter extends AlarmDispatcher implements MonitorAlerter { - /** The store for the status results from the components.*/ private final StatusStore statusStore; - /** The maximum number of missing replies before an alarm is dispatched.*/ private final BigInteger maxRetries; /** - * @param settings FIXME - * @param statusStore The store for the status results from the components. + * @param settings The settings. * @param sender Used for sending the alarms. * @param alarmLevel Only send alarms at this alarms level or higher. - * @param statusStore Used to maintain the status of the components. + * @param statusStore The store for the status results from the components. */ public BasicMonitoringServiceAlerter( - Settings settings, MessageSender sender, AlarmLevel alarmLevel, StatusStore statusStore) { + Settings settings, MessageSender sender, AlarmLevel alarmLevel, StatusStore statusStore) { super(settings, sender, alarmLevel); this.statusStore = statusStore; maxRetries = settings.getReferenceSettings().getMonitoringServiceSettings().getMaxRetries(); } - + @Override public void checkStatuses() { Map statusMap = statusStore.getStatusMap(); List nonRespondingComponents = new ArrayList<>(); - for(String ID : statusMap.keySet()) { + for (String ID : statusMap.keySet()) { ComponentStatus componentStatus = statusMap.get(ID); - if(componentStatus.getNumberOfMissingReplies() >= maxRetries.intValue()) { + if (componentStatus.getNumberOfMissingReplies() >= maxRetries.intValue()) { componentStatus.markAsUnresponsive(); - if(!componentStatus.hasAlarmed()) { - nonRespondingComponents.add(ID); - componentStatus.alarmed(); + if (!componentStatus.hasAlarmed()) { + nonRespondingComponents.add(ID); + componentStatus.alarmed(); } } } - - if(!nonRespondingComponents.isEmpty()) { + + if (!nonRespondingComponents.isEmpty()) { Alarm alarm = new Alarm(); alarm.setAlarmCode(AlarmCode.COMPONENT_FAILURE); alarm.setAlarmText("The following components have become " + diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/MonitorAlerter.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/MonitorAlerter.java index 9bc82ca7b..d2d2a1bfe 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/MonitorAlerter.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/alarm/MonitorAlerter.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -25,10 +25,10 @@ * Interface for the monitor alerter. */ public interface MonitorAlerter { - + /** * Check for components that have not responded withing the given constraints, and send alarm - * message if there is any. + * message if there is any. */ void checkStatuses(); } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/GetStatusEventHandler.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/GetStatusEventHandler.java index 6454246c4..44f1f9b72 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/GetStatusEventHandler.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/GetStatusEventHandler.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,43 +30,37 @@ import org.slf4j.LoggerFactory; /** - * The eventhandler for handling the events by the GetStatusClient. + * The EventHandler for handling the events by the GetStatusClient. */ public class GetStatusEventHandler implements EventHandler { - /** The log.*/ private final Logger log = LoggerFactory.getLogger(GetStatusEventHandler.class); - /** The store for the status results. */ private final StatusStore statusStore; - /** The alarm dispatcher*/ private final MonitorAlerter alerter; /** - * Constructor. - * @param statusStore The store for the status results. + * @param statusStore The store for the status results. * @param alarmDispatcher The alarm dispatcher. */ public GetStatusEventHandler(StatusStore statusStore, MonitorAlerter alarmDispatcher) { this.statusStore = statusStore; this.alerter = alarmDispatcher; } - + @Override public void handleEvent(OperationEvent event) { log.debug("Got event: " + event); - - switch(event.getEventType()) { + + switch (event.getEventType()) { case COMPONENT_COMPLETE: - StatusCompleteContributorEvent statusEvent = (StatusCompleteContributorEvent) event; + StatusCompleteContributorEvent statusEvent = (StatusCompleteContributorEvent) event; statusStore.updateStatus(statusEvent.getContributorID(), statusEvent.getStatus()); break; case COMPLETE: - alerter.checkStatuses(); - break; case FAILED: alerter.checkStatuses(); break; default: break; - } + } } } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/StatusCollector.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/StatusCollector.java index 8d9da227d..3b5923e5b 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/StatusCollector.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/collector/StatusCollector.java @@ -5,78 +5,73 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice.collector; -import java.util.Timer; -import java.util.TimerTask; - import org.bitrepository.access.getstatus.GetStatusClient; import org.bitrepository.client.eventhandler.EventHandler; import org.bitrepository.common.settings.Settings; import org.bitrepository.monitoringservice.alarm.MonitorAlerter; import org.bitrepository.monitoringservice.status.StatusStore; +import java.util.Timer; +import java.util.TimerTask; + /** * The collector of status messages. */ public class StatusCollector { - /** The getStatusClient */ - private GetStatusClient getStatusClient; - /** The store for the status results.*/ + private final GetStatusClient getStatusClient; private final StatusStore statusStore; - /** The EventHandler */ - private EventHandler eventHandler; - /** Defines that the timer is a daemon thread. */ + private final EventHandler eventHandler; private static final Boolean TIMER_IS_DAEMON = true; - /** The name of the timer.*/ private static final String NAME_OF_TIMER = "GetStatus collection timer"; - /** Timer for collecting statuses on a regular basis */ private static final Timer timer = new Timer(NAME_OF_TIMER, TIMER_IS_DAEMON); - /** Time between getStatus collections */ private final long collectionInterval; - + /** - * Constructor. * @param getStatusClient The status client. - * @param settings The settings. - * @param statusStore The storage for the status results. - * @param alerter The alerter. + * @param settings The settings. + * @param statusStore The storage for the status results. + * @param alerter The alerter. */ - public StatusCollector(GetStatusClient getStatusClient, Settings settings, StatusStore statusStore, - MonitorAlerter alerter) { + public StatusCollector(GetStatusClient getStatusClient, Settings settings, StatusStore statusStore, MonitorAlerter alerter) { this.getStatusClient = getStatusClient; eventHandler = new GetStatusEventHandler(statusStore, alerter); this.statusStore = statusStore; collectionInterval = settings.getReferenceSettings().getMonitoringServiceSettings().getCollectionInterval(); } - - /** Start the collection of statuses */ + + /** + * Start the collection of statuses + */ public void start() { timer.schedule(new StatusCollectorTimerTask(), 0, collectionInterval); } - - /** Stop the collection of statuses */ + + /** + * Stop the collection of statuses + */ public void stop() { timer.cancel(); } - + /** - * The timertask for collecting the status. - * Tells the store that a new status request has been issued, and then starts the conversation for retrieving the + * The timer task for collecting the status. + * Tells the store that a new status request has been issued, and then starts the conversation for retrieving the * status from all the contributors. */ private class StatusCollectorTimerTask extends TimerTask { diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatus.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatus.java index 6e7ca70a5..a282c2f2c 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatus.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatus.java @@ -5,45 +5,33 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice.status; -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.ResultingStatus; -/** - * Class to encapsulate the status of a component. - */ +import javax.xml.datatype.XMLGregorianCalendar; + public class ComponentStatus { - /** The number of missing replies.*/ private int numberOfMissingReplies; - /** The current status code.*/ private ComponentStatusCode status; - /** The date for the latest reply.*/ private XMLGregorianCalendar lastReply; - /** The status information of the latest reply.*/ private String info; - /** Indication whether an alarm has been sent due to the components status */ private Boolean alarmed; - - - /** - * Constructor - */ + public ComponentStatus() { numberOfMissingReplies = 0; status = ComponentStatusCode.UNKNOWN; @@ -51,10 +39,11 @@ public ComponentStatus() { info = "No status received yet."; alarmed = false; } - + /** * Update the status of a component with the given results. - * @param resultingStatus FIXME + * + * @param resultingStatus The status will be updated to the string value of the status code. */ public void updateStatus(ResultingStatus resultingStatus) { numberOfMissingReplies = 0; @@ -65,28 +54,28 @@ public void updateStatus(ResultingStatus resultingStatus) { } /** - * Add another missing reply. + * Updates the number of missing replies by exactly one. */ - public void updateReplys() { + public void updateReplies() { numberOfMissingReplies++; } - + /** * Marks the component as unresponsive. */ public void markAsUnresponsive() { status = ComponentStatusCode.UNRESPONSIVE; } - + /** - * @return The number of missing replies in a row. + * @return The number of missing replies. */ public int getNumberOfMissingReplies() { return numberOfMissingReplies; } /** - * @return The code for the latest reply. + * @return The status code for the latest reply. */ public ComponentStatusCode getStatus() { return status; @@ -95,22 +84,25 @@ public ComponentStatusCode getStatus() { /** * @return The date for the latest reply. */ - public XMLGregorianCalendar getLastReply() { + public XMLGregorianCalendar getLastReplyDate() { return lastReply; } /** - * @return The latest status message. + * @return The information message from the latest reply. */ public String getInfo() { return info; - } - + } + + /** + * @return Returns a {@link Boolean} indicating whether the component has invoked an alarm. + */ public Boolean hasAlarmed() { - return alarmed; + return alarmed; } - + public void alarmed() { - alarmed = true; + alarmed = true; } } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusCode.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusCode.java index d2ffd1c29..0090306da 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusCode.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusCode.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,20 +22,15 @@ package org.bitrepository.monitoringservice.status; /** - * Enumeration of possible status states for a component. + * Enumeration of possible status states for a component. */ public enum ComponentStatusCode { - /** If no status is known for the given component.*/ UNKNOWN, - /** If the component is fine.*/ OK, - /** If the component has reported a warning.*/ WARNING, - /** If the component has reported an error.*/ ERROR, - /** If the component has become unresponsive.*/ UNRESPONSIVE; - + /** * @return The value of the status. */ diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java index 0d331ee31..327d4f153 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/ComponentStatusStore.java @@ -21,15 +21,15 @@ */ package org.bitrepository.monitoringservice.status; +import org.bitrepository.bitrepositoryelements.ResultingStatus; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.bitrepository.bitrepositoryelements.ResultingStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Storage for the status of the different components. */ @@ -62,7 +62,7 @@ public synchronized void updateStatus(String componentID, ResultingStatus status @Override public synchronized void updateReplyCounts() { for(String ID : statusMap.keySet()) { - statusMap.get(ID).updateReplys(); + statusMap.get(ID).updateReplies(); } } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/StatusStore.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/StatusStore.java index 98f5a7d5b..9087fe96d 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/StatusStore.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/status/StatusStore.java @@ -5,44 +5,45 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice.status; -import java.util.Map; - import org.bitrepository.bitrepositoryelements.ResultingStatus; +import java.util.Map; + /** * Interface for the storage of statuses. */ public interface StatusStore { /** * Updates the status of a given component. + * * @param componentID The id of the component to update. - * @param status The resulting status for the given component. + * @param status The resulting status for the given component. */ void updateStatus(String componentID, ResultingStatus status); - + /** * Tells the store that new statuses have been requested from the components. * This should increase the 'missingReplies' for each component, and whenever the component delivers its * reply, then the 'missingReplies' are set to zero again. */ void updateReplyCounts(); - + /** * @return The mapping between components and their status. */ diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/MonitoringServiceContextListener.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/MonitoringServiceContextListener.java index a01a298f5..13121d159 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/MonitoringServiceContextListener.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/MonitoringServiceContextListener.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Audit Trail Service - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -45,7 +45,7 @@ public LifeCycledService getService() { } @Override - public void initialize(String configutrationDir) { - MonitoringServiceFactory.init(configutrationDir); + public void initialize(String configurationDir) { + MonitoringServiceFactory.init(configurationDir); } } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/RestMonitoringService.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/RestMonitoringService.java index c1732759e..9c8b89550 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/RestMonitoringService.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/RestMonitoringService.java @@ -5,66 +5,65 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.monitoringservice.webservice; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; import org.bitrepository.common.utils.TimeUtils; import org.bitrepository.monitoringservice.MonitoringService; import org.bitrepository.monitoringservice.MonitoringServiceFactory; import org.bitrepository.monitoringservice.status.ComponentStatus; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + @Path("/MonitoringService") public class RestMonitoringService { - - private MonitoringService service; - + private final MonitoringService service; + public RestMonitoringService() { service = MonitoringServiceFactory.getMonitoringService(); } - + @GET @Path("/getMonitoringConfiguration/") @Produces("application/json") public List getMonitoringServiceConfiguration() { List options = new ArrayList<>(); - + options.add(new WebConfOption("Check interval", TimeUtils.millisecondsToHuman(service.getCollectionInterval()))); options.add(new WebConfOption("Max retries", Long.toString(service.getMaxRetries()))); - + return options; } - + @GET @Path("/getComponentStatus/") @Produces("application/json") public List getComponentStatus() { Map statusMap = service.getStatus(); List statuses = new ArrayList<>(); - - for(String component : statusMap.keySet()) { + + for (String component : statusMap.keySet()) { statuses.add(new WebStatus(component, statusMap.get(component))); } return statuses; } - + } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebConfOption.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebConfOption.java index 005e18486..cd66bb711 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebConfOption.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebConfOption.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -29,32 +29,31 @@ public class WebConfOption { private String confOption; private String confValue; - + public WebConfOption() {} - + public WebConfOption(String option, String value) { this.confOption = option; this.confValue = value; } - + @XmlElement(name = "confOption") public String getConfOption() { return confOption; } - + public void setConfOption(String confOption) { this.confOption = confOption; } - + @XmlElement(name = "confValue") public String getConfValue() { return confValue; } - + public void setConfValue(String confValue) { this.confValue = confValue; } - - - + + } diff --git a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebStatus.java b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebStatus.java index 57db6a025..75d6211ff 100644 --- a/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebStatus.java +++ b/bitrepository-monitoring-service/src/main/java/org/bitrepository/monitoringservice/webservice/WebStatus.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -21,70 +21,69 @@ */ package org.bitrepository.monitoringservice.webservice; +import org.bitrepository.common.utils.TimeUtils; +import org.bitrepository.monitoringservice.status.ComponentStatus; + import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.datatype.XMLGregorianCalendar; -import org.bitrepository.common.utils.TimeUtils; -import org.bitrepository.monitoringservice.status.ComponentStatus; - @XmlRootElement public class WebStatus { - private String componentID; private String status; private String info; private String timeStamp; - + public WebStatus() {} - + public WebStatus(String componentID, ComponentStatus status) { this.componentID = componentID; this.status = status.getStatus().toString(); this.info = status.getInfo(); - XMLGregorianCalendar cal = status.getLastReply(); - if(cal != null) { + XMLGregorianCalendar cal = status.getLastReplyDate(); + if (cal != null) { timeStamp = TimeUtils.shortDate(cal); } else { - timeStamp = "N/A"; + timeStamp = "N/A"; } } - + @XmlElement(name = "componentID") public String getComponentID() { return componentID; } - + public void setComponentID(String componentID) { this.componentID = componentID; } - + @XmlElement(name = "status") public String getStatus() { return status; } - + public void setStatus(String status) { this.status = status; } - + @XmlElement(name = "info") public String getInfo() { return info; } - + public void setInfo(String info) { this.info = info; } - + @XmlElement(name = "timeStamp") public String getTimeStamp() { return timeStamp; } - + public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } - - + + } diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockStatusStore.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockStatusStore.java index 0ddc9556c..37b20a23d 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockStatusStore.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/MockStatusStore.java @@ -21,13 +21,13 @@ */ package org.bitrepository.monitoringservice; -import java.util.HashMap; -import java.util.Map; - import org.bitrepository.bitrepositoryelements.ResultingStatus; import org.bitrepository.monitoringservice.status.ComponentStatus; import org.bitrepository.monitoringservice.status.StatusStore; +import java.util.HashMap; +import java.util.Map; + public class MockStatusStore implements StatusStore { private int callsForUpdateStatus = 0; diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java index f860b55fc..360a3d294 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/alarm/MonitorAlerterTest.java @@ -21,9 +21,6 @@ */ package org.bitrepository.monitoringservice.alarm; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; import org.bitrepository.bitrepositoryelements.ResultingStatus; import org.bitrepository.bitrepositoryelements.StatusCode; import org.bitrepository.bitrepositoryelements.StatusInfo; @@ -37,6 +34,10 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.util.HashMap; +import java.util.Map; + public class MonitorAlerterTest extends IntegrationTest { @Test(groups = {"regressiontest"}) @@ -69,7 +70,7 @@ public void testMonitorAlerter() throws Exception { addStep("Check the status when a negative entry exists.", "Should send an alarm and make another call for the GetStatusMap"); - cs.updateReplys(); + cs.updateReplies(); store.statuses.put(componentID, cs); alerter.checkStatuses(); Assert.assertEquals(store.getCallsForGetStatusMap(), 3); diff --git a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java index 97ee3d8b4..c93d24701 100644 --- a/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java +++ b/bitrepository-monitoring-service/src/test/java/org/bitrepository/monitoringservice/status/ComponentStatusStoreTest.java @@ -21,10 +21,6 @@ */ package org.bitrepository.monitoringservice.status; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - import org.bitrepository.bitrepositoryelements.ResultingStatus; import org.bitrepository.bitrepositoryelements.StatusCode; import org.bitrepository.bitrepositoryelements.StatusInfo; @@ -36,6 +32,10 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + public class ComponentStatusStoreTest extends ExtendedTestCase { Settings settings; @@ -61,7 +61,7 @@ public void testComponentStatus() throws Exception { Assert.assertNotNull(statuses.get(componentId)); Assert.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), newStatus.getNumberOfMissingReplies()); - Assert.assertEquals(statuses.get(componentId).getLastReply(), newStatus.getLastReply()); + Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); Assert.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); addStep("Update the replay counts and validate ", "it should increases the 'number of missing replies' by 1"); @@ -71,7 +71,7 @@ public void testComponentStatus() throws Exception { Assert.assertNotNull(statuses.get(componentId)); Assert.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), 1); - Assert.assertEquals(statuses.get(componentId).getLastReply(), newStatus.getLastReply()); + Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); Assert.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); addStep("Test what happens when an invalid component id attempted to be updated.", "Should not affect content."); @@ -81,7 +81,7 @@ public void testComponentStatus() throws Exception { Assert.assertNotNull(statuses.get(componentId)); Assert.assertEquals(statuses.get(componentId).getInfo(), newStatus.getInfo()); Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), 1); - Assert.assertEquals(statuses.get(componentId).getLastReply(), newStatus.getLastReply()); + Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), newStatus.getLastReplyDate()); Assert.assertEquals(statuses.get(componentId).getStatus(), newStatus.getStatus()); addStep("Try giving it a positive status", "Should be inserted into the store."); @@ -92,7 +92,7 @@ public void testComponentStatus() throws Exception { Assert.assertNotNull(statuses.get(componentId)); Assert.assertEquals(statuses.get(componentId).getInfo(), resStatus.getStatusInfo().getStatusText()); Assert.assertEquals(statuses.get(componentId).getNumberOfMissingReplies(), 0); - Assert.assertEquals(statuses.get(componentId).getLastReply(), resStatus.getStatusTimestamp()); + Assert.assertEquals(statuses.get(componentId).getLastReplyDate(), resStatus.getStatusTimestamp()); Assert.assertEquals(statuses.get(componentId).getStatus().value(), resStatus.getStatusInfo().getStatusCode().name()); } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/Pillar.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/Pillar.java index 7ee32725a..3602346a0 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/Pillar.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/Pillar.java @@ -5,24 +5,22 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar; -import javax.jms.JMSException; - import org.bitrepository.common.ArgumentValidator; import org.bitrepository.common.settings.Settings; import org.bitrepository.common.utils.SettingsUtils; @@ -32,41 +30,34 @@ import org.bitrepository.pillar.store.StorageModel; import org.bitrepository.protocol.messagebus.MessageBus; import org.bitrepository.service.scheduler.JobScheduler; -import org.bitrepository.service.scheduler.TimerbasedScheduler; +import org.bitrepository.service.scheduler.TimerBasedScheduler; import org.bitrepository.service.workflow.SchedulableJob; import org.bitrepository.settings.referencesettings.PillarType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.jms.JMSException; + /** * Class for the Reference Pillar. * This will either be a File Reference Pillar or a Checksum Reference Pillar, depending on the type of * storage model. */ public class Pillar { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The messagebus for the pillar.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private final MessageBus messageBus; - /** The settings.*/ private final Settings settings; - /** The storage model for all the file data.*/ private final StorageModel pillarModel; - - /** The type of pillar.*/ - private final PillarType pillarType; private final PillarMediator mediator; - - /** The scheduler for the recalculation workflows.*/ private final JobScheduler scheduler; - /** The default time for running the recalculation workflow, when the settings is not set. - * The default is every hour. */ + /** + * The default time for running the recalculation workflow, when the settings are not set. + * The default is every hour. + */ private static final Long DEFAULT_RECALCULATION_WORKFLOW_TIME = 3600000L; /** - * Constructor. - * - * @param messageBus The messagebus for the communication. + * @param messageBus The message-bus for the communication. * @param settings The settings for the pillar. * @param pillarModel The storage model for the pillar. * @param context The context for the message handler. @@ -78,35 +69,36 @@ public Pillar(MessageBus messageBus, Settings settings, StorageModel pillarModel SettingsUtils.initialize(settings); this.settings = settings; this.pillarModel = pillarModel; - this.pillarType = settings.getReferenceSettings().getPillarSettings().getPillarType(); + + PillarType pillarType = settings.getReferenceSettings().getPillarSettings().getPillarType(); log.info("Starting the ReferencePillar of type '" + pillarType + "'."); messageBus.setCollectionFilter(context.getPillarCollections()); mediator = new PillarMediator(messageBus, context, pillarModel); mediator.start(); - - this.scheduler = new TimerbasedScheduler(); - if(pillarType == PillarType.FILE) { + + this.scheduler = new TimerBasedScheduler(); + if (pillarType == PillarType.FILE) { initializeWorkflows(); } } - + /** * Initializes one RecalculateChecksums workflow for each collection. */ private void initializeWorkflows() { Long interval = DEFAULT_RECALCULATION_WORKFLOW_TIME; - if(settings.getReferenceSettings().getPillarSettings().getRecalculateOldChecksumsInterval() != null) { + if (settings.getReferenceSettings().getPillarSettings().getRecalculateOldChecksumsInterval() != null) { interval = settings.getReferenceSettings().getPillarSettings() .getRecalculateOldChecksumsInterval().longValue(); } - for(String collectionID : SettingsUtils.getCollectionIDsForPillar( + for (String collectionID : SettingsUtils.getCollectionIDsForPillar( settings.getReferenceSettings().getPillarSettings().getPillarID())) { SchedulableJob workflow = new RecalculateChecksumJob(collectionID, pillarModel); scheduler.schedule(workflow, interval); } } - + /** * Closes the ReferencePillar. */ @@ -117,7 +109,7 @@ public void close() { pillarModel.close(); log.info("ReferencePillar stopped!"); } catch (JMSException e) { - log.warn("Could not close the messagebus.", e); + log.warn("Could not close the message-bus.", e); } } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarComponentFactory.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarComponentFactory.java index 50a8f5e7b..8f55963bc 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarComponentFactory.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarComponentFactory.java @@ -1,31 +1,29 @@ /* * #%L * Bitrepository Integration - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar; -import java.lang.reflect.Constructor; - import org.bitrepository.common.filestore.FileStore; import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.XMLFileSettingsLoader; @@ -58,21 +56,20 @@ import org.bitrepository.service.database.DatabaseManager; import org.bitrepository.settings.referencesettings.PillarType; +import java.lang.reflect.Constructor; + /** * Component factory for this module. */ public final class PillarComponentFactory { - /** The singleton instance. */ private static PillarComponentFactory instance; /** - * Instantiation of this singleton. - * * @return The singleton instance of this factory class. */ public static synchronized PillarComponentFactory getInstance() { // ensure singleton. - if(instance == null) { + if (instance == null) { instance = new PillarComponentFactory(); } return instance; @@ -86,9 +83,10 @@ private PillarComponentFactory() { /** * Creates the pillar from on settings, key-file and pillar-ID. + * * @param pathToSettings The path to the settings file. - * @param pathToKeyFile The path to the key file (can be empty). - * @param pillarID The id of the pillar (if null, the pillar-id in settings are used). + * @param pathToKeyFile The path to the key file (can be empty). + * @param pillarID The id of the pillar (if null, the pillar-id in settings are used). * @return The pillar. */ public Pillar createPillar(String pathToSettings, String pathToKeyFile, String pillarID) { @@ -96,19 +94,20 @@ public Pillar createPillar(String pathToSettings, String pathToKeyFile, String p SecurityManager securityManager = loadSecurityManager(pathToKeyFile, settings); MessageBus messageBus = ProtocolComponentFactory.getInstance().getMessageBus(settings, securityManager); - + return createPillar(settings, messageBus); } - + /** * Creates a pillar from settings and message-bus. - * @param settings The instantiated settings. - * @param messageBus The messagebus. + * + * @param settings The instantiated settings. + * @param messageBus The message-bus. * @return The pillar. */ public Pillar createPillar(Settings settings, MessageBus messageBus) { ChecksumStore cache = getChecksumStore(settings); - AuditTrailManager audits = getAuditTrailManager(settings); + AuditTrailManager audits = getAuditTrailManager(settings); PillarAlarmDispatcher alarmDispatcher = new PillarAlarmDispatcher(settings, messageBus); ResponseDispatcher responseDispatcher = new ResponseDispatcher(settings, messageBus); @@ -121,12 +120,13 @@ public Pillar createPillar(Settings settings, MessageBus messageBus) { alarmDispatcher, audits, ProtocolComponentFactory.getInstance().getFileExchange(settings)); - - return new Pillar(messageBus, settings, pillarModel, context); + + return new Pillar(messageBus, settings, pillarModel, context); } - + /** * Instantiates the ChecksumStore. + * * @param settings The settings. * @return The ChecksumStore. */ @@ -134,9 +134,10 @@ private ChecksumStore getChecksumStore(Settings settings) { DatabaseManager checksumDatabaseManager = new ChecksumDatabaseManager(settings); return new ChecksumDAO(checksumDatabaseManager); } - + /** * Instantiates the AuditTrailManager. + * * @param settings The settings. * @return The AuditTrailManager. */ @@ -147,18 +148,19 @@ private AuditTrailManager getAuditTrailManager(Settings settings) { settings.getComponentID()); } - + /** * Retrieves the FileStore defined in the settings. + * * @param settings The settings. - * @return The filestore from settings, or the CollectionArchiveManager, if the setting is missing. + * @return The file-store from settings, or the CollectionArchiveManager, if the setting is missing. */ @SuppressWarnings("unchecked") private FileStore getFileStore(Settings settings) { - if(settings.getReferenceSettings().getPillarSettings().getFileStoreClass() == null) { + if (settings.getReferenceSettings().getPillarSettings().getFileStoreClass() == null) { return new CollectionArchiveManager(settings); } - + try { Class fsClass = (Class) Class.forName( settings.getReferenceSettings().getPillarSettings().getFileStoreClass()); @@ -168,20 +170,21 @@ private FileStore getFileStore(Settings settings) { throw new CoordinationLayerException("Could not instantiate the FileStore", e); } } - + /** * Instantiates the PillarModel. - * @param settings The settings. - * @param cache The ChecksumCache. + * + * @param settings The settings. + * @param cache The ChecksumCache. * @param alarmDispatcher The alarm dispatcher. * @return The PillarModel, either for FullReferencePillar or ChecksumPillar. */ private StorageModel getPillarModel(Settings settings, ChecksumStore cache, AlarmDispatcher alarmDispatcher) { PillarType pillarType = settings.getReferenceSettings().getPillarSettings().getPillarType(); - if(pillarType == PillarType.CHECKSUM) { + if (pillarType == PillarType.CHECKSUM) { return new ChecksumStorageModel(cache, alarmDispatcher, settings, ProtocolComponentFactory.getInstance().getFileExchange(settings)); - } else if(pillarType == PillarType.FILE) { + } else if (pillarType == PillarType.FILE) { FileStore archive = getFileStore(settings); return new FileStorageModel(archive, cache, alarmDispatcher, settings, ProtocolComponentFactory.getInstance().getFileExchange(settings)); @@ -190,19 +193,24 @@ private StorageModel getPillarModel(Settings settings, ChecksumStore cache, Alar } } - /** The default path for the settings in the development.*/ + /** + * The default path for the settings in the development. + */ private static final String DEFAULT_PATH_TO_SETTINGS = "conf"; - /** The default path for the settings in the development.*/ + /** + * The default path for the settings in the development. + */ private static final String DEFAULT_PATH_TO_KEY_FILE = "conf/pillar.pem"; /** * Method for retrieving the settings for the launcher. + * * @param pathToSettings The path to the settings. If it is null or empty, then the default path is used. * @return The settings. */ private static Settings loadSettings(String pillarID, String pathToSettings) { String settingsPath; - if(pathToSettings == null || pathToSettings.isEmpty()) { + if (pathToSettings == null || pathToSettings.isEmpty()) { settingsPath = DEFAULT_PATH_TO_SETTINGS; } else { settingsPath = pathToSettings; @@ -216,13 +224,14 @@ private static Settings loadSettings(String pillarID, String pathToSettings) { /** * Instantiates the security manager based on the settings and the path to the key file. + * * @param pathToPrivateKeyFile The path to the key file. - * @param settings The settings. + * @param settings The settings. * @return The security manager. */ private static BasicSecurityManager loadSecurityManager(String pathToPrivateKeyFile, Settings settings) { String privateKeyFile; - if(pathToPrivateKeyFile == null || pathToPrivateKeyFile.isEmpty()) { + if (pathToPrivateKeyFile == null || pathToPrivateKeyFile.isEmpty()) { privateKeyFile = DEFAULT_PATH_TO_KEY_FILE; } else { privateKeyFile = pathToPrivateKeyFile; diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarLauncher.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarLauncher.java index 0706ca32a..281114317 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarLauncher.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarLauncher.java @@ -1,23 +1,24 @@ /* * #%L - * Bitmagasin integrationstest - * + * BitRepository IntegrationTests + * * $Id: ReferencePillarLauncher.java 685 2012-01-06 16:35:17Z jolf $ - * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/ReferencePillarLauncher.java $ + * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/main/java/org + * /bitrepository/pillar/ReferencePillarLauncher.java $ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,7 +28,7 @@ import org.bitrepository.common.settings.XMLFileSettingsLoader; /** - * Method for launching the ReferencePillar. + * Method for launching the ReferencePillar. * It just loads the configurations and uses them to create the PillarSettings needed for starting the ReferencePillar. */ public final class PillarLauncher { @@ -35,20 +36,20 @@ public final class PillarLauncher { /** * Private constructor. To prevent instantiation of this utility class. */ - private PillarLauncher() { } - + private PillarLauncher() {} + /** * @param args
    - *
  1. The path to the directory containing the settings. See {@link XMLFileSettingsLoader} for details.
  2. - *
  3. The path to the private key file with the certificates for communication.
  4. - *
  5. The pillar's componentID.
  6. - *
+ *
  • The path to the directory containing the settings. See {@link XMLFileSettingsLoader} for details.
  • + *
  • The path to the private key file with the certificates for communication.
  • + *
  • The pillar's componentID.
  • + * */ public static void main(String[] args) { String pathToSettings = args[0]; - String pathToKeyFile = args.length >=2 ? args[1] : null; - String pillarID = args.length == 3 ? args[2]: null; - + String pathToKeyFile = args.length >= 2 ? args[1] : null; + String pillarID = args.length == 3 ? args[2] : null; + Pillar pillar = PillarComponentFactory.getInstance().createPillar(pathToSettings, pathToKeyFile, pillarID); PillarRunner.launchPillar(pillar); } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarRunner.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarRunner.java index 40ea332ae..2f42dcd90 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarRunner.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarRunner.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -25,15 +25,18 @@ * Launches a given pillar. */ public final class PillarRunner { - /** Private constructor, to avoid instantiation of this utility class.*/ + private static final Object lock = new Object(); + private PillarRunner() {} + /** * Method for launching the pillar. + * * @param pillar The pillar to run. */ public static void launchPillar(Pillar pillar) { try { - synchronized(pillar) { + synchronized (lock) { pillar.wait(); } } catch (Exception e) { diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarSettingsProvider.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarSettingsProvider.java index 770124946..26df3dc5b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarSettingsProvider.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/PillarSettingsProvider.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -25,19 +25,16 @@ import org.bitrepository.common.settings.SettingsProvider; import org.bitrepository.settings.referencesettings.ReferenceSettings; -/** - * The settings provider for the pillar. - */ public class PillarSettingsProvider extends SettingsProvider { - private String pillarID; + private final String pillarID; /** - * Creates a SettingsProvider which will use the provided SettingsLoader for loading the + * Creates a {@link SettingsProvider} which will use the provided {@link SettingsLoader} for loading the * settings. * * @param settingsReader Use for loading the settings. - * @param pillarID Optional pillarID if more than one reference pillar in the collection. If null the - * pillarID from the first pillar settings section in the reference settings wil be used. + * @param pillarID Optional pillarID if more than one reference pillar in the collection. If null the + * pillarID from the first pillar settings section in the reference settings wil be used. */ public PillarSettingsProvider(SettingsLoader settingsReader, String pillarID) { super(settingsReader, null); @@ -45,7 +42,7 @@ public PillarSettingsProvider(SettingsLoader settingsReader, String pillarID) { } protected String getComponentID(ReferenceSettings referenceSettings) { - if(pillarID == null) { + if (pillarID == null) { return referenceSettings.getPillarSettings().getPillarID(); } else { return pillarID; diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/ChecksumDatabaseCreator.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/ChecksumDatabaseCreator.java index 97f7f077e..4650dbd82 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/ChecksumDatabaseCreator.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/ChecksumDatabaseCreator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,23 +27,24 @@ import org.bitrepository.settings.referencesettings.DatabaseSpecifics; /** - * Will create a checksum database. - * Defines the concrete DatabaseSpecifics and sql script location, - * all intelligence is located in the DatabaseCreator super class. + * Used to create a checksum database.
    + * Defines the concrete DatabaseSpecifics and SQL-script location. * - * @see DatabaseCreator + * @see DatabaseCreator DatabaseCreater */ public class ChecksumDatabaseCreator extends DatabaseCreator { - /** Default location for the script for creating the Checksum database.*/ + /** + * Default location for the script for creating the Checksum database. + */ public static final String DEFAULT_CHECKSUM_DB_SCRIPT = "sql/derby/checksumDBCreation.sql"; /** * @param args
      - *
    1. The path to the directory containing the settings. See - * {@link org.bitrepository.common.settings.XMLFileSettingsLoader} for details.
    2. - *
    3. The database creation script as found in the classpath. Will revert to DEFAULT_CHECKSUM_DB_SCRIPT = - * "sql/derby/checksumDBCreation.sql" if null.
    4. - *
    + *
  • The path to the directory containing the settings. See + * {@link org.bitrepository.common.settings.XMLFileSettingsLoader} for details.
  • + *
  • The database creation script as found in the classpath. Will revert to DEFAULT_CHECKSUM_DB_SCRIPT = + * "sql/derby/checksumDBCreation.sql" if null.
  • + * */ public static void main(String[] args) { ChecksumDatabaseCreator dbCreator = new ChecksumDatabaseCreator(); @@ -53,10 +54,8 @@ public static void main(String[] args) { } public void createChecksumDatabase(Settings settings, String pathToSqlCreationScript) { - DatabaseSpecifics databaseSpecifics = - settings.getReferenceSettings().getPillarSettings().getChecksumDatabase(); + DatabaseSpecifics databaseSpecifics = settings.getReferenceSettings().getPillarSettings().getChecksumDatabase(); - createDatabase(databaseSpecifics, pathToSqlCreationScript == null ? - DEFAULT_CHECKSUM_DB_SCRIPT : pathToSqlCreationScript); + createDatabase(databaseSpecifics, pathToSqlCreationScript == null ? DEFAULT_CHECKSUM_DB_SCRIPT : pathToSqlCreationScript); } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/MessageHandlerContext.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/MessageHandlerContext.java index c7221ca8c..56c1436f9 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/MessageHandlerContext.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/MessageHandlerContext.java @@ -5,24 +5,22 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.common; -import java.util.List; - import org.bitrepository.common.ArgumentValidator; import org.bitrepository.common.settings.Settings; import org.bitrepository.protocol.FileExchange; @@ -30,6 +28,8 @@ import org.bitrepository.service.contributor.ContributorContext; import org.bitrepository.service.contributor.ResponseDispatcher; +import java.util.List; + /** * Container for the context of the pillar, e.g. all the components needed for the message handling. */ @@ -42,8 +42,8 @@ public class MessageHandlerContext extends ContributorContext { * * @param settings The settings. * @param pillarCollections The collections which the pillar is part of. - * @param responseDispatcher The component for sending responses on the messagebus. - * @param alarmDispatcher The component for dispatching alarms on the messagebus. + * @param responseDispatcher The component for sending responses on the message-bus. + * @param alarmDispatcher The component for dispatching alarms on the message-bus. * @param auditTrailManager The audit trail storage / manager. * @param fileExchange The file exchange. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAlarmDispatcher.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAlarmDispatcher.java index 9ea3e1a18..a1c6f0b93 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAlarmDispatcher.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAlarmDispatcher.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Integration - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -34,22 +34,20 @@ import org.bitrepository.service.exception.IllegalOperationException; import org.bitrepository.service.exception.RequestHandlerException; -/** - * The class for dispatching alarms. - */ public class PillarAlarmDispatcher extends AlarmDispatcher { - + /** * @param settings The settings for this alarm dispatcher. - * @param sender The sender for this alarm dispatcher. + * @param sender The sender for this alarm dispatcher. */ public PillarAlarmDispatcher(Settings settings, MessageSender sender) { super(settings, sender, settings.getReferenceSettings().getPillarSettings().getAlarmLevel()); } - + /** * Method for sending an alarm based on an IllegalArgumentException. * Is only send if the alarm level is 'WARNING', otherwise the exception is just logged. + * * @param exception The exception to base the alarm upon. */ public void handleIllegalArgumentException(IllegalArgumentException exception) { @@ -58,13 +56,14 @@ public void handleIllegalArgumentException(IllegalArgumentException exception) { Alarm ad = new Alarm(); ad.setAlarmCode(AlarmCode.INCONSISTENT_REQUEST); ad.setAlarmText(exception.getMessage()); - + warning(ad); } /** * Sends an alarm for a RuntimeException. Such exceptions are sent unless the AlarmLevel is 'EMERGENCY', * otherwise the exception is just logged. + * * @param exception The exception causing the alarm. */ public void handleRuntimeExceptions(RuntimeException exception) { @@ -79,15 +78,16 @@ public void handleRuntimeExceptions(RuntimeException exception) { /** * Handles the case when the request causes a RequestHandlerException. - * @param e The exception causing this alarm case. + * + * @param e The exception causing this alarm case. * @param collectionID The ID of the collection, where the exception occurred. */ public void handleRequestException(RequestHandlerException e, String collectionID) { Alarm alarm = new Alarm(); - - if(e.getResponseInfo().getResponseCode() == ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE) { + + if (e.getResponseInfo().getResponseCode() == ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE) { alarm.setAlarmCode(AlarmCode.INVALID_MESSAGE); - } else if(e.getResponseInfo().getResponseCode() == ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE + } else if (e.getResponseInfo().getResponseCode() == ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE || e.getResponseInfo().getResponseCode() == ResponseCode.NEW_FILE_CHECKSUM_FAILURE) { alarm.setAlarmCode(AlarmCode.CHECKSUM_ALARM); } else { @@ -96,8 +96,8 @@ public void handleRequestException(RequestHandlerException e, String collectionI alarm.setAlarmText(e.getResponseInfo().getResponseText()); alarm.setCollectionID(collectionID); - - if(e instanceof IllegalOperationException) { + + if (e instanceof IllegalOperationException) { IllegalOperationException ioe = (IllegalOperationException) e; alarm.setFileID(ioe.getFileId()); error(alarm); diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAuditTrailDatabaseCreator.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAuditTrailDatabaseCreator.java index 7240a1f2b..a22250cb0 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAuditTrailDatabaseCreator.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/PillarAuditTrailDatabaseCreator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,16 +30,18 @@ * Class for creating the audit trail contributor database for the pillar. */ public class PillarAuditTrailDatabaseCreator extends DatabaseCreator { - /** Default location of the script for creating the audit trail contributor database.*/ + /** + * Default location of the script for creating the audit trail contributor database. + */ public static final String DEFAULT_AUDIT_TRAIL_DB_SCRIPT = "sql/derby/auditContributorDBCreation.sql"; /** * @param args
      - *
    1. The path to the directory containing the settings. See - * {@link org.bitrepository.common.settings.XMLFileSettingsLoader} for details.
    2. - *
    3. The database creation script as found in the classpath. Will revert to DEFAULT_CHECKSUM_DB_SCRIPT = - * "sql/derby/checksumDBCreation.sql" if null.
    4. - *
    + *
  • The path to the directory containing the settings. See + * {@link org.bitrepository.common.settings.XMLFileSettingsLoader} for details.
  • + *
  • The database creation script as found in the classpath. Will revert to DEFAULT_CHECKSUM_DB_SCRIPT = + * "sql/derby/checksumDBCreation.sql" if null.
  • + * */ public static void main(String[] args) { PillarAuditTrailDatabaseCreator dbCreatorPillar = new PillarAuditTrailDatabaseCreator(); @@ -50,14 +52,15 @@ public static void main(String[] args) { /** * Creates the audit trail contributor database for the pillar. - * @param settings The settings for the pillar. + * + * @param settings The settings for the pillar. * @param pathToSqlCreationScript The path to the script for creating the audit trail contributor database. */ public void createAuditTrailContributorDatabase(Settings settings, String pathToSqlCreationScript) { DatabaseSpecifics databaseSpecifics = settings.getReferenceSettings().getPillarSettings().getAuditTrailContributerDatabase(); - createDatabase(databaseSpecifics, pathToSqlCreationScript == null ? + createDatabase(databaseSpecifics, pathToSqlCreationScript == null ? DEFAULT_AUDIT_TRAIL_DB_SCRIPT : pathToSqlCreationScript); } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/SettingsHelper.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/SettingsHelper.java index e72ca1003..d675669d1 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/SettingsHelper.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/common/SettingsHelper.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -22,22 +22,21 @@ package org.bitrepository.pillar.common; +import org.bitrepository.settings.repositorysettings.Collection; + import java.util.ArrayList; import java.util.List; -import org.bitrepository.settings.repositorysettings.Collection; - /** - * - Provides functionality for creating data derived from the pillar settings + * Provides functionality for creating data derived from the pillar settings */ public final class SettingsHelper { - /** Private constructor, to avoid instantiation of this utility class.*/ private SettingsHelper() {} - + /** * Calculates the list of pillars - * @param pillarID The ID of the pillar. + * + * @param pillarID The ID of the pillar. * @param collections The collection for the whole repository. * @return all pillars in collections with the provided pillarID */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/DeleteFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/DeleteFileRequestHandler.java index 1e6c3125a..a7b4711bd 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/DeleteFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/DeleteFileRequestHandler.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -44,16 +44,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Class for handling the DeleteFile operation. - */ public class DeleteFileRequestHandler extends PerformRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - + private final Logger log = LoggerFactory.getLogger(getClass()); + /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected DeleteFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -68,42 +64,40 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(DeleteFileRequest request) { return createFinalResponse(request); } - + @Override - protected void validateRequest(DeleteFileRequest request, MessageContext messageContext) + protected void validateRequest(DeleteFileRequest request, MessageContext messageContext) throws RequestHandlerException { validateCollectionID(request); validatePillarId(request.getPillarID()); - getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile(), - request.getCollectionID()); - if(request.getChecksumDataForExistingFile() != null) { - getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForExistingFile().getChecksumSpec(), - request.getCollectionID()); - } else if(getSettings().getRepositorySettings().getProtocolSettings() + getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile()); + if (request.getChecksumDataForExistingFile() != null) { + getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForExistingFile().getChecksumSpec()); + } else if (getSettings().getRepositorySettings().getProtocolSettings() .isRequireChecksumForDestructiveRequests()) { throw new IllegalOperationException(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, "No mandatory checksum " + "for destructive operation was supplied.", request.getFileID()); } - + validateFileIDFormat(request.getFileID()); // Validate, that we have the requested file. - if(!getPillarModel().hasFileID(request.getFileID(), request.getCollectionID())) { + if (!getPillarModel().hasFileID(request.getFileID(), request.getCollectionID())) { throw new InvalidMessageException(ResponseCode.FILE_NOT_FOUND_FAILURE, "File not found."); } - + // calculate and validate the checksum of the file. ChecksumDataForFileTYPE checksumData = request.getChecksumDataForExistingFile(); - if(checksumData != null) { + if (checksumData != null) { ChecksumSpecTYPE checksumType = checksumData.getChecksumSpec(); - String calculatedChecksum = getPillarModel().getChecksumForFile(request.getFileID(), + String calculatedChecksum = getPillarModel().getChecksumForFile(request.getFileID(), request.getCollectionID(), checksumType); String requestedChecksum = Base16Utils.decodeBase16(checksumData.getChecksumValue()); - if(!calculatedChecksum.equals(requestedChecksum)) { + if (!calculatedChecksum.equals(requestedChecksum)) { // Log the different checksums, but do not send the right checksum back! log.warn("Failed to handle delete operation on file '" + request.getFileID() + "' since the request " - + "had the checksum '" + requestedChecksum + "' where our local file has the value '" + + "had the checksum '" + requestedChecksum + "' where our local file has the value '" + calculatedChecksum + "'. Sending alarm and respond failure."); throw new IllegalOperationException(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, "Cannot delete file " @@ -113,12 +107,13 @@ protected void validateRequest(DeleteFileRequest request, MessageContext message log.debug("No checksum for validation of the existing file before delete the file '" + request.getFileID() + "'"); } - + log.debug(MessageUtils.createMessageIdentifier(request) + "' validated and accepted."); } /** * The method for sending a progress response telling, that the operation is about to be performed. + * * @param request The request for the DeleteFile operation. */ @Override @@ -131,49 +126,51 @@ protected void sendProgressResponse(DeleteFileRequest request, MessageContext re dispatchResponse(response, request); } - + @Override - protected void performOperation(DeleteFileRequest request, MessageContext requestContext) + protected void performOperation(DeleteFileRequest request, MessageContext requestContext) throws RequestHandlerException { - log.info(MessageUtils.createMessageIdentifier(request) + " Deleting file " + request.getFileID() + log.info(MessageUtils.createMessageIdentifier(request) + " Deleting file " + request.getFileID() + " on collection " + request.getCollectionID()); ChecksumDataForFileTYPE resultingChecksum = calculatedRequestedChecksum(request); deleteTheFile(request); - getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), + getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), "Deleting the file.", request.getAuditTrailInformation(), FileAction.DELETE_FILE, request.getCorrelationID(), requestContext.getCertificateFingerprint()); sendFinalResponse(request, resultingChecksum); } /** - * Method for calculating the requested checksum. + * Method for calculating the requested checksum. * If no checksum is requested to be delivered back a warning is logged. + * * @param message The request for deleting the file. Contains the specs for calculating the checksum. * @return The requested checksum, or null if no such checksum is requested. * @throws RequestHandlerException If the requested checksum specification is not supported. */ - private ChecksumDataForFileTYPE calculatedRequestedChecksum(DeleteFileRequest message) + private ChecksumDataForFileTYPE calculatedRequestedChecksum(DeleteFileRequest message) throws RequestHandlerException { ChecksumSpecTYPE checksumType = message.getChecksumRequestForExistingFile(); - if(checksumType == null) { + if (checksumType == null) { return null; } return getPillarModel().getChecksumDataForFile(message.getFileID(), message.getCollectionID(), checksumType); } - + /** * Performs the operation of deleting the file from the archive. + * * @param message The message requesting the file to be deleted. */ - private void deleteTheFile(DeleteFileRequest message) - throws RequestHandlerException { + private void deleteTheFile(DeleteFileRequest message) { getPillarModel().deleteFile(message.getFileID(), message.getCollectionID()); } /** * Method for sending the final response. - * @param request The request to respond to. + * + * @param request The request to respond to. * @param requestedChecksum The results of the requested checksums */ private void sendFinalResponse(DeleteFileRequest request, ChecksumDataForFileTYPE requestedChecksum) { @@ -185,12 +182,12 @@ private void sendFinalResponse(DeleteFileRequest request, ChecksumDataForFileTYP dispatchResponse(response, request); } - + /** - * Creates a DeleteFileProgressResponse based on a DeleteFileRequest. Missing the + * Creates a DeleteFileProgressResponse based on a DeleteFileRequest. Missing the * following fields: *
    - ResponseInfo - * + * * @param request The DeleteFileRequest to base the progress response on. * @return The DeleteFileProgressResponse based on the request. */ @@ -198,16 +195,16 @@ private DeleteFileProgressResponse createDeleteFileProgressResponse(DeleteFileRe DeleteFileProgressResponse res = new DeleteFileProgressResponse(); res.setFileID(request.getFileID()); res.setPillarID(getPillarModel().getPillarID()); - + return res; } - + /** - * Creates a DeleteFileFinalResponse based on a DeleteFileRequest. Missing the + * Creates a DeleteFileFinalResponse based on a DeleteFileRequest. Missing the * following fields: *
    - ResponseInfo *
    - ChecksumDataForFile - * + * * @param msg The DeleteFileRequest to base the final response on. * @return The DeleteFileFinalResponse based on the request. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetChecksumsRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetChecksumsRequestHandler.java index 1f78a9dbd..78064bfae 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetChecksumsRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetChecksumsRequestHandler.java @@ -8,35 +8,22 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.messagehandler; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Date; - -import javax.xml.bind.JAXBException; - import org.apache.activemq.util.ByteArrayInputStream; import org.bitrepository.bitrepositorydata.GetChecksumsResults; import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; @@ -59,16 +46,24 @@ import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; -/** - * Class for performing the GetChecksums operation for this pillar. - */ +import javax.xml.bind.JAXBException; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Date; + public class GetChecksumsRequestHandler extends PerformRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected GetChecksumsRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -85,12 +80,11 @@ public MessageResponse generateFailedResponse(GetChecksumsRequest request) { } @Override - protected void validateRequest(GetChecksumsRequest request, MessageContext requestContext) + protected void validateRequest(GetChecksumsRequest request, MessageContext requestContext) throws RequestHandlerException { validateCollectionID(request); validatePillarId(request.getPillarID()); - getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile(), - request.getCollectionID()); + getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile()); if (request.getFileIDs() != null && request.getFileIDs().getFileID() != null) { validateFileIDFormat(request.getFileIDs().getFileID()); verifyFileIDExistence(request.getFileIDs(), request.getCollectionID()); @@ -112,13 +106,13 @@ protected void sendProgressResponse(GetChecksumsRequest request, MessageContext } @Override - protected void performOperation(GetChecksumsRequest request, MessageContext requestContext) + protected void performOperation(GetChecksumsRequest request, MessageContext requestContext) throws RequestHandlerException { - log.debug(MessageUtils.createMessageIdentifier(request) + " Performing GetChecksums for file(s) " + log.debug(MessageUtils.createMessageIdentifier(request) + " Performing GetChecksums for file(s) " + request.getFileIDs() + " on collection " + request.getCollectionID()); ExtractedChecksumResultSet extractedChecksums = extractChecksumResults(request); ResultingChecksums checksumResults; - if(request.getResultAddress() == null) { + if (request.getResultAddress() == null) { checksumResults = compileResultsForMessage(extractedChecksums); } else { checksumResults = createAndUploadResults(request, extractedChecksums); @@ -128,38 +122,39 @@ protected void performOperation(GetChecksumsRequest request, MessageContext requ /** * Method for calculating the checksum results requested. + * * @param request The message with the checksum request. * @return The extracted results for the requested checksum. * @throws RequestHandlerException If the requested checksum specification is not supported. */ - private ExtractedChecksumResultSet extractChecksumResults(GetChecksumsRequest request) + private ExtractedChecksumResultSet extractChecksumResults(GetChecksumsRequest request) throws RequestHandlerException { log.debug("Starting to extracting the checksum of the requested files."); - if(request.getFileIDs().isSetFileID()) { - return getPillarModel().getSingleChecksumResultSet(request.getFileIDs().getFileID(), - request.getCollectionID(), request.getMinTimestamp(), request.getMaxTimestamp(), + if (request.getFileIDs().isSetFileID()) { + return getPillarModel().getSingleChecksumResultSet(request.getFileIDs().getFileID(), + request.getCollectionID(), request.getMinTimestamp(), request.getMaxTimestamp(), request.getChecksumRequestForExistingFile()); } else { Long maxResults = null; - if(request.getMaxNumberOfResults() != null) { + if (request.getMaxNumberOfResults() != null) { maxResults = request.getMaxNumberOfResults().longValue(); } - return getPillarModel().getChecksumResultSet(request.getMinTimestamp(), request.getMaxTimestamp(), + return getPillarModel().getChecksumResultSet(request.getMinTimestamp(), request.getMaxTimestamp(), maxResults, request.getCollectionID(), request.getChecksumRequestForExistingFile()); } } /** - * Uploads the extracted checksum results to the given URL, and creates the ResultingChecksums object for + * Uploads the extracted checksum results to the given URL, and creates the ResultingChecksums object for * the final response message. - * - * @param request The message requesting the calculation of the checksums. + * + * @param request The message requesting the calculation of the checksums. * @param checksumResultSet List containing the requested checksums. * @return The ResultingChecksums containing the URL. */ - private ResultingChecksums createAndUploadResults(GetChecksumsRequest request, - ExtractedChecksumResultSet checksumResultSet) throws RequestHandlerException { + private ResultingChecksums createAndUploadResults(GetChecksumsRequest request, + ExtractedChecksumResultSet checksumResultSet) throws RequestHandlerException { ResultingChecksums res = new ResultingChecksums(); String url = request.getResultAddress(); @@ -174,16 +169,17 @@ private ResultingChecksums createAndUploadResults(GetChecksumsRequest request, res.setResultAddress(url); return res; } - + /** * Compiles the extracted checksum results into the message format. + * * @param checksumResultSet The checksum results extracted from the database. * @return The extracted results in the ResultingChecksums format. */ private ResultingChecksums compileResultsForMessage(ExtractedChecksumResultSet checksumResultSet) { ResultingChecksums res = new ResultingChecksums(); - - for(ChecksumDataForChecksumSpecTYPE cs : checksumResultSet.getEntries()) { + + for (ChecksumDataForChecksumSpecTYPE cs : checksumResultSet.getEntries()) { res.getChecksumDataItems().add(cs); } @@ -192,16 +188,16 @@ private ResultingChecksums compileResultsForMessage(ExtractedChecksumResultSet c /** * Method for creating a file containing the list of calculated checksums. - * - * @param request The GetChecksumMessage requesting the checksum calculations. + * + * @param request The GetChecksumMessage requesting the checksum calculations. * @param checksumResultSet The list of checksums to put into the list. * @return A file containing all the checksums in the list. - * @throws IOException If something goes wrong in the upload. + * @throws IOException If something goes wrong in the upload. * @throws JAXBException If the resulting structure cannot be serialized. - * @throws SAXException If the results does not validate against the XSD. + * @throws SAXException If the results does not validate against the XSD. */ private File makeTemporaryChecksumFile(GetChecksumsRequest request, - ExtractedChecksumResultSet checksumResultSet) throws IOException, JAXBException, SAXException { + ExtractedChecksumResultSet checksumResultSet) throws IOException, JAXBException, SAXException { // Create the temporary file. File checksumResultFile = File.createTempFile(request.getCorrelationID(), new Date().getTime() + ".cs"); log.debug("Writing the list of checksums to the file '" + checksumResultFile + "'"); @@ -212,23 +208,17 @@ private File makeTemporaryChecksumFile(GetChecksumsRequest request, results.setMinVersion(MIN_VERSION); results.setPillarID(getSettings().getReferenceSettings().getPillarSettings().getPillarID()); results.setCollectionID(request.getCollectionID()); - for(ChecksumDataForChecksumSpecTYPE cs : checksumResultSet.getEntries()) { + for (ChecksumDataForChecksumSpecTYPE cs : checksumResultSet.getEntries()) { results.getChecksumDataItems().add(cs); } // Print all the checksums safely (close the streams!) - OutputStream is = null; - try { - is = new FileOutputStream(checksumResultFile); + try (OutputStream is = new FileOutputStream(checksumResultFile)) { JaxbHelper jaxb = new JaxbHelper(XSD_CLASSPATH, XSD_BR_DATA); String xmlMessage = jaxb.serializeToXml(results); jaxb.validate(new ByteArrayInputStream(xmlMessage.getBytes(StandardCharsets.UTF_8))); is.write(xmlMessage.getBytes(StandardCharsets.UTF_8)); is.flush(); - } finally { - if(is != null) { - is.close(); - } } return checksumResultFile; @@ -236,10 +226,10 @@ private File makeTemporaryChecksumFile(GetChecksumsRequest request, /** * Method for uploading a file to a given URL. - * + * * @param fileToUpload The File to upload. - * @param url The location where the file should be uploaded. - * @throws Exception If something goes wrong. + * @param url The location where the file should be uploaded. + * @throws IOException If something goes wrong. */ private void uploadFile(File fileToUpload, String url) throws IOException { URL uploadUrl = new URL(url); @@ -253,12 +243,13 @@ private void uploadFile(File fileToUpload, String url) throws IOException { /** * Method for sending a final response reporting the success. - * @param request The GetChecksumRequest to base the response upon. - * @param results The results of the checksum calculations. + * + * @param request The GetChecksumRequest to base the response upon. + * @param results The results of the checksum calculations. * @param hasMoreEntries Whether more results can be found. */ - private void sendFinalResponse(GetChecksumsRequest request, ResultingChecksums results, - boolean hasMoreEntries) { + private void sendFinalResponse(GetChecksumsRequest request, ResultingChecksums results, + boolean hasMoreEntries) { GetChecksumsFinalResponse response = createFinalResponse(request); ResponseInfo fri = new ResponseInfo(); @@ -274,7 +265,7 @@ private void sendFinalResponse(GetChecksumsRequest request, ResultingChecksums r * Method for creating a GetChecksumProgressResponse based on a request. * Missing arguments: *
    AuditTrailInformation - * + * * @param message The GetChecksumsRequest to base the results upon. * @return The GetChecksumsProgressResponse based on the GetChecksumsRequest. */ @@ -294,7 +285,7 @@ private GetChecksumsProgressResponse createProgressResponse(GetChecksumsRequest *
    - AuditTrailInformation *
    - FinalResponseInfo *
    - ResultingChecksums - * + * * @param message The message to base the response upon and respond to. * @return The response for the generic GetChecksumRequest. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileIDsRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileIDsRequestHandler.java index c3d635936..e4f94a46d 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileIDsRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileIDsRequestHandler.java @@ -3,40 +3,28 @@ * bitrepository-access-client * * * $Id: GetFileIDsRequestHandler.java 685 2012-01-06 16:35:17Z jolf $ - * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileIDsRequestHandler.java $ + * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/main/java/org + * /bitrepository/pillar/messagehandler/GetFileIDsRequestHandler.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.messagehandler; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Date; - -import javax.xml.bind.JAXBException; - import org.apache.activemq.util.ByteArrayInputStream; import org.bitrepository.bitrepositorydata.GetFileIDsResults; import org.bitrepository.bitrepositoryelements.FileIDsData; @@ -59,21 +47,29 @@ import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; -/** - * Class for handling requests for the GetFileIDs operation. - */ +import javax.xml.bind.JAXBException; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Date; + public class GetFileIDsRequestHandler extends PerformRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected GetFileIDsRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); } - + @Override public Class getRequestClass() { return GetFileIDsRequest.class; @@ -85,7 +81,7 @@ public MessageResponse generateFailedResponse(GetFileIDsRequest request) { } @Override - protected void validateRequest(GetFileIDsRequest request, MessageContext requestContext) + protected void validateRequest(GetFileIDsRequest request, MessageContext requestContext) throws RequestHandlerException { validateCollectionID(request); validatePillarId(request.getPillarID()); @@ -100,7 +96,7 @@ protected void validateRequest(GetFileIDsRequest request, MessageContext request @Override protected void sendProgressResponse(GetFileIDsRequest request, MessageContext requestContext) { GetFileIDsProgressResponse response = createProgressResponse(request); - + ResponseInfo prInfo = new ResponseInfo(); prInfo.setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); prInfo.setResponseText("Starting to locate files."); @@ -110,13 +106,13 @@ protected void sendProgressResponse(GetFileIDsRequest request, MessageContext re } @Override - protected void performOperation(GetFileIDsRequest request, MessageContext requestContext) + protected void performOperation(GetFileIDsRequest request, MessageContext requestContext) throws RequestHandlerException { - log.debug(MessageUtils.createMessageIdentifier(request) + " Performing GetFileIDs for file(s) " + log.debug(MessageUtils.createMessageIdentifier(request) + " Performing GetFileIDs for file(s) " + request.getFileIDs() + " on collection " + request.getCollectionID()); ExtractedFileIDsResultSet extractedFileIDs = retrieveFileIDsData(request); ResultingFileIDs results = new ResultingFileIDs(); - if(request.getResultAddress() == null) { + if (request.getResultAddress() == null) { results.setFileIDsData(extractedFileIDs.getEntries()); } else { uploadResults(request, extractedFileIDs); @@ -124,30 +120,30 @@ protected void performOperation(GetFileIDsRequest request, MessageContext reques } sendFinalResponse(request, results, extractedFileIDs); } - + /** * Retrieves the requested FileIDs. Depending on which operation is requested, it will call the appropriate method. - * + * * @param message The requested for extracting the file ids. * @return The resulting collection of FileIDs found. */ private ExtractedFileIDsResultSet retrieveFileIDsData(GetFileIDsRequest message) { Long maxResults = null; - if(message.getMaxNumberOfResults() != null) { + if (message.getMaxNumberOfResults() != null) { maxResults = message.getMaxNumberOfResults().longValue(); } - return getPillarModel().getFileIDsResultSet(message.getFileIDs().getFileID(), message.getMinTimestamp(), + return getPillarModel().getFileIDsResultSet(message.getFileIDs().getFileID(), message.getMinTimestamp(), message.getMaxTimestamp(), maxResults, message.getCollectionID()); } - + /** * Uploads the results to the URL in the request. - * - * @param request The request. + * + * @param request The request. * @param extractedFileIDs The extracted file ids. - * @throws RequestHandlerException If the file with the resutls could not be created, or could not be uploaded. + * @throws RequestHandlerException If the file with the results could not be created, or could not be uploaded. */ - private void uploadResults(GetFileIDsRequest request, ExtractedFileIDsResultSet extractedFileIDs) + private void uploadResults(GetFileIDsRequest request, ExtractedFileIDsResultSet extractedFileIDs) throws RequestHandlerException { String resultingAddress = request.getResultAddress(); try { @@ -157,33 +153,31 @@ private void uploadResults(GetFileIDsRequest request, ExtractedFileIDsResultSet throw new InvalidMessageException(ResponseCode.FILE_TRANSFER_FAILURE, "Could not deliver results.", e); } } - + /** * Method for creating a file containing the resulting list of file ids. - * + * * @param request The GetFileIDsMessage requesting the checksum calculations. * @param fileIDs The file ids to be put into the result file. * @return A file containing all the checksums in the list. - * @throws IOException If a problem occurs during accessing or handling the data. + * @throws IOException If a problem occurs during accessing or handling the data. * @throws JAXBException If the resulting structure cannot be serialized or if it is invalid. */ private File makeTemporaryResultFile(GetFileIDsRequest request, FileIDsData fileIDs) throws IOException, JAXBException { // Create the temporary file. File checksumResultFile = File.createTempFile(request.getCorrelationID(), new Date().getTime() + ".id"); - log.info("Writing the requested fileids to the file '" + checksumResultFile + "'"); + log.info("Writing the requested fileIDs to the file '" + checksumResultFile + "'"); // Print all the file ids data safely (close the streams!) - OutputStream is = null; - try { - is = new FileOutputStream(checksumResultFile); + try (OutputStream is = new FileOutputStream(checksumResultFile)) { GetFileIDsResults result = new GetFileIDsResults(); result.setCollectionID(request.getCollectionID()); result.setMinVersion(MIN_VERSION); result.setVersion(VERSION); result.setPillarID(getSettings().getReferenceSettings().getPillarSettings().getPillarID()); result.setFileIDsData(fileIDs); - + JaxbHelper jaxbHelper = new JaxbHelper(XSD_CLASSPATH, XSD_BR_DATA); String file = jaxbHelper.serializeToXml(result); try { @@ -196,21 +190,17 @@ private File makeTemporaryResultFile(GetFileIDsRequest request, FileIDsData file } is.write(file.getBytes(StandardCharsets.UTF_8)); is.flush(); - } finally { - if(is != null) { - is.close(); - } } - + return checksumResultFile; } - + /** * Method for uploading a file to a given URL. - * + * * @param fileToUpload The File to upload. - * @param url The location where the file should be uploaded. - * @throws Exception If something goes wrong. + * @param url The location where the file should be uploaded. + * @throws IOException If something goes wrong. */ private void uploadFile(File fileToUpload, String url) throws IOException { URL uploadUrl = new URL(url); @@ -220,18 +210,19 @@ private void uploadFile(File fileToUpload, String url) throws IOException { context.getFileExchange().putFile(in, uploadUrl); } } - + /** * Send a positive final response telling that the operation has successfully finished. - * @param request The request to base the final response upon. - * @param results The results to be put into the final response. + * + * @param request The request to base the final response upon. + * @param results The results to be put into the final response. * @param extractedFileIDs The extracted file ids. Contains whether more results can be found. */ - private void sendFinalResponse(GetFileIDsRequest request, ResultingFileIDs results, - ExtractedFileIDsResultSet extractedFileIDs) { + private void sendFinalResponse(GetFileIDsRequest request, ResultingFileIDs results, + ExtractedFileIDsResultSet extractedFileIDs) { GetFileIDsFinalResponse response = createFinalResponse(request); - if(extractedFileIDs.hasMoreEntries()) { + if (extractedFileIDs.hasMoreEntries()) { response.setPartialResult(true); } @@ -242,12 +233,12 @@ private void sendFinalResponse(GetFileIDsRequest request, ResultingFileIDs resul getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** * Create a generic final response message for the GetFileIDs conversation. * Missing: *
    - ProgressResponseInfo - * + * * @param message The GetFileIDsRequest to base the response upon. * @return The GetFileIDsFinalResponse. */ @@ -259,13 +250,13 @@ private GetFileIDsProgressResponse createProgressResponse(GetFileIDsRequest mess return res; } - + /** * Create a generic final response message for the GetFileIDs conversation. * Missing: *
    - FinalResponseInfo *
    - ResultingFileIDs - * + * * @param message The GetFileIDsRequest to base the response upon. * @return The GetFileIDsFinalResponse. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java index 24c119cc2..d1ad53fb3 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/GetFileRequestHandler.java @@ -8,28 +8,22 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.messagehandler; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.net.URL; - import org.bitrepository.bitrepositoryelements.FileAction; import org.bitrepository.bitrepositoryelements.FilePart; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -48,15 +42,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -/** - * Class for performing the GetFile operation. - */ +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.net.URL; + public class GetFileRequestHandler extends PerformRequestHandler { - private Logger log = LoggerFactory.getLogger(getClass()); - + private final Logger log = LoggerFactory.getLogger(getClass()); + /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected GetFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -73,21 +70,17 @@ public MessageResponse generateFailedResponse(GetFileRequest message) { } @Override - protected void validateRequest(GetFileRequest request, MessageContext requestContext) - throws RequestHandlerException { + protected void validateRequest(GetFileRequest request, MessageContext requestContext) throws RequestHandlerException { validateCollectionID(request); validatePillarId(request.getPillarID()); validateFileIDFormat(request.getFileID()); getPillarModel().verifyFileExists(request.getFileID(), request.getCollectionID()); - } @Override - protected void sendProgressResponse(GetFileRequest request, MessageContext requestContext) - throws RequestHandlerException { - FileInfo requestedFi = getPillarModel().getFileInfoForActualFile(request.getFileID(), - request.getCollectionID()); + protected void sendProgressResponse(GetFileRequest request, MessageContext requestContext) throws RequestHandlerException { + FileInfo requestedFi = getPillarModel().getFileInfoForActualFile(request.getFileID(), request.getCollectionID()); GetFileProgressResponse response = createGetFileProgressResponse(request); response.setFileSize(BigInteger.valueOf(requestedFi.getSize())); @@ -99,31 +92,29 @@ protected void sendProgressResponse(GetFileRequest request, MessageContext reque } @Override - protected void performOperation(GetFileRequest request, MessageContext requestContext) - throws RequestHandlerException { - log.info(MessageUtils.createMessageIdentifier(request) + " Performing GetFile for file " - + request.getFileID() + " on collection " + request.getCollectionID()); + protected void performOperation(GetFileRequest request, MessageContext requestContext) throws RequestHandlerException { + log.info(MessageUtils.createMessageIdentifier(request) + " Performing GetFile for file " + request.getFileID() + " on collection " + + request.getCollectionID()); uploadToClient(request); - getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), - "Failed identifying pillar.", request.getAuditTrailInformation(), FileAction.GET_FILE, - request.getCorrelationID(), requestContext.getCertificateFingerprint()); + getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), "Failed identifying pillar.", + request.getAuditTrailInformation(), FileAction.GET_FILE, request.getCorrelationID(), + requestContext.getCertificateFingerprint()); sendFinalResponse(request); } /** * Method for uploading the file to the requested location. + * * @param message The message requesting the GetFile operation. * @throws InvalidMessageException If the upload of the file fails. */ - protected void uploadToClient(GetFileRequest message) - throws RequestHandlerException { - FileInfo requestedFile = getPillarModel().getFileInfoForActualFile(message.getFileID(), - message.getCollectionID()); + protected void uploadToClient(GetFileRequest message) throws RequestHandlerException { + FileInfo requestedFile = getPillarModel().getFileInfoForActualFile(message.getFileID(), message.getCollectionID()); try { InputStream is; - if(message.getFilePart() == null) { - is = requestedFile.getInputstream(); + if (message.getFilePart() == null) { + is = requestedFile.getInputStream(); } else { is = extractFilePart(requestedFile, message.getFilePart()); } @@ -131,15 +122,16 @@ protected void uploadToClient(GetFileRequest message) log.info("Uploading file: " + requestedFile.getFileID() + " to " + message.getFileAddress()); context.getFileExchange().putFile(is, new URL(message.getFileAddress())); } catch (IOException e) { - log.warn("The file '" + message.getFileID() + "' from collection '" + message.getCollectionID() - + "' could not be uploaded at '" + message.getFileAddress() + "'"); - throw new InvalidMessageException(ResponseCode.FILE_TRANSFER_FAILURE, "Could not deliver file to address '" - + message.getFileAddress() + "'", e); + log.warn("The file '" + message.getFileID() + "' from collection '" + message.getCollectionID() + + "' could not be uploaded at '" + message.getFileAddress() + "'"); + throw new InvalidMessageException(ResponseCode.FILE_TRANSFER_FAILURE, + "Could not deliver file to address '" + message.getFileAddress() + "'", e); } } - + /** - * Extracts a given file part + * Extracts a given file part + * * @param fileInfo The requested file to extract the file part from. * @param filePart The defined interval for the file part. * @return A InputStream with the requested file part. @@ -149,23 +141,26 @@ private InputStream extractFilePart(FileInfo fileInfo, FilePart filePart) throws int offset = filePart.getPartOffSet().intValue(); int size = filePart.getPartLength().intValue(); byte[] partOfFile = new byte[size]; - InputStream fis = null; + InputStream fis = null; try { log.debug("Extracting " + size + " bytes with offset " + offset + " from " + fileInfo.getFileID()); - fis = fileInfo.getInputstream(); - - fis.read(new byte[offset]); - fis.read(partOfFile); + fis = fileInfo.getInputStream(); + + int bytesRead = fis.read(partOfFile, offset, size); + if (bytesRead == size) { + log.debug("Bytes extracted successfully."); + } } finally { - if(fis != null) { + if (fis != null) { fis.close(); } } return new ByteArrayInputStream(partOfFile); } - + /** * Method for sending the final response. + * * @param request The request to respond to. */ protected void sendFinalResponse(GetFileRequest request) { @@ -176,9 +171,10 @@ protected void sendFinalResponse(GetFileRequest request) { dispatchResponse(response, request); } - + /** - * Creates a GetFileProgressResponse based on a GetFileRequest. + * Creates a GetFileProgressResponse based on a GetFileRequest. + * * @param msg The GetFileRequest to base the progress response on. * @return The GetFileProgressResponse based on the request. */ @@ -191,9 +187,10 @@ private GetFileProgressResponse createGetFileProgressResponse(GetFileRequest msg return res; } - + /** - * Creates a GetFileFinalResponse based on a GetFileRequest. + * Creates a GetFileFinalResponse based on a GetFileRequest. + * * @param msg The GetFileRequest to base the final response on. * @return The GetFileFinalResponse based on the request. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForDeleteFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForDeleteFileRequestHandler.java index 35177d2d5..35e28945b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForDeleteFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForDeleteFileRequestHandler.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -42,14 +42,13 @@ /** * Class for handling the identification of this pillar for the purpose of performing the DeleteFile operation. */ -public class IdentifyPillarsForDeleteFileRequestHandler +public class IdentifyPillarsForDeleteFileRequestHandler extends IdentifyRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyPillarsForDeleteFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -64,10 +63,10 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(IdentifyPillarsForDeleteFileRequest message) { return createFinalResponse(message); } - + @Override - protected void validateRequest(IdentifyPillarsForDeleteFileRequest request, MessageContext messageContext) + protected void validateRequest(IdentifyPillarsForDeleteFileRequest request, MessageContext messageContext) throws RequestHandlerException { validateCollectionID(request); validateFileIDFormat(request.getFileID()); @@ -78,9 +77,9 @@ protected void validateRequest(IdentifyPillarsForDeleteFileRequest request, Mess protected void sendPositiveResponse(IdentifyPillarsForDeleteFileRequest request, MessageContext messageContext) { IdentifyPillarsForDeleteFileResponse response = createFinalResponse(request); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); - + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); irInfo.setResponseText(RESPONSE_FOR_POSITIVE_IDENTIFICATION); @@ -89,27 +88,28 @@ protected void sendPositiveResponse(IdentifyPillarsForDeleteFileRequest request, dispatchResponse(response, request); log.debug(MessageUtils.createMessageIdentifier(request) + " Identified for performing a DeleteFile operation."); } - + /** - * Validates that the requested files are present in the archive. - * Otherwise an {@link IdentifyContributorException} with the appropriate errorcode is thrown. - * @param message The message containing the id of the file. If no file id is given, then a warning is logged, - * but the operation is accepted. + * Validates that the requested files are present in the archive. + * Otherwise, an {@link IdentifyContributorException} with the appropriate error-code is thrown. + * + * @param message The message containing the id of the file. If no file id is given, then a warning is logged, + * but the operation is accepted. */ - private void checkThatRequestedFileIsAvailable(IdentifyPillarsForDeleteFileRequest message) + private void checkThatRequestedFileIsAvailable(IdentifyPillarsForDeleteFileRequest message) throws RequestHandlerException { - if(!getPillarModel().hasFileID(message.getFileID(), message.getCollectionID())) { + if (!getPillarModel().hasFileID(message.getFileID(), message.getCollectionID())) { throw new IdentifyContributorException(ResponseCode.FILE_NOT_FOUND_FAILURE, "File not found."); } } /** - * Creates a IdentifyPillarsForDeleteFileResponse based on a + * Creates a IdentifyPillarsForDeleteFileResponse based on a * IdentifyPillarsForDeleteFileRequest. The following fields are not inserted: *
    - TimeToDeliver *
    - ResponseInfo *
    - PillarChecksumSpec - * + * * @param msg The IdentifyPillarsForDeleteFileRequest to base the response on. * @return The response to the request. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetChecksumsRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetChecksumsRequestHandler.java index 81f9fc0c6..f84613658 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetChecksumsRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetChecksumsRequestHandler.java @@ -8,16 +8,16 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -43,19 +43,17 @@ /** * Class for handling the identification of this pillar for the purpose of performing the GetChecksums operation. */ -public class IdentifyPillarsForGetChecksumsRequestHandler - extends IdentifyRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); +public class IdentifyPillarsForGetChecksumsRequestHandler extends IdentifyRequestHandler { + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyPillarsForGetChecksumsRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); } - + @Override public Class getRequestClass() { return IdentifyPillarsForGetChecksumsRequest.class; @@ -65,13 +63,12 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(IdentifyPillarsForGetChecksumsRequest message) { return createFinalResponse(message); } - + @Override protected void validateRequest(IdentifyPillarsForGetChecksumsRequest request, MessageContext messageContext) throws RequestHandlerException { validateCollectionID(request); - getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile(), - request.getCollectionID()); + getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile()); if (request.getFileIDs() != null && request.getFileIDs().getFileID() != null) { validateFileIDFormat(request.getFileIDs().getFileID()); checkThatAllRequestedFilesAreAvailable(request); @@ -82,41 +79,40 @@ protected void validateRequest(IdentifyPillarsForGetChecksumsRequest request, Me protected void sendPositiveResponse(IdentifyPillarsForGetChecksumsRequest request, MessageContext requestContext) { IdentifyPillarsForGetChecksumsResponse response = createFinalResponse(request); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); irInfo.setResponseText(RESPONSE_FOR_POSITIVE_IDENTIFICATION); response.setResponseInfo(irInfo); - + dispatchResponse(response, request); - log.debug(MessageUtils.createMessageIdentifier(request) - + " Identified for performing a GetChecksums operation."); + log.debug(MessageUtils.createMessageIdentifier(request) + " Identified for performing a GetChecksums operation."); } /** - * Validates that all the requested files in the filelist are present. - * Otherwise an {@link IdentifyContributorException} with the appropriate errorcode is thrown. - * @param message The message containing the list files. An empty filelist is expected - * when "AllFiles" or the parameter option is used. + * Validates that all the requested files in the file-list are present. + * Otherwise an {@link IdentifyContributorException} with the appropriate error-code is thrown. + * + * @param message The message containing the list files. An empty file-list is expected + * when "AllFiles" or the parameter option is used. */ - private void checkThatAllRequestedFilesAreAvailable(IdentifyPillarsForGetChecksumsRequest message) - throws RequestHandlerException { + private void checkThatAllRequestedFilesAreAvailable(IdentifyPillarsForGetChecksumsRequest message) throws RequestHandlerException { FileIDs fileids = message.getFileIDs(); - - if(fileids.getFileID() != null && !getPillarModel().hasFileID(fileids.getFileID(), message.getCollectionID())) { + + if (fileids.getFileID() != null && !getPillarModel().hasFileID(fileids.getFileID(), message.getCollectionID())) { throw new IdentifyContributorException(ResponseCode.FILE_NOT_FOUND_FAILURE, "File not found."); } } - + /** - * Creates a IdentifyPillarsForGetChecksumsResponse based on a + * Creates a IdentifyPillarsForGetChecksumsResponse based on a * IdentifyPillarsForGetFileRequest. The following fields are not inserted: *
    - AuditTrailInformation *
    - ResponseInfo *
    - PillarChecksumSpec - * + * * @param msg The IdentifyPillarsForGetFileRequest to base the response on. * @return The response to the request. */ @@ -126,7 +122,7 @@ private IdentifyPillarsForGetChecksumsResponse createFinalResponse(IdentifyPilla res.setChecksumRequestForExistingFile(msg.getChecksumRequestForExistingFile()); res.setPillarID(getPillarModel().getPillarID()); res.setPillarChecksumSpec(getPillarModel().getChecksumPillarSpec()); - + return res; } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileIDsRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileIDsRequestHandler.java index e5856523d..bf2baa53a 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileIDsRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileIDsRequestHandler.java @@ -8,16 +8,16 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -41,19 +41,17 @@ /** * Class for handling the identification of this pillar for the purpose of performing the GetFileIDs operation. */ -public class IdentifyPillarsForGetFileIDsRequestHandler - extends IdentifyRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - +public class IdentifyPillarsForGetFileIDsRequestHandler extends IdentifyRequestHandler { + private final Logger log = LoggerFactory.getLogger(getClass()); + /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyPillarsForGetFileIDsRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); } - + @Override public Class getRequestClass() { return IdentifyPillarsForGetFileIDsRequest.class; @@ -63,9 +61,9 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(IdentifyPillarsForGetFileIDsRequest message) { return createFinalResponse(message); } - + @Override - protected void validateRequest(IdentifyPillarsForGetFileIDsRequest request, MessageContext messageContext) + protected void validateRequest(IdentifyPillarsForGetFileIDsRequest request, MessageContext messageContext) throws RequestHandlerException { validateCollectionID(request); if (request.getFileIDs() != null && request.getFileIDs().getFileID() != null) { @@ -73,13 +71,13 @@ protected void validateRequest(IdentifyPillarsForGetFileIDsRequest request, Mess verifyFileIDExistence(request.getFileIDs(), request.getCollectionID()); } } - + @Override protected void sendPositiveResponse(IdentifyPillarsForGetFileIDsRequest request, MessageContext requestContext) { IdentifyPillarsForGetFileIDsResponse response = createFinalResponse(request); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); - + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); irInfo.setResponseText(RESPONSE_FOR_POSITIVE_IDENTIFICATION); @@ -88,13 +86,13 @@ protected void sendPositiveResponse(IdentifyPillarsForGetFileIDsRequest request, dispatchResponse(response, request); log.debug(MessageUtils.createMessageIdentifier(request) + " Identified for performing a GetFileIDs operation."); } - + /** - * Creates a IdentifyPillarsForGetFileIDsResponse based on a + * Creates a IdentifyPillarsForGetFileIDsResponse based on a * IdentifyPillarsForGetFileIDsRequest. The following fields are not inserted: *
    - TimeToDeliver *
    - IdentifyResponseInfo - * + * * @param msg The IdentifyPillarsForGetFileIDsRequest to base the response on. * @return The response to the request. */ @@ -102,7 +100,7 @@ private IdentifyPillarsForGetFileIDsResponse createFinalResponse(IdentifyPillars IdentifyPillarsForGetFileIDsResponse res = new IdentifyPillarsForGetFileIDsResponse(); res.setFileIDs(msg.getFileIDs()); res.setPillarID(getPillarModel().getPillarID()); - + return res; } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileRequestHandler.java index f218d21ba..870928456 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForGetFileRequestHandler.java @@ -8,16 +8,16 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -42,19 +42,17 @@ /** * Class for handling the identification of this pillar for the purpose of performing the GetFile operation. */ -public class IdentifyPillarsForGetFileRequestHandler - extends IdentifyRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); +public class IdentifyPillarsForGetFileRequestHandler extends IdentifyRequestHandler { + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyPillarsForGetFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); } - + @Override public Class getRequestClass() { return IdentifyPillarsForGetFileRequest.class; @@ -64,18 +62,16 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(IdentifyPillarsForGetFileRequest message) { return createFinalResponse(message); } - + @Override - protected void validateRequest(IdentifyPillarsForGetFileRequest request, MessageContext requestContext) - throws RequestHandlerException { - if(getPillarModel().getChecksumPillarSpec() != null) { - throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "A ChecksumPillar cannot deliver " - + "actual files."); + protected void validateRequest(IdentifyPillarsForGetFileRequest request, MessageContext requestContext) throws RequestHandlerException { + if (getPillarModel().getChecksumPillarSpec() != null) { + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "A ChecksumPillar cannot deliver " + "actual files."); } validateCollectionID(request); validateFileIDFormat(request.getFileID()); - + checkThatFileIsAvailable(request); } @@ -83,9 +79,9 @@ protected void validateRequest(IdentifyPillarsForGetFileRequest request, Message protected void sendPositiveResponse(IdentifyPillarsForGetFileRequest request, MessageContext requestContext) { IdentifyPillarsForGetFileResponse response = createFinalResponse(request); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); - + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); irInfo.setResponseText(RESPONSE_FOR_POSITIVE_IDENTIFICATION); @@ -94,24 +90,24 @@ protected void sendPositiveResponse(IdentifyPillarsForGetFileRequest request, Me dispatchResponse(response, request); log.debug(MessageUtils.createMessageIdentifier(request) + " Identified for performing a GetFile operation."); } - + /** - * Validates that the requested file is within the archive. - * Otherwise an {@link IdentifyContributorException} with the appropriate errorcode is thrown. + * Validates that the requested file is within the archive. + * * @param message The request for the identification for the GetFileRequest operation. + * @throws RequestHandlerException If the file could not be found in the archive. */ - private void checkThatFileIsAvailable(IdentifyPillarsForGetFileRequest message) - throws RequestHandlerException { + private void checkThatFileIsAvailable(IdentifyPillarsForGetFileRequest message) throws RequestHandlerException { getPillarModel().verifyFileExists(message.getFileID(), message.getCollectionID()); } - + /** - * Creates a IdentifyPillarsForGetFileResponse based on a + * Creates a IdentifyPillarsForGetFileResponse based on a * IdentifyPillarsForGetFileRequest. The following fields are not inserted: *
    - TimeToDeliver *
    - AuditTrailInformation *
    - IdentifyResponseInfo - * + * * @param msg The IdentifyPillarsForGetFileRequest to base the response on. * @return The response to the request. */ @@ -119,7 +115,7 @@ private IdentifyPillarsForGetFileResponse createFinalResponse(IdentifyPillarsFor IdentifyPillarsForGetFileResponse res = new IdentifyPillarsForGetFileResponse(); res.setFileID(msg.getFileID()); res.setPillarID(getPillarModel().getPillarID()); - + return res; } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForPutFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForPutFileRequestHandler.java index 64ae518ee..d98a8933c 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForPutFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForPutFileRequestHandler.java @@ -8,24 +8,22 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.messagehandler; -import java.math.BigInteger; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositoryelements.ResponseInfo; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForPutFileRequest; @@ -41,117 +39,116 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.math.BigInteger; + /** * Class for handling the identification of this pillar for the purpose of performing the PutFile operation. */ -public class IdentifyPillarsForPutFileRequestHandler - extends IdentifyRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - +public class IdentifyPillarsForPutFileRequestHandler extends IdentifyRequestHandler { + private final Logger log = LoggerFactory.getLogger(getClass()); + /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyPillarsForPutFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); } - + @Override public Class getRequestClass() { return IdentifyPillarsForPutFileRequest.class; } - + @Override public MessageResponse generateFailedResponse(IdentifyPillarsForPutFileRequest message) { return createFinalResponse(message); } - + @Override - public void validateRequest(IdentifyPillarsForPutFileRequest request, MessageContext messageContext) - throws RequestHandlerException { + public void validateRequest(IdentifyPillarsForPutFileRequest request, MessageContext messageContext) throws RequestHandlerException { validateCollectionID(request); validateFileIDFormat(request.getFileID()); } - + @Override protected void sendPositiveResponse(IdentifyPillarsForPutFileRequest request, MessageContext requestContext) - throws RequestHandlerException { - if(checkThatTheFileDoesNotAlreadyExist(request)) { + throws RequestHandlerException { + if (checkThatTheFileDoesNotAlreadyExist(request)) { respondDuplicateFile(request); } else { checkSpaceForStoringNewFile(request); - respondSuccesfullIdentification(request); + respondSuccessfulIdentification(request); } } - + /** - * Validates that the file is not already within the archive. - * Otherwise an {@link IdentifyContributorException} with the appropriate errorcode is thrown. + * Validates that the file is not already within the archive. + * * @param message The request with the filename to validate. * @return Whether the file already exists. */ private boolean checkThatTheFileDoesNotAlreadyExist(IdentifyPillarsForPutFileRequest message) { - if(message.getFileID() == null) { - log.debug("No fileid given in the identification request."); + if (message.getFileID() == null) { + log.debug("No fileID given in the identification request."); return false; } - + return getPillarModel().hasFileID(message.getFileID(), message.getCollectionID()); } - + /** * Validates that enough space exists is left in the archive. - * Otherwise an {@link IdentifyContributorException} with the appropriate errorcode is thrown. + * * @param message The request with the size of the file. + * @throws RequestHandlerException If there is not enough space free to store the file. */ - private void checkSpaceForStoringNewFile(IdentifyPillarsForPutFileRequest message) - throws RequestHandlerException { + private void checkSpaceForStoringNewFile(IdentifyPillarsForPutFileRequest message) throws RequestHandlerException { BigInteger fileSize = message.getFileSize(); - if(fileSize == null) { - log.debug("No file size given in the identification request. " - + "Validating that the archive has any space left."); + if (fileSize == null) { + log.debug("No file size given in the identification request. " + "Validating that the archive has any space left."); fileSize = BigInteger.ZERO; } - + getPillarModel().verifyEnoughFreeSpaceLeftForFile(fileSize.longValue(), message.getCollectionID()); } - + /** * Method for sending a response for 'DUPLICATE_FILE_FAILURE'. + * * @param message The request to base the response upon. - * @throws RequestHandlerException + * @throws RequestHandlerException If the checksum of the file from the request could not be verified. */ private void respondDuplicateFile(IdentifyPillarsForPutFileRequest message) throws RequestHandlerException { IdentifyPillarsForPutFileResponse response = createFinalResponse(message); response.setReplyTo(getSettings().getReceiverDestinationID()); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); - response.setChecksumDataForExistingFile(getPillarModel().getChecksumDataForFile(message.getFileID(), - message.getCollectionID(), ChecksumUtils.getDefault(getSettings()))); - + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + response.setChecksumDataForExistingFile(getPillarModel().getChecksumDataForFile(message.getFileID(), message.getCollectionID(), + ChecksumUtils.getDefault(getSettings()))); + ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.DUPLICATE_FILE_FAILURE); response.setResponseInfo(irInfo); dispatchResponse(response, message); - log.debug(MessageUtils.createMessageIdentifier(message) - + " Duplicate file identification for PutFile operation"); + log.debug(MessageUtils.createMessageIdentifier(message) + " Duplicate file identification for PutFile operation"); } - + /** * Method for sending a positive response for putting this file. + * * @param request The request to respond to. */ - private void respondSuccesfullIdentification(IdentifyPillarsForPutFileRequest request) { + private void respondSuccessfulIdentification(IdentifyPillarsForPutFileRequest request) { IdentifyPillarsForPutFileResponse response = createFinalResponse(request); // Needs to filled in: AuditTrailInformation, PillarChecksumSpec, ReplyTo, TimeToDeliver response.setReplyTo(getSettings().getContributorDestinationID()); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); - + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); irInfo.setResponseText(RESPONSE_FOR_POSITIVE_IDENTIFICATION); @@ -160,15 +157,15 @@ private void respondSuccesfullIdentification(IdentifyPillarsForPutFileRequest re dispatchResponse(response, request); log.debug(MessageUtils.createMessageIdentifier(request) + " Identified for performing a PutFile operation."); } - + /** - * Creates a IdentifyPillarsForPutFileResponse based on a + * Creates a IdentifyPillarsForPutFileResponse based on a * IdentifyPillarsForPutFileRequest. The following fields are not inserted: *
    - TimeToDeliver *
    - AuditTrailInformation *
    - PillarChecksumSpec *
    - IdentifyResponseInfo - * + * * @param msg The IdentifyPillarsForPutFileRequest to base the response on. * @return A IdentifyPillarsForPutFileResponse from the request. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForReplaceFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForReplaceFileRequestHandler.java index 235f7f487..bea3c6e2b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForReplaceFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyPillarsForReplaceFileRequestHandler.java @@ -1,31 +1,29 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.messagehandler; -import java.math.BigInteger; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositoryelements.ResponseInfo; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForReplaceFileRequest; @@ -41,17 +39,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.math.BigInteger; + /** * Class for handling the identification of this pillar for the purpose of performing the ReplaceFile operation. */ -public class IdentifyPillarsForReplaceFileRequestHandler - extends IdentifyRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); +public class IdentifyPillarsForReplaceFileRequestHandler extends IdentifyRequestHandler { + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyPillarsForReplaceFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -66,68 +64,65 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(IdentifyPillarsForReplaceFileRequest message) { return createFinalResponse(message); } - + @Override - protected void validateRequest(IdentifyPillarsForReplaceFileRequest request, MessageContext messageContext) + protected void validateRequest(IdentifyPillarsForReplaceFileRequest request, MessageContext messageContext) throws RequestHandlerException { validateCollectionID(request); validateFileIDFormat(request.getFileID()); checkThatRequestedFileIsAvailable(request); checkSpaceForStoringNewFile(request); } - + @Override - protected void sendPositiveResponse(IdentifyPillarsForReplaceFileRequest request, - MessageContext requestContext) throws RequestHandlerException { + protected void sendPositiveResponse(IdentifyPillarsForReplaceFileRequest request, MessageContext requestContext) { IdentifyPillarsForReplaceFileResponse response = createFinalResponse(request); - response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMiliseconds( - getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); - + response.setTimeToDeliver(TimeMeasurementUtils.getTimeMeasurementFromMilliseconds( + getSettings().getReferenceSettings().getPillarSettings().getTimeToStartDeliver())); + ResponseInfo irInfo = new ResponseInfo(); irInfo.setResponseCode(ResponseCode.IDENTIFICATION_POSITIVE); irInfo.setResponseText(RESPONSE_FOR_POSITIVE_IDENTIFICATION); response.setResponseInfo(irInfo); dispatchResponse(response, request); - log.debug(MessageUtils.createMessageIdentifier(request) - + " Identified for performing a ReplaceFile operation."); + log.debug(MessageUtils.createMessageIdentifier(request) + " Identified for performing a ReplaceFile operation."); } /** - * Validates that the requested files are present in the archive. - * Otherwise an {@link IdentifyContributorException} with the appropriate error code is thrown. - * @param message The message containing the id of the file. + * Validates that the requested files are present in the archive. + * + * @param message The message containing the id of the file. + * @throws IdentifyContributorException If the file is not available, e.g. it doesn't exist. */ - private void checkThatRequestedFileIsAvailable(IdentifyPillarsForReplaceFileRequest message) - throws RequestHandlerException { - if(!getPillarModel().hasFileID(message.getFileID(), message.getCollectionID())) { - throw new IdentifyContributorException(ResponseCode.FILE_NOT_FOUND_FAILURE, "Could not find the " - + "requested file to delete."); + private void checkThatRequestedFileIsAvailable(IdentifyPillarsForReplaceFileRequest message) throws IdentifyContributorException { + if (!getPillarModel().hasFileID(message.getFileID(), message.getCollectionID())) { + throw new IdentifyContributorException(ResponseCode.FILE_NOT_FOUND_FAILURE, + "Could not find the " + "requested file to delete."); } } - + /** * Validates that enough space exists is left in the archive. - * Otherwise an {@link IdentifyContributorException} with the appropriate error code is thrown. + * * @param message The request with the size of the file. + * @throws RequestHandlerException If there is not enough space free to store the file. */ - private void checkSpaceForStoringNewFile(IdentifyPillarsForReplaceFileRequest message) - throws RequestHandlerException { + private void checkSpaceForStoringNewFile(IdentifyPillarsForReplaceFileRequest message) throws RequestHandlerException { BigInteger fileSize = message.getFileSize(); - if(fileSize == null) { - log.debug("No file size given in the identification request. " - + "Validating that the archive has any space left."); + if (fileSize == null) { + log.debug("No file size given in the identification request. " + "Validating that the archive has any space left."); fileSize = BigInteger.ZERO; } - + getPillarModel().verifyEnoughFreeSpaceLeftForFile(fileSize.longValue(), message.getCollectionID()); } - + /** - * Creates a IdentifyPillarsForGetChecksumsResponse based on a - * IdentifyPillarsForReplaceFileRequest. - * + * Creates a IdentifyPillarsForGetChecksumsResponse based on a + * IdentifyPillarsForReplaceFileRequest. + * * @param request The IdentifyPillarsForReplaceFileRequest to base the response on. * @return The response to the request. */ @@ -136,7 +131,7 @@ private IdentifyPillarsForReplaceFileResponse createFinalResponse(IdentifyPillar res.setFileID(request.getFileID()); res.setPillarID(getPillarModel().getPillarID()); res.setPillarChecksumSpec(getPillarModel().getChecksumPillarSpec()); - + return res; } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyRequestHandler.java index 2ae83f6de..e8a1e5f16 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/IdentifyRequestHandler.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -30,14 +30,14 @@ /** * Abstract class for the methods for handing the identify request messages. * Contains the common methods for handling identify request messages. - * @param The type of identify request message to handle. + * + * @param The type of identify request message to handle. */ public abstract class IdentifyRequestHandler extends PillarMessageHandler { /** - * Constructor. * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected IdentifyRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -52,16 +52,18 @@ public void processRequest(T request, MessageContext requestContext) /** * Validate both that the given request it is possible to perform and that it is allowed. - * @param request The request to validate. + * + * @param request The request to validate. * @param requestContext The context for the request. * @throws RequestHandlerException If something in the request is inconsistent with the possibilities of the pillar. */ protected abstract void validateRequest(T request, MessageContext requestContext) throws RequestHandlerException; - + /** * Sends a identification response. - * @param request The request to respond to. + * + * @param request The request to respond to. * @param requestContext The context for the request. * @throws RequestHandlerException If the positive response could not be created. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PerformRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PerformRequestHandler.java index 4898c9b38..0f3118b78 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PerformRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PerformRequestHandler.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -30,14 +30,14 @@ /** * Abstract class for the methods for handing the perform request messages. * Contains the common methods for handling perform request messages. - * @param The type of perform request message to handle. + * + * @param The type of perform request message to handle. */ public abstract class PerformRequestHandler extends PillarMessageHandler { /** - * Constructor. * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected PerformRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -53,25 +53,28 @@ public void processRequest(T request, MessageContext requestContext) /** * Validate both that the given request it is possible to perform and that it is allowed. - * @param request The request to validate. + * + * @param request The request to validate. * @param requestContext The context for the request. * @throws RequestHandlerException If something in the request is inconsistent with the possibilities of the pillar. */ protected abstract void validateRequest(T request, MessageContext requestContext) throws RequestHandlerException; - + /** * Sends a progress response. - * @param request The request to respond to. + * + * @param request The request to respond to. * @param requestContext The context for the request. - * @throws RequestHandlerException If something data necessary for the progress response could not be extracted. + * @throws RequestHandlerException If something data necessary for the progress response could not be extracted. */ protected abstract void sendProgressResponse(T request, MessageContext requestContext) throws RequestHandlerException; - + /** * Perform the operation behind the request. - * @param request The request to perform. + * + * @param request The request to perform. * @param requestContext The context for the request. * @throws RequestHandlerException If the request is unable to be performed. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMediator.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMediator.java index 437cabfe1..c95951680 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMediator.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMediator.java @@ -8,25 +8,22 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.messagehandler; -import java.util.ArrayList; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositoryelements.ResponseInfo; import org.bitrepository.bitrepositorymessages.MessageRequest; @@ -47,23 +44,23 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + /** * This is the abstract instance for delegating the conversations for the pillar. - * It only responds to requests. It does not it self start conversations, though it might send Alarms when something + * It only responds to requests. It does not it self start conversations, though it might send Alarms when something * is not right. * All other messages than requests are considered garbage. */ public class PillarMediator extends AbstractContributorMediator { - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); protected final MessageHandlerContext context; protected final StorageModel pillarModel; /** - * Constructor. - * Sets the parameters of this mediator, and adds itself as a listener to the destinations. - * - * @param messageBus The messagebus. + * @param messageBus The message-bus. * @param context The context for the message handlers. * @param pillarModel The storage model for the pillar. */ @@ -73,7 +70,7 @@ public PillarMediator(MessageBus messageBus, MessageHandlerContext context, Stor this.pillarModel = pillarModel; } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected void handleRequest(MessageRequest request, MessageContext messageContext, RequestHandler handler) { try { @@ -94,37 +91,37 @@ protected void handleRequest(MessageRequest request, MessageContext messageConte ResponseInfo responseInfo = new ResponseInfo(); responseInfo.setResponseCode(ResponseCode.FAILURE); responseInfo.setResponseText(e.toString()); - + dispatchNegativeResponse(request, handler, responseInfo); getAlarmDispatcher().handleRuntimeExceptions(e); } } - + @SuppressWarnings("rawtypes") @Override protected RequestHandler[] createListOfHandlers() { List handlers = new ArrayList<>(); - + handlers.add(new IdentifyPillarsForGetFileRequestHandler(context, pillarModel)); handlers.add(new GetFileRequestHandler(context, pillarModel)); handlers.add(new IdentifyPillarsForGetFileIDsRequestHandler(context, pillarModel)); handlers.add(new GetFileIDsRequestHandler(context, pillarModel)); handlers.add(new IdentifyPillarsForGetChecksumsRequestHandler(context, pillarModel)); handlers.add(new GetChecksumsRequestHandler(context, pillarModel)); - + handlers.add(new IdentifyContributorsForGetStatusRequestHandler(getContext())); handlers.add(new GetStatusRequestHandler(getContext())); handlers.add(new IdentifyContributorsForGetAuditTrailsRequestHandler(getContext())); handlers.add(new GetAuditTrailsRequestHandler(getContext(), context.getAuditTrailManager())); - + handlers.add(new IdentifyPillarsForPutFileRequestHandler(context, pillarModel)); handlers.add(new PutFileRequestHandler(context, pillarModel)); handlers.add(new IdentifyPillarsForDeleteFileRequestHandler(context, pillarModel)); handlers.add(new DeleteFileRequestHandler(context, pillarModel)); handlers.add(new IdentifyPillarsForReplaceFileRequestHandler(context, pillarModel)); handlers.add(new ReplaceFileRequestHandler(context, pillarModel)); - - return handlers.toArray(new RequestHandler[handlers.size()]); + + return handlers.toArray(new RequestHandler[0]); } @Override @@ -136,7 +133,7 @@ protected PillarAlarmDispatcher getAlarmDispatcher() { return (PillarAlarmDispatcher) context.getAlarmDispatcher(); } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) private void dispatchNegativeResponse(MessageRequest request, RequestHandler handler, ResponseInfo info) { log.info("Cannot perform operation. Sending failed response. Cause: " + info.getResponseText()); MessageResponse response = handler.generateFailedResponse(request); diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMessageHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMessageHandler.java index be84e3871..1ba8e2d5b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMessageHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PillarMessageHandler.java @@ -8,16 +8,16 @@ * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -41,19 +41,14 @@ /** * Abstract level for message handling for both types of pillar. + * * @param The type of request message to handle. */ public abstract class PillarMessageHandler extends AbstractRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The response value for a positive identification.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); protected static final String RESPONSE_FOR_POSITIVE_IDENTIFICATION = "Operation acknowledged and accepted."; - - /** The context for the message handler.*/ protected final MessageHandlerContext context; - /** The file id validator for validating the file id.*/ private final FileIDValidator fileIDValidator; - /** The model for the pillar.*/ private final StorageModel pillarModel; /** @@ -73,69 +68,70 @@ protected PillarMessageHandler(MessageHandlerContext context, StorageModel fileI protected StorageModel getPillarModel() { return pillarModel; } - + /** * @return The settings for this message handler. */ protected Settings getSettings() { return context.getSettings(); } - + /** * @return The audit trail manager for this message sender. */ protected AuditTrailManager getAuditManager() { return context.getAuditTrailManager(); } - + /** * Validates that it is the correct pillar id. + * * @param pillarID The pillar id. */ protected void validatePillarId(String pillarID) { - if(!pillarID.equals(getSettings().getComponentID())) { - throw new IllegalArgumentException("The message had a wrong PillarId: " - + "Expected '" + getSettings().getComponentID() - + "' but was '" + pillarID + "'."); + if (!pillarID.equals(getSettings().getComponentID())) { + throw new IllegalArgumentException( + "The message had a wrong PillarId: " + "Expected '" + getSettings().getComponentID() + "' but was '" + pillarID + "'."); } } - + /** - * Verifies that we have a given fileID on a given collection, otherwise throws an exception. + * Verifies that we have a given fileID on a given collection, otherwise throws an exception. * If no specific FileID is given (the AllFileIDs), then it is ignored. - * @param fileIDs The FileIDs containing the fileID which we should have. + * + * @param fileIDs The FileIDs containing the fileID which we should have. * @param collectionID The collection which should contain the requested file. * @throws RequestHandlerException If a specific file is given, but we do not have it. */ protected void verifyFileIDExistence(FileIDs fileIDs, String collectionID) throws RequestHandlerException { - if(fileIDs.getFileID() == null) { + if (fileIDs.getFileID() == null) { return; } - if(!getPillarModel().hasFileID(fileIDs.getFileID(), collectionID)) { - log.warn("The following file is missing '" + fileIDs.getFileID() + "' at collection '" + collectionID - + "'."); + if (!getPillarModel().hasFileID(fileIDs.getFileID(), collectionID)) { + log.warn("The following file is missing '" + fileIDs.getFileID() + "' at collection '" + collectionID + "'."); throw new InvalidMessageException(ResponseCode.FILE_NOT_FOUND_FAILURE, "File not found."); } } - + /** * Uses the FileIDValidator to validate the format of a given file id. - * Also validates, that the file-id does not start with illegal 'path' characters (e.g. '..' or starts with a '/'). + * This validation also catches the use of illegal starting characters that could refer to unauthorized directories. + * * @param fileID The id to validate. * @throws RequestHandlerException If the id of the file was invalid. */ protected void validateFileIDFormat(String fileID) throws RequestHandlerException { ResponseInfo ri = fileIDValidator.validateFileID(fileID); - if(ri == null) { - if(fileID.contains("/..") || fileID.contains("../")) { + if (ri == null) { + if (fileID.contains("/..") || fileID.contains("../")) { ri = new ResponseInfo(); ri.setResponseCode(ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE); - ri.setResponseText("Invalid"); + ri.setResponseText("Invalid"); } } - - if(ri != null) { + + if (ri != null) { throw new InvalidMessageException(ri); } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PutFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PutFileRequestHandler.java index 5219f038b..52b2bebeb 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PutFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PutFileRequestHandler.java @@ -3,21 +3,22 @@ * bitrepository-access-client * * * $Id: PutFileRequestHandler.java 687 2012-01-09 12:56:47Z ktc $ - * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/PutFileRequestHandler.java $ + * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/main/java/org + * /bitrepository/pillar/messagehandler/PutFileRequestHandler.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -45,17 +46,16 @@ * Class for performing the PutFile operation. */ public class PutFileRequestHandler extends PerformRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - + private final Logger log = LoggerFactory.getLogger(getClass()); + /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected PutFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); } - + @Override public Class getRequestClass() { return PutFileRequest.class; @@ -65,97 +65,97 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(PutFileRequest message) { return createFinalResponse(message); } - + @Override - protected void validateRequest(PutFileRequest request, MessageContext requestContext) - throws RequestHandlerException { + protected void validateRequest(PutFileRequest request, MessageContext requestContext) throws RequestHandlerException { validateCollectionID(request); validatePillarId(request.getPillarID()); - if(request.getChecksumDataForNewFile() != null) { - getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForNewFile().getChecksumSpec(), - request.getCollectionID()); - } else if(getSettings().getRepositorySettings().getProtocolSettings().isRequireChecksumForNewFileRequests()) { - throw new IllegalOperationException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, "A checksum is required for " - + "the PutFile operation to be performed.", request.getFileID()); + if (request.getChecksumDataForNewFile() != null) { + getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForNewFile().getChecksumSpec()); + } else if (getSettings().getRepositorySettings().getProtocolSettings().isRequireChecksumForNewFileRequests()) { + throw new IllegalOperationException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, + "A checksum is required for " + "the PutFile operation to be performed.", request.getFileID()); } - - getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForNewFile(), request.getCollectionID()); + + getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForNewFile()); validateFileIDFormat(request.getFileID()); - + checkThatTheFileDoesNotAlreadyExist(request); checkSpaceForStoringNewFile(request); } @Override - protected void sendProgressResponse(PutFileRequest request, MessageContext requestContext) - throws RequestHandlerException { + protected void sendProgressResponse(PutFileRequest request, MessageContext requestContext) { PutFileProgressResponse response = createPutFileProgressResponse(request); ResponseInfo prInfo = new ResponseInfo(); prInfo.setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); - prInfo.setResponseText("Started to receive data."); + prInfo.setResponseText("Started to receive data."); response.setResponseInfo(prInfo); dispatchResponse(response, request); } @Override - protected void performOperation(PutFileRequest request, MessageContext requestContext) - throws RequestHandlerException { - log.info(MessageUtils.createMessageIdentifier(request) + " Performing PutFile for file " - + request.getFileID() + " on collection " + request.getCollectionID()); + protected void performOperation(PutFileRequest request, MessageContext requestContext) throws RequestHandlerException { + log.info(MessageUtils.createMessageIdentifier(request) + " Performing PutFile for file " + request.getFileID() + " on collection " + + request.getCollectionID()); try { retrieveFile(request); - getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), - "Add file to archive.", request.getAuditTrailInformation(), FileAction.PUT_FILE, - request.getCorrelationID(), requestContext.getCertificateFingerprint()); + getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), "Add file to archive.", + request.getAuditTrailInformation(), FileAction.PUT_FILE, request.getCorrelationID(), + requestContext.getCertificateFingerprint()); sendFinalResponse(request); } finally { getPillarModel().ensureFileNotInTmpDir(request.getFileID(), request.getCollectionID()); } } - + /** - * Validates that the file is not already within the archive. - * Otherwise an {@link InvalidMessageException} with the appropriate error code is thrown. + * Validates that the file is not already within the archive. + * * @param message The request with the filename to validate. + * @throws InvalidMessageException If the file already exists. */ - private void checkThatTheFileDoesNotAlreadyExist(PutFileRequest message) throws RequestHandlerException { - if(getPillarModel().hasFileID(message.getFileID(), message.getCollectionID())) { + private void checkThatTheFileDoesNotAlreadyExist(PutFileRequest message) throws InvalidMessageException { + if (getPillarModel().hasFileID(message.getFileID(), message.getCollectionID())) { throw new InvalidMessageException(ResponseCode.DUPLICATE_FILE_FAILURE, "We already have the file"); } } - + /** - * Validates that enough space exists is left in the archive. - * Otherwise an {@link InvalidMessageException} with the appropriate error code is thrown. - * If the no size is defined in the message, then it is not checked. + * Validates that enough space exists is left in the archive.
    + * If no size is defined in the message, then it is not checked. + * * @param message The request with the size of the file. + * @throws RequestHandlerException If there is not enough space free to store the file. */ private void checkSpaceForStoringNewFile(PutFileRequest message) throws RequestHandlerException { long fileSize; - if(message.getFileSize() == null) { + if (message.getFileSize() == null) { log.debug("No size for the file to be put."); fileSize = 0L; } else { fileSize = message.getFileSize().longValue(); } - + getPillarModel().verifyEnoughFreeSpaceLeftForFile(fileSize, message.getCollectionID()); } - + /** * Retrieves the actual data, validates it and stores it. + * * @param message The request to for the file to put. - * @throws RequestHandlerException If the retrival of the file fails. + * @throws RequestHandlerException If the retrieval of the file fails. */ private void retrieveFile(PutFileRequest message) throws RequestHandlerException { - getPillarModel().putFile(message.getCollectionID(), message.getFileID(), message.getFileAddress(), + getPillarModel().putFile(message.getCollectionID(), message.getFileID(), message.getFileAddress(), message.getChecksumDataForNewFile()); } - + /** * Method for sending the final response for the requested put operation. + * * @param message The request requesting the put operation. * @throws RequestHandlerException If the requested checksum specification is not supported. */ @@ -165,20 +165,21 @@ private void sendFinalResponse(PutFileRequest message) throws RequestHandlerExce ResponseInfo frInfo = new ResponseInfo(); frInfo.setResponseCode(ResponseCode.OPERATION_COMPLETED); response.setResponseInfo(frInfo); - - if(message.getChecksumRequestForNewFile() != null) { - response.setChecksumDataForNewFile(getPillarModel().getChecksumDataForFile(message.getFileID(), - message.getCollectionID(), message.getChecksumRequestForNewFile())); + + if (message.getChecksumRequestForNewFile() != null) { + response.setChecksumDataForNewFile(getPillarModel().getChecksumDataForFile(message.getFileID(), message.getCollectionID(), + message.getChecksumRequestForNewFile())); } else { log.debug("No checksum validation requested."); } dispatchResponse(response, message); } - - + + /** - * Creates a PutFileProgressResponse based on a PutFileRequest. + * Creates a PutFileProgressResponse based on a PutFileRequest. + * * @param request The PutFileRequest to base the progress response on. * @return The PutFileProgressResponse based on the request. */ @@ -191,10 +192,10 @@ private PutFileProgressResponse createPutFileProgressResponse(PutFileRequest req return res; } - + /** - * Creates a PutFileFinalResponse based on a PutFileRequest. - * + * Creates a PutFileFinalResponse based on a PutFileRequest. + * * @param request The PutFileRequest to base the final response message on. * @return The PutFileFinalResponse message based on the request. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/ReplaceFileRequestHandler.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/ReplaceFileRequestHandler.java index 656edb5e2..ebd415447 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/ReplaceFileRequestHandler.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/messagehandler/ReplaceFileRequestHandler.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -46,24 +46,23 @@ /** * Class for handling the ReplaceFile operation. - * In the positive scenario:
      - *
    • It starts by validating the message
    • + * In the positive scenario:
        + *
      • It starts by validating the message
      • *
      • Afterwards it sends a positive progress to tell that the new file is being downloaded <> *
      • Then the new file is downloaded to 'tempDir' <> *
      • A progress message is then send to tell that the new file is replacing the old one.<> - *
      • Then it performs the replacement of the file by deleting the old one (moving it from 'fileDir' to 'retainDir') + *
      • Then it performs the replacement of the file by deleting the old one (moving it from 'fileDir' to 'retainDir') * and then moves the new file from 'tempDir' to 'fileDir'<> *
      • Finally the complete message is send.
      • *
      * If anything goes wrong a FinalResponse is send telling about the failure. */ public class ReplaceFileRequestHandler extends PerformRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - + private final Logger log = LoggerFactory.getLogger(getClass()); + /** * @param context The context for the message handling. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ protected ReplaceFileRequestHandler(MessageHandlerContext context, StorageModel model) { super(context, model); @@ -78,20 +77,20 @@ public Class getRequestClass() { public MessageResponse generateFailedResponse(ReplaceFileRequest message) { return createFinalResponse(message); } - + @Override - protected void validateRequest(ReplaceFileRequest request, MessageContext requestContext) + protected void validateRequest(ReplaceFileRequest request, MessageContext requestContext) throws RequestHandlerException { validateCollectionID(request); validatePillarId(request.getPillarID()); validateFileIDFormat(request.getFileID()); - - if(!getPillarModel().hasFileID(request.getFileID(), request.getCollectionID())) { - throw new InvalidMessageException(ResponseCode.FILE_NOT_FOUND_FAILURE, "The file '" + request.getFileID() + + if (!getPillarModel().hasFileID(request.getFileID(), request.getCollectionID())) { + throw new InvalidMessageException(ResponseCode.FILE_NOT_FOUND_FAILURE, "The file '" + request.getFileID() + "' has been requested, but we do not have that file!"); } - getPillarModel().verifyEnoughFreeSpaceLeftForFile(request.getFileSize().longValue(), + getPillarModel().verifyEnoughFreeSpaceLeftForFile(request.getFileSize().longValue(), request.getCollectionID()); validateChecksumAlgorithms(request); @@ -99,13 +98,12 @@ protected void validateRequest(ReplaceFileRequest request, MessageContext reques } @Override - protected void sendProgressResponse(ReplaceFileRequest request, MessageContext requestContext) - throws RequestHandlerException { + protected void sendProgressResponse(ReplaceFileRequest request, MessageContext requestContext) { ReplaceFileProgressResponse response = createProgressResponse(request); String responseText = "Performing the ReplaceFileRequest for file '" + request.getFileID() + "' at '" + request.getCollectionID() + "'."; log.debug(responseText); - + ResponseInfo responseInfo = new ResponseInfo(); responseInfo.setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); responseInfo.setResponseText(responseText); @@ -115,14 +113,14 @@ protected void sendProgressResponse(ReplaceFileRequest request, MessageContext r } @Override - protected void performOperation(ReplaceFileRequest request, MessageContext requestContext) + protected void performOperation(ReplaceFileRequest request, MessageContext requestContext) throws RequestHandlerException { - log.info(MessageUtils.createMessageIdentifier(request) + " Performing ReplaceFile for file " + log.info(MessageUtils.createMessageIdentifier(request) + " Performing ReplaceFile for file " + request.getFileID() + " on collection " + request.getCollectionID()); try { ChecksumDataForFileTYPE requestedOldChecksum = calculateChecksumOnOldFile(request); replaceFile(request); - getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), + getAuditManager().addAuditEvent(request.getCollectionID(), request.getFileID(), request.getFrom(), "Replacing the file.", request.getAuditTrailInformation(), FileAction.REPLACE_FILE, request.getCorrelationID(), requestContext.getCertificateFingerprint()); @@ -132,58 +130,57 @@ protected void performOperation(ReplaceFileRequest request, MessageContext reque getPillarModel().ensureFileNotInTmpDir(request.getFileID(), request.getCollectionID()); } } - + /** * Validates that the checksum algorithms in the request are supported, and that the request contains the required * checksums for destructive and new file requests. + * * @param request The request. - * @throws RequestHandlerException If one (or more) of the algorithms are not supported, or if the required - * checksums are not given. + * @throws RequestHandlerException If one (or more) of the algorithms are not supported, or if the required + * checksums are not given. */ private void validateChecksumAlgorithms(ReplaceFileRequest request) throws RequestHandlerException { - getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile(), - request.getCollectionID()); - getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForNewFile(), request.getCollectionID()); - if(request.getChecksumDataForExistingFile() != null) { - getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForExistingFile().getChecksumSpec(), - request.getCollectionID()); - } else if(getSettings().getRepositorySettings().getProtocolSettings() + getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForExistingFile()); + getPillarModel().verifyChecksumAlgorithm(request.getChecksumRequestForNewFile()); + if (request.getChecksumDataForExistingFile() != null) { + getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForExistingFile().getChecksumSpec()); + } else if (getSettings().getRepositorySettings().getProtocolSettings() .isRequireChecksumForDestructiveRequests()) { throw new IllegalOperationException(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, "According to the " - + "contract a checksum for file to be deleted during the replacing operation is required.", + + "contract a checksum for file to be deleted during the replacing operation is required.", request.getFileID()); } - if(request.getChecksumDataForNewFile() != null) { - getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForNewFile().getChecksumSpec(), - request.getCollectionID()); - } else if(getSettings().getRepositorySettings().getProtocolSettings() + if (request.getChecksumDataForNewFile() != null) { + getPillarModel().verifyChecksumAlgorithm(request.getChecksumDataForNewFile().getChecksumSpec()); + } else if (getSettings().getRepositorySettings().getProtocolSettings() .isRequireChecksumForNewFileRequests()) { throw new IllegalOperationException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, "According to the contract a " + "checksum for new file in the replacing operation is required.", request.getFileID()); } } - + /** - * Validates the the existing file has the expected checksum. + * Validates that the existing file has the expected checksum. + * * @param request The request containing info about which file and which checksum is expected. * @throws RequestHandlerException If the file does not have the expected checksum. */ private void validateExistingChecksum(ReplaceFileRequest request) throws RequestHandlerException { ChecksumDataForFileTYPE checksumData = request.getChecksumDataForExistingFile(); - if(checksumData != null) { + if (checksumData != null) { ChecksumSpecTYPE checksumType = checksumData.getChecksumSpec(); - String calculatedChecksum = getPillarModel().getChecksumForFile(request.getFileID(), + String calculatedChecksum = getPillarModel().getChecksumForFile(request.getFileID(), request.getCollectionID(), checksumType); String requestedChecksum = Base16Utils.decodeBase16(checksumData.getChecksumValue()); - if(!calculatedChecksum.equals(requestedChecksum)) { + if (!calculatedChecksum.equals(requestedChecksum)) { // Log the different checksums, but do not send the right checksum back! log.warn("Failed to handle replace operation on file '" + request.getFileID() + "' since the request " - + "had the checksum '" + requestedChecksum + "' where our local file has the value '" + + "had the checksum '" + requestedChecksum + "' where our local file has the value '" + calculatedChecksum + "'. Sending alarm and respond failure."); String errMsg = "Requested to replace the file '" + request.getFileID() + "' with checksum '" + requestedChecksum + "', but our file had a different checksum."; - + throw new IllegalOperationException(ResponseCode.EXISTING_FILE_CHECKSUM_FAILURE, errMsg, request.getFileID()); } @@ -191,81 +188,86 @@ private void validateExistingChecksum(ReplaceFileRequest request) throws Request log.debug("No checksum for validation of the existing file before replace."); } } - + /** * Calculates the checksum for the old file. * ONLY USE BEFORE THE REPLACE OPERATION HAS BEEN PERFORMED! - * @param message The message containing the request for the checksum to be calculated, along with the - * specification about which algorithm and salt to use. + * + * @param message The message containing the request for the checksum to be calculated, along with the + * specification about which algorithm and salt to use. * @return The checksum data for the old file in the archive. - * If no checksum specification for the 'old' file has been defined, then an null is returned. + * If no checksum specification for the 'old' file has been defined, then null is returned. * @throws RequestHandlerException If the checksum of the requested type cannot be retrieved. */ - private ChecksumDataForFileTYPE calculateChecksumOnOldFile(ReplaceFileRequest message) + private ChecksumDataForFileTYPE calculateChecksumOnOldFile(ReplaceFileRequest message) throws RequestHandlerException { ChecksumSpecTYPE csType = message.getChecksumRequestForExistingFile(); - if(csType != null) { + if (csType != null) { return getPillarModel().getChecksumDataForFile(message.getFileID(), message.getCollectionID(), csType); } - + return null; } - + /** * Perform the replaceFile operation. - * - * Downloading the new file to replace the old one. + *

      + * Downloading the new file to replace the old one. * Also validates against the given checksum. Will log a warning, if no checksum for validation is in the request. + * * @param message The request containing the location of the file and the checksum of it. */ private void replaceFile(ReplaceFileRequest message) throws RequestHandlerException { log.info("Replacing the file '" + message.getFileID() + "' in the archive with the one in the " + "temporary area."); - getPillarModel().replaceFile(message.getFileID(), message.getCollectionID(), + getPillarModel().replaceFile(message.getFileID(), message.getCollectionID(), message.getFileAddress(), message.getChecksumDataForNewFile()); } /** * Calculates the checksum for the new file. * ONLY USE WHEN THE REPLACE OPERATION HAS BEEN PERFORMED! - * @param message The message containing the request for the checksum to be calculated, along with the - * specification about which algorithm and salt to use. + * + * @param message The message containing the request for the checksum to be calculated, along with the + * specification about which algorithm and salt to use. * @return The checksum data for the new file in the archive. - * If no checksum specification for the 'old' file has been defined, then an null is returned. + * If no checksum specification for the 'old' file has been defined, then null is returned. * @throws RequestHandlerException If the checksum of the requested type cannot be retrieved. */ - private ChecksumDataForFileTYPE calculateChecksumOnNewFile(ReplaceFileRequest message) + private ChecksumDataForFileTYPE calculateChecksumOnNewFile(ReplaceFileRequest message) throws RequestHandlerException { ChecksumSpecTYPE csType = message.getChecksumRequestForNewFile(); - if(csType != null) { + if (csType != null) { return getPillarModel().getChecksumDataForFile(message.getFileID(), message.getCollectionID(), csType); } - + return null; } - + /** * Sends the final response for a successful finish of the operation. - * @param request The request to base the response upon. + * + * @param request The request to base the response upon. * @param requestedOldChecksum The requested checksum for the old file, or null if no checksum for the old file. * @param requestedNewChecksum The requested checksum for the new file, or null if no checksum for the new file. */ private void sendFinalResponse(ReplaceFileRequest request, ChecksumDataForFileTYPE requestedOldChecksum, - ChecksumDataForFileTYPE requestedNewChecksum) { + ChecksumDataForFileTYPE requestedNewChecksum) { ReplaceFileFinalResponse response = createFinalResponse(request); - + ResponseInfo ri = new ResponseInfo(); ri.setResponseCode(ResponseCode.OPERATION_COMPLETED); response.setResponseInfo(ri); - + response.setChecksumDataForNewFile(requestedNewChecksum); response.setChecksumDataForExistingFile(requestedOldChecksum); dispatchResponse(response, request); } - + /** * Creates the generic ReplaceFileFinalResponse based on the request. + * * @param request The ReplaceFileRequest to base the response upon. * @return The ReplaceFileFinalResponse based on the request. */ @@ -278,9 +280,10 @@ private ReplaceFileProgressResponse createProgressResponse(ReplaceFileRequest re return res; } - + /** * Creates the generic ReplaceFileFinalResponse based on the request. + * * @param request The ReplaceFileRequest to base the response upon. * @return The ReplaceFileFinalResponse based on the request. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/package-info.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/package-info.java index 5da2e9dfe..b307dba07 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/package-info.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/package-info.java @@ -24,7 +24,7 @@ */ /** *

      - * This package implementes a reference pillar. + * This package implements a reference pillar. *

      * The class @see org.bitrepository.pillar.PillarAPI provides the basic interface for the reference pillar towards * the @see org.bitrepository.pillar.PillarMessageListener. @@ -41,7 +41,7 @@ * The actual implementation of the reference pillar is in the * org.bitrepository.pillar.referencepillar.ReferencePillar class. *

      - * Automatical creation of the response message for the reference pillar is done in the + * Automatic creation of the response message for the reference pillar is done in the * org.bitrepository.pillar.ReferencePillarMessageFactory class. *

      * The @see org.bitrepository.pillar.checksumpillar.ChecksumPillar is the implementation of the checksum pillar. diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumJob.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumJob.java index a92b3b433..971521c9c 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumJob.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumJob.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -33,28 +33,22 @@ * Workflow for recalculating the checksums of the files of a given collection. */ public class RecalculateChecksumJob implements SchedulableJob { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The id of the collection to recalculate the checksum for.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private final String collectionID; - /** The manager of the checksum and reference archive.*/ private final StorageModel model; - - /** The state of this workflow. */ private WorkflowState state = WorkflowState.NOT_RUNNING; private final JobID id; - + /** - * Constructor. * @param collectionID The id of the collection to recalculate checksum for. - * @param model The storage model for the pillar. + * @param model The storage model for the pillar. */ public RecalculateChecksumJob(String collectionID, StorageModel model) { this.collectionID = collectionID; this.model = model; id = new JobID(getClass().getSimpleName(), collectionID); } - + @Override public void start() { log.info("Recalculating old checksums for collection '" + collectionID + "'."); @@ -93,6 +87,6 @@ public void setCurrentState(WorkflowState newState) { @Override public String getHumanReadableState() { - return state.name(); + return state.name(); } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/ChecksumStorageModel.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/ChecksumStorageModel.java index 20cff68e9..81829d17d 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/ChecksumStorageModel.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/ChecksumStorageModel.java @@ -1,35 +1,29 @@ /* * #%L * Bitmagasin - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store; -import java.io.IOException; -import java.net.URL; -import java.util.Date; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -49,12 +43,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.io.IOException; +import java.net.URL; +import java.util.Date; + /** * The storage model for a pillar without a file store. */ public class ChecksumStorageModel extends StorageModel { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param cache The storage for the checksums. @@ -62,34 +60,31 @@ public class ChecksumStorageModel extends StorageModel { * @param settings The configuration to use. * @param fileExchange The file exchange. */ - public ChecksumStorageModel(ChecksumStore cache, AlarmDispatcher alarmDispatcher, Settings settings, - FileExchange fileExchange) { + public ChecksumStorageModel(ChecksumStore cache, AlarmDispatcher alarmDispatcher, Settings settings, FileExchange fileExchange) { super(null, cache, alarmDispatcher, settings, fileExchange); } - + @Override public ChecksumSpecTYPE getChecksumPillarSpec() { return defaultChecksumSpec; } @Override - public void verifyEnoughFreeSpaceLeftForFile(Long fileSize, String collectionID) throws RequestHandlerException { + public void verifyEnoughFreeSpaceLeftForFile(Long fileSize, String collectionID) { // Does not require the actual file. } @Override - public void replaceFile(String fileID, String collectionID, String fileAddress, - ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { - String calculatedChecksum = retrieveChecksumFromDownloadOrVerificationData(fileID, collectionID, fileAddress, - expectedChecksum); + public void replaceFile(String fileID, String collectionID, String fileAddress, ChecksumDataForFileTYPE expectedChecksum) + throws RequestHandlerException { + String calculatedChecksum = retrieveChecksumFromDownloadOrVerificationData(fileID, collectionID, fileAddress, expectedChecksum); cache.insertChecksumCalculation(fileID, collectionID, calculatedChecksum, new Date()); } @Override - public void putFile(String collectionID, String fileID, String fileAddress, - ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { - String calculatedChecksum = retrieveChecksumFromDownloadOrVerificationData(fileID, collectionID, fileAddress, - expectedChecksum); + public void putFile(String collectionID, String fileID, String fileAddress, ChecksumDataForFileTYPE expectedChecksum) + throws RequestHandlerException { + String calculatedChecksum = retrieveChecksumFromDownloadOrVerificationData(fileID, collectionID, fileAddress, expectedChecksum); cache.insertChecksumCalculation(fileID, collectionID, calculatedChecksum, new Date()); } @@ -104,120 +99,124 @@ protected void verifyFileToCacheConsistencyIfRequired(String fileID, String coll } @Override - protected String getNonDefaultChecksum(String fileID, String collectionID, ChecksumSpecTYPE csType) - throws RequestHandlerException { - throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "The ChecksumPillar cannot handle a " - + "non-default checksum specification '" + csType + "'.'"); + protected String getNonDefaultChecksum(String fileID, String collectionID, ChecksumSpecTYPE csType) throws RequestHandlerException { + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, + "The ChecksumPillar cannot handle a " + "non-default checksum specification '" + csType + "'.'"); } @Override - public FileInfo getFileInfoForActualFile(String fileID, String collectionID) - throws RequestHandlerException { - throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "This is a checksum pillar and it does " - + "not have the actual file. Only it's checksum."); + public FileInfo getFileInfoForActualFile(String fileID, String collectionID) throws RequestHandlerException { + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, + "This is a checksum pillar and it does " + "not have the actual file. Only it's checksum."); } @Override - public ExtractedFileIDsResultSet getFileIDsResultSet(String fileID, XMLGregorianCalendar minTimestamp, - XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID) { + public ExtractedFileIDsResultSet getFileIDsResultSet(String fileID, XMLGregorianCalendar minTimestamp, + XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID) { return cache.getFileIDs(minTimestamp, maxTimestamp, maxResults, fileID, collectionID); } @Override - protected ExtractedChecksumResultSet getNonDefaultChecksumResultSet(Long maxResults, String collectionID, - ChecksumSpecTYPE csSpec) throws RequestHandlerException { - throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "This is a checksum pillar and it does " - + "not have the actual file. Only it's checksum."); + protected ExtractedChecksumResultSet getNonDefaultChecksumResultSet(Long maxResults, String collectionID, ChecksumSpecTYPE csSpec) + throws RequestHandlerException { + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, + "This is a checksum pillar and it does " + "not have the actual file. Only it's checksum."); } @Override public void verifyFileExists(String fileID, String collectionID) throws RequestHandlerException { - throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "This is a checksum pillar and it does " - + "not have the actual file. Only it's checksum."); + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, + "This is a checksum pillar and it does " + "not have the actual file. Only it's checksum."); } - + /** * Retrieves the checksum either by downloading the file from the file-address and calculating the checksum, or * by extracting it from the verification data. * Strategy is decided by the settings for this ChecksumPillar. - * @param fileID The ID of the file. - * @param collectionID The ID of the collection. - * @param fileAddress The address where the file can be download from, if necessary. - * @param expectedChecksum The expected results for calculation the checksum of the file. The checksum can be - * extracted from here instead. + * + * @param fileID The ID of the file. + * @param collectionID The ID of the collection. + * @param fileAddress The address where the file can be downloaded from, if necessary. + * @param expectedChecksum The expected results for calculation the checksum of the file. The checksum can be + * extracted from here instead. * @return The checksum. * @throws RequestHandlerException If something goes wrong with extracting the checksum, e.g. it is missing from - * the 'expectedChecksum' part, it is not possible to download, or the downloaded file does not have the expected - * checksum. + * the 'expectedChecksum' part, it is not possible to download, or the downloaded file does not have + * the expected + * checksum. */ - private String retrieveChecksumFromDownloadOrVerificationData(String fileID, String collectionID, - String fileAddress, ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { - switch(getChecksumPillarFileDownload()) { - case ALWAYS_DOWNLOAD: - return downloadFileAndCalculateChecksum(fileID, collectionID, fileAddress, expectedChecksum); - case NEVER_DOWNLOAD: - return extractChecksum(expectedChecksum); - default: - if(expectedChecksum != null) { + private String retrieveChecksumFromDownloadOrVerificationData(String fileID, String collectionID, String fileAddress, + ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { + switch (getChecksumPillarFileDownload()) { + case ALWAYS_DOWNLOAD: + return downloadFileAndCalculateChecksum(fileID, collectionID, fileAddress, expectedChecksum); + case NEVER_DOWNLOAD: return extractChecksum(expectedChecksum); - } else { - return downloadFileAndCalculateChecksum(fileID, collectionID, fileAddress, null); - } + default: + if (expectedChecksum != null) { + return extractChecksum(expectedChecksum); + } else { + return downloadFileAndCalculateChecksum(fileID, collectionID, fileAddress, null); + } } } /** * Retrieves the ChecksumPillarFileDownload from settings. If not set, then the default value is * 'DOWNLOAD_WHEN_MISSING_FROM_MESSAGE'. + * * @return Whether the ChecksumPillar should download the files regarding PutFileRequests. */ protected ChecksumPillarFileDownload getChecksumPillarFileDownload() { - if(settings.getReferenceSettings().getPillarSettings().getChecksumPillarFileDownload() - == null) { + if (settings.getReferenceSettings().getPillarSettings().getChecksumPillarFileDownload() == null) { return ChecksumPillarFileDownload.DOWNLOAD_WHEN_MISSING_FROM_MESSAGE; } else { return settings.getReferenceSettings().getPillarSettings().getChecksumPillarFileDownload(); } - } - + } + /** - * Extracts the checksum from ChecksumDataForFileTYPE. + * Extracts the checksum from ChecksumDataForFileTYPE. + * * @param checksumData The message to extract the checksum from. * @return The checksum from the message. * @throws RequestHandlerException If the checksum data does not contain the checksum. */ - private String extractChecksum(ChecksumDataForFileTYPE checksumData) - throws RequestHandlerException { - if(checksumData != null) { + private String extractChecksum(ChecksumDataForFileTYPE checksumData) throws RequestHandlerException { + if (checksumData != null) { return Base16Utils.decodeBase16(checksumData.getChecksumValue()); } else { - throw new InvalidMessageException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, "The checksum should have been " - + "provided with the message"); + throw new InvalidMessageException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, + "The checksum should have been " + "provided with the message"); } } /** * Retrieves the actual data, validates it (if possible). - * @param message The request to for the file to put. + * + * @param fileID The ID of the file. + * @param collectionID The collection ID in where the file is located. + * @param fileAddress The address where the file can be found at. * @return The checksum of the retrieved file. * @throws RequestHandlerException If the operation fails. */ - private String downloadFileAndCalculateChecksum(String fileID, String collectionID, String fileAddress, - ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { + private String downloadFileAndCalculateChecksum(String fileID, String collectionID, String fileAddress, + ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { String calculatedChecksum = calculateChecksumForFileAtURL(fileAddress); - if(!validChecksum(calculatedChecksum, expectedChecksum)) { + if (!validChecksum(calculatedChecksum, expectedChecksum)) { String givenChecksum = Base16Utils.decodeBase16(expectedChecksum.getChecksumValue()); - log.error("Wrong checksum for file '" + fileID + "' at '" + collectionID + "'! Expected: [" - + givenChecksum + "], but calculated: [" + calculatedChecksum + "]"); - throw new IllegalOperationException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, "Expected checksums '" - + givenChecksum + "' but the checksum was '" + calculatedChecksum + "'.", fileID); + log.error("Wrong checksum for file '" + fileID + "' at '" + collectionID + "'! Expected: [" + givenChecksum + + "], but calculated: [" + calculatedChecksum + "]"); + throw new IllegalOperationException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, + "Expected checksums '" + givenChecksum + "' but the checksum was '" + calculatedChecksum + "'.", fileID); } return calculatedChecksum; } - + /** * Calculates the checksum for a file at a given URL. + * * @param fileAddress The URL for the file. * @return The checksum for the file. * @throws RequestHandlerException If data for the file could not be retrieved. @@ -226,28 +225,26 @@ private String calculateChecksumForFileAtURL(String fileAddress) throws RequestH log.debug("Retrieving the data from URL: '" + fileAddress + "'"); try { - return ChecksumUtils.generateChecksum(fileExchange.getFile(new URL(fileAddress)), - defaultChecksumSpec); + return ChecksumUtils.generateChecksum(fileExchange.getFile(new URL(fileAddress)), defaultChecksumSpec); } catch (IOException e) { String errMsg = "Could not retrieve the file from '" + fileAddress + "'"; log.error(errMsg, e); throw new InvalidMessageException(ResponseCode.FILE_TRANSFER_FAILURE, errMsg, null); } } - + /** * Checks whether a calculated checksum is identical to a given checksum. + * * @param calculatedChecksum The calculated checksum. - * @param expectedChecksum The expected checksum, may be null (will give a 'true' answer). + * @param expectedChecksum The expected checksum, may be null (will give a 'true' answer). * @return Whether the calculated checksum is the same as the expected one (or true, if nothing is expected). */ private boolean validChecksum(String calculatedChecksum, ChecksumDataForFileTYPE expectedChecksum) { - if(expectedChecksum != null) { + if (expectedChecksum != null) { String givenChecksum = Base16Utils.decodeBase16(expectedChecksum.getChecksumValue()); - if(!calculatedChecksum.equals(givenChecksum)) { - return false; - } - } + return calculatedChecksum.equals(givenChecksum); + } return true; } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/FileStorageModel.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/FileStorageModel.java index 033782e7d..fe552c76b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/FileStorageModel.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/FileStorageModel.java @@ -1,37 +1,29 @@ /* * #%L - * Bitmagasin - * + * Bitmagasin + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store; -import java.io.IOException; -import java.net.URL; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentSkipListMap; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.Alarm; import org.bitrepository.bitrepositoryelements.AlarmCode; import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; @@ -56,11 +48,18 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.io.IOException; +import java.net.URL; +import java.util.Date; +import java.util.Map; +import java.util.concurrent.ConcurrentSkipListMap; + /** * The storage model for a pillar with a file store, where it can store its actual files. */ public class FileStorageModel extends StorageModel { - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); /** * @param archives The file archives. @@ -70,7 +69,7 @@ public class FileStorageModel extends StorageModel { * @param fileExchange The file exchange. */ public FileStorageModel(FileStore archives, ChecksumStore cache, AlarmDispatcher alarmDispatcher, - Settings settings, FileExchange fileExchange) { + Settings settings, FileExchange fileExchange) { super(archives, cache, alarmDispatcher, settings, fileExchange); log.info("Instantiating the FileStorageModel: " + getPillarID()); } @@ -79,7 +78,7 @@ public FileStorageModel(FileStore archives, ChecksumStore cache, AlarmDispatcher public void verifyFileToCacheConsistencyOfAllDataIfRequired( String collectionID) { Boolean verify = settings.getReferenceSettings().getPillarSettings().isVerifyDataConsistencyOnMessage(); - if(verify != null && verify) { + if (verify != null && verify) { verifyFileToCacheConsistencyOfAllData(collectionID); } } @@ -87,7 +86,7 @@ public void verifyFileToCacheConsistencyOfAllDataIfRequired( @Override protected void verifyFileToCacheConsistencyIfRequired(String fileID, String collectionID) { Boolean verify = settings.getReferenceSettings().getPillarSettings().isVerifyDataConsistencyOnMessage(); - if(verify != null && verify) { + if (verify != null && verify) { recalculateChecksum(fileID, collectionID); } } @@ -105,23 +104,23 @@ public FileInfo getFileInfoForActualFile(String fileID, String collectionID) { @Override public ExtractedFileIDsResultSet getFileIDsResultSet(String fileID, XMLGregorianCalendar minTimestamp, - XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID) { + XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID) { Long minTime = null; - if(minTimestamp != null) { + if (minTimestamp != null) { minTime = CalendarUtils.convertFromXMLGregorianCalendar(minTimestamp).getTime(); } Long maxTime = null; - if(maxTimestamp != null) { + if (maxTimestamp != null) { maxTime = CalendarUtils.convertFromXMLGregorianCalendar(maxTimestamp).getTime(); } - if(fileID == null) { + if (fileID == null) { return getFileIds(minTime, maxTime, maxResults, collectionID); } ExtractedFileIDsResultSet res = new ExtractedFileIDsResultSet(); FileInfo entry = fileArchive.getFileInfo(fileID, collectionID); - if((minTime == null || minTime <= entry.getLastModifiedDate()) && + if ((minTime == null || minTime <= entry.getLastModifiedDate()) && (maxTime == null || maxTime >= entry.getLastModifiedDate())) { res.insertFileInfo(entry); } @@ -131,11 +130,11 @@ public ExtractedFileIDsResultSet getFileIDsResultSet(String fileID, XMLGregorian @Override public void verifyEnoughFreeSpaceLeftForFile(Long fileSize, - String collectionID) throws RequestHandlerException { - long useableSizeLeft = fileArchive.sizeLeftInArchive(collectionID) + String collectionID) throws RequestHandlerException { + long useableSizeLeft = fileArchive.sizeLeftInArchive(collectionID) - settings.getReferenceSettings().getPillarSettings().getMinimumSizeLeft(); - if(useableSizeLeft < fileSize) { + if (useableSizeLeft < fileSize) { throw new IdentifyContributorException(ResponseCode.FAILURE, "Not enough space left in this pillar. " + "Requires '" + fileSize + "' but has only '" + useableSizeLeft + "'"); } @@ -147,8 +146,8 @@ protected ExtractedChecksumResultSet getNonDefaultChecksumResultSet( ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); long i = 0; - for(String fileID : cache.getAllFileIDs(collectionID)) { - if(maxResults != null && i > maxResults) { + for (String fileID : cache.getAllFileIDs(collectionID)) { + if (maxResults != null && i > maxResults) { break; } i++; @@ -163,8 +162,8 @@ protected ExtractedChecksumResultSet getNonDefaultChecksumResultSet( @Override public void verifyFileExists(String fileID, String collectionID) throws RequestHandlerException { - if(!hasFileID(fileID, collectionID)) { - log.warn("The file '" + fileID + "' has been requested, but we do not have that file in collection '" + if (!hasFileID(fileID, collectionID)) { + log.warn("The file '" + fileID + "' has been requested, but we do not have that file in collection '" + collectionID + "'!"); throw new InvalidMessageException(ResponseCode.FILE_NOT_FOUND_FAILURE, "File not found."); } @@ -178,7 +177,7 @@ public ChecksumSpecTYPE getChecksumPillarSpec() { @Override public void putFile(String collectionID, String fileID, String fileAddress, - ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { + ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { transferFileToTmp(fileID, collectionID, fileAddress); verifyFileInTmp(fileID, collectionID, expectedChecksum); fileArchive.moveToArchive(fileID, collectionID); @@ -187,7 +186,7 @@ public void putFile(String collectionID, String fileID, String fileAddress, @Override public void replaceFile(String fileID, String collectionID, String fileAddress, - ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { + ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { transferFileToTmp(fileID, collectionID, fileAddress); verifyFileInTmp(fileID, collectionID, expectedChecksum); fileArchive.replaceFile(fileID, collectionID); @@ -196,7 +195,8 @@ public void replaceFile(String fileID, String collectionID, String fileAddress, /** * Recalculates the checksum of a given file based on the default checksum specification. - * @param fileID The id of the file to recalculate its default checksum for. + * + * @param fileID The id of the file to recalculate its default checksum for. * @param collectionID The id of the collection of the file. */ protected void recalculateChecksum(String fileID, String collectionID) { @@ -208,9 +208,10 @@ protected void recalculateChecksum(String fileID, String collectionID) { /** * Calculates the checksum of a file within the tmpDir. - * @param fileID The id of the file to calculate the checksum for. + * + * @param fileID The id of the file to calculate the checksum for. * @param collectionID The id of the collection of the file. - * @param csType The specification for the type of checksum to calculate. + * @param csType The specification for the type of checksum to calculate. * @return The checksum of the given type for the file with the given id. */ private String getChecksumForTempFile(String fileID, String collectionID, ChecksumSpecTYPE csType) { @@ -220,21 +221,22 @@ private String getChecksumForTempFile(String fileID, String collectionID, Checks /** * TODO this should be in the database instead. - * @param minTime The minimum date for the timestamp of the extracted file ids entries. - * @param maxTime The maximum date for the timestamp of the extracted file ids entries. + * + * @param minTime The minimum date for the timestamp of the extracted file ids entries. + * @param maxTime The maximum date for the timestamp of the extracted file ids entries. * @param maxNumberOfResults The maximum number of results. - * @param collectionID The id of the collection. + * @param collectionID The id of the collection. * @return The requested file ids. */ - private ExtractedFileIDsResultSet getFileIds(Long minTime, Long maxTime, Long maxNumberOfResults, - String collectionID) { + private ExtractedFileIDsResultSet getFileIds(Long minTime, Long maxTime, Long maxNumberOfResults, + String collectionID) { ExtractedFileIDsResultSet res = new ExtractedFileIDsResultSet(); // Map between lastModifiedDate and fileInfo. ConcurrentSkipListMap sortedDateFileIDMap = new ConcurrentSkipListMap<>(); - for(String fileID : fileArchive.getAllFileIds(collectionID)) { + for (String fileID : fileArchive.getAllFileIds(collectionID)) { FileInfo fi = fileArchive.getFileInfo(fileID, collectionID); - if((minTime == null || minTime <= fi.getLastModifiedDate()) && + if ((minTime == null || minTime <= fi.getLastModifiedDate()) && (maxTime == null || maxTime >= fi.getLastModifiedDate())) { sortedDateFileIDMap.put(fi.getLastModifiedDate(), fi); } @@ -242,13 +244,13 @@ private ExtractedFileIDsResultSet getFileIds(Long minTime, Long maxTime, Long ma int i = 0; Map.Entry entry; - while((entry = sortedDateFileIDMap.pollFirstEntry()) != null && + while ((entry = sortedDateFileIDMap.pollFirstEntry()) != null && (maxNumberOfResults == null || i < maxNumberOfResults)) { res.insertFileInfo(entry.getValue()); i++; } - if(maxNumberOfResults != null && i >= maxNumberOfResults) { + if (maxNumberOfResults != null && i >= maxNumberOfResults) { res.reportMoreEntriesFound(); } @@ -257,18 +259,18 @@ private ExtractedFileIDsResultSet getFileIds(Long minTime, Long maxTime, Long ma @Override public void verifyFileToCacheConsistencyOfAllData(String collectionID) { - for(String fileID : cache.getAllFileIDs(collectionID)) { + for (String fileID : cache.getAllFileIDs(collectionID)) { verifyCacheToArchiveConsistencyForFile(fileID, collectionID); } - for(String fileID : fileArchive.getAllFileIds(collectionID)) { + for (String fileID : fileArchive.getAllFileIds(collectionID)) { verifyArchiveToCacheConsistencyForFile(fileID, collectionID); } long maxAgeForChecksums = settings.getReferenceSettings().getPillarSettings() .getMaxAgeForChecksums().longValue(); Date checksumDate = new Date(System.currentTimeMillis() - maxAgeForChecksums); - for(String fileID : cache.getFileIDsWithOldChecksums(checksumDate, collectionID)) { + for (String fileID : cache.getFileIDsWithOldChecksums(checksumDate, collectionID)) { recalculateChecksum(fileID, collectionID); } // TODO: validate the 'last modified' timestamp ? @@ -277,11 +279,12 @@ public void verifyFileToCacheConsistencyOfAllData(String collectionID) { /** * Ensures that a file id in the cache is also in the archive. * Will send an alarm, if the file is missing, then remove it from index. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection of the file. */ private void verifyCacheToArchiveConsistencyForFile(String fileID, String collectionID) { - if(!fileArchive.hasFile(fileID, collectionID)) { + if (!fileArchive.hasFile(fileID, collectionID)) { log.warn("The file '" + fileID + "' in the ChecksumCache is no longer in the archive. " + "Dispatching an alarm, and removing it from the cache."); Alarm alarm = new Alarm(); @@ -296,13 +299,14 @@ private void verifyCacheToArchiveConsistencyForFile(String fileID, String collec } /** - * Ensures that the cache has an non-obsolete checksum for the given file. - * Also validates, that the checksum is up to date with the file. - * @param fileID The id of the file. + * Ensures that the cache has a non-obsolete checksum for the given file. + * Also validates, that the checksum is up-to-date with the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection of the file. */ private void verifyArchiveToCacheConsistencyForFile(String fileID, String collectionID) { - if(!cache.hasFile(fileID, collectionID)) { + if (!cache.hasFile(fileID, collectionID)) { log.debug("No checksum cached for file '" + fileID + "'. Calculating the checksum."); recalculateChecksum(fileID, collectionID); } @@ -310,13 +314,13 @@ private void verifyArchiveToCacheConsistencyForFile(String fileID, String collec /** * Downloads the file to temporary area. - * - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection. - * @param fileAddress The address to download the file from. + * @param fileAddress The address to download the file from. * @throws RequestHandlerException If the download fails. */ - private void transferFileToTmp(String fileID, String collectionID, String fileAddress) + private void transferFileToTmp(String fileID, String collectionID, String fileAddress) throws RequestHandlerException { log.debug("Retrieving the data to be stored from URL: '" + fileAddress + "'"); @@ -327,33 +331,33 @@ private void transferFileToTmp(String fileID, String collectionID, String fileAd String errMsg = "Could not retrieve the file from '" + fileAddress + "'"; log.error(errMsg, e); throw new InvalidMessageException(ResponseCode.FILE_TRANSFER_FAILURE, errMsg, e); - } + } } /** * Verifies that a file in temporary area has the expected checksum. - * - * @param fileID The id of the file. - * @param collectionID The id of the collection. + * + * @param fileID The id of the file. + * @param collectionID The id of the collection. * @param expectedChecksum The expected checksum for the downloaded file. - * @throws RequestHandlerException If it does not have the expected checksum. + * @throws RequestHandlerException If it does not have the expected checksum. */ - private void verifyFileInTmp(String fileID, String collectionID, ChecksumDataForFileTYPE expectedChecksum) + private void verifyFileInTmp(String fileID, String collectionID, ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException { - if(expectedChecksum != null) { - String calculatedChecksum = getChecksumForTempFile(fileID, collectionID, + if (expectedChecksum != null) { + String calculatedChecksum = getChecksumForTempFile(fileID, collectionID, expectedChecksum.getChecksumSpec()); String expectedChecksumValue = Base16Utils.decodeBase16(expectedChecksum.getChecksumValue()); - log.debug("Validating newly downloaded file, '" + fileID + "', against expected checksum '" + log.debug("Validating newly downloaded file, '" + fileID + "', against expected checksum '" + expectedChecksumValue + "'."); - if(!calculatedChecksum.equals(expectedChecksumValue)) { - log.warn("Wrong checksum! Expected: [" + expectedChecksumValue + if (!calculatedChecksum.equals(expectedChecksumValue)) { + log.warn("Wrong checksum! Expected: [" + expectedChecksumValue + "], but calculated: [" + calculatedChecksum + "]"); throw new IllegalOperationException(ResponseCode.NEW_FILE_CHECKSUM_FAILURE, "The downloaded file does " + "not have the expected checksum", fileID); } } else { log.debug("No checksums for validating the newly downloaded file '" + fileID + "'."); - } + } } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/StorageModel.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/StorageModel.java index 73a1dd4b6..4336ff3d2 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/StorageModel.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/StorageModel.java @@ -1,34 +1,29 @@ /* * #%L * Bitmagasin - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store; -import java.security.NoSuchAlgorithmException; -import java.util.Date; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -49,27 +44,26 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.xml.datatype.XMLGregorianCalendar; +import java.security.NoSuchAlgorithmException; +import java.util.Date; + /** * Storage model for the file data. - * Involves having the checksums in a checksum store (database), + * Involves having the checksums in a checksum store (database), * and potentially having the actual files in a file store (file system). * Handles all requests or operations regarding files. */ public abstract class StorageModel { - - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - - /** The storage of checksums.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); protected final ChecksumStore cache; - /** The file archives for the different collections. Can be null, if the pillar has no actual files - * (e.g. ChecksumPillar). */ + /** + * The file archives for the different collections. Can be null, if the pillar has no actual files + * (e.g. ChecksumPillar). + */ protected FileStore fileArchive; - /** The default checksum specification.*/ protected final ChecksumSpecTYPE defaultChecksumSpec; - /** The dispatcher of alarms.*/ protected final AlarmDispatcher alarmDispatcher; - /** The settings.*/ protected final Settings settings; protected final FileExchange fileExchange; @@ -80,8 +74,8 @@ public abstract class StorageModel { * @param settings The configuration to use. * @param fileExchange The file exchange. */ - protected StorageModel(FileStore archives, ChecksumStore cache, AlarmDispatcher alarmDispatcher, - Settings settings, FileExchange fileExchange) { + protected StorageModel(FileStore archives, ChecksumStore cache, AlarmDispatcher alarmDispatcher, Settings settings, + FileExchange fileExchange) { this.cache = cache; this.fileArchive = archives; this.alarmDispatcher = alarmDispatcher; @@ -89,9 +83,10 @@ protected StorageModel(FileStore archives, ChecksumStore cache, AlarmDispatcher this.fileExchange = fileExchange; this.defaultChecksumSpec = ChecksumUtils.getDefault(settings); } - + /** * Retrieval of the pillar id. + * * @return The id of the pillar. */ public String getPillarID() { @@ -101,38 +96,38 @@ public String getPillarID() { /** * Checks whether the pillar has an entry with the file-id for the given collection. * It will potentially verify that the actual file is consistent with the data in the cache. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection. * @return Whether the pillar has an entry for the file. */ public boolean hasFileID(String fileID, String collectionID) { - if(cache.hasFile(fileID, collectionID)) { + if (cache.hasFile(fileID, collectionID)) { verifyFileToCacheConsistencyIfRequired(fileID, collectionID); return true; - } + } return false; } /** * Retrieves the checksum for a given file at the given collection with the given checksum specification. - * If it is the default checksum specification, then the cached checksum is returned (though it might verify the + * If it is the default checksum specification, then the cached checksum is returned (though it might verify the * consistency between the actual file and the cache before). - * If it otherwise requests a non-default checksum specification, then it will be handled differently for the + * If it otherwise requests a non-default checksum specification, then it will be handled differently for the * Full ReferencePillar and the ChecksumPillar. - * The Full ReferencePillar will recalculated the default checksum for the file and updated in the database, along + * The Full ReferencePillar will re-calculated the default checksum for the file and updated in the database, along * with calculating the new checksum specification for the file which will be returned. - * - * @param fileID The id of the file whose checksum is requested. + * + * @param fileID The id of the file whose checksum is requested. * @param collectionID The id of the collection of the file. - * @param csType The type of checksum. + * @param csType The type of checksum. * @return The requested type of checksum for the given file. * @throws RequestHandlerException If a non-default checksum is requested for a checksum-pillar. */ - public String getChecksumForFile(String fileID, String collectionID, ChecksumSpecTYPE csType) - throws RequestHandlerException { - if(csType.equals(defaultChecksumSpec)) { + public String getChecksumForFile(String fileID, String collectionID, ChecksumSpecTYPE csType) throws RequestHandlerException { + if (csType.equals(defaultChecksumSpec)) { verifyFileToCacheConsistencyIfRequired(fileID, collectionID); - return cache.getChecksum(fileID, collectionID); + return cache.getChecksum(fileID, collectionID); } else { return getNonDefaultChecksum(fileID, collectionID, csType); } @@ -140,21 +135,20 @@ public String getChecksumForFile(String fileID, String collectionID, ChecksumSpe /** * Retrieves the checksum entry for a given file at the given collection with the given checksum specification. - * If it is the default checksum specification, then the entry in the case is returned (though it might verify the + * If it is the default checksum specification, then the entry in the case is returned (though it might verify the * consistency between the actual file and the cache before). - * If it otherwise requests a non-default checksum specification, then it will be handled differently for the + * If it otherwise requests a non-default checksum specification, then it will be handled differently for the * Full ReferencePillar and the ChecksumPillar. - * - * @param fileID The id of the file whose checksum is requested. + * + * @param fileID The id of the file whose checksum is requested. * @param collectionID The id of the collection of the file. - * @param csType The type of checksum. - * @return The entry for the requested type of checksum for the given file. - * @return {@link RequestHandlerException} If a non-default checksum is requested from a ChecksumPillar. - * @throws RequestHandlerException FIXME + * @param csType The type of checksum. + * @return The {@link ChecksumEntry} for the requested type of checksum for the given file. + * @throws RequestHandlerException If an error occurs when trying to compute a non-default checksum. */ public ChecksumEntry getChecksumEntryForFile(String fileID, String collectionID, ChecksumSpecTYPE csType) throws RequestHandlerException { - if(csType.equals(defaultChecksumSpec)) { + if (csType.equals(defaultChecksumSpec)) { verifyFileToCacheConsistencyIfRequired(fileID, collectionID); return cache.getEntry(fileID, collectionID); } else { @@ -165,9 +159,10 @@ public ChecksumEntry getChecksumEntryForFile(String fileID, String collectionID, /** * Retrieves the entry for a given file with a given checksumSpec in the ChecksumDataForFileTYPE format. - * @param fileID The id of the file to retrieve the data from. + * + * @param fileID The id of the file to retrieve the data from. * @param collectionID The id of the collection of the file. - * @param csType The type of checksum to calculate. + * @param csType The type of checksum to calculate. * @return The entry encapsulated in the ChecksumDataForFileTYPE data format. * @throws RequestHandlerException If an issue occurs when retrieving the checksum for the file. */ @@ -180,80 +175,85 @@ public ChecksumDataForFileTYPE getChecksumDataForFile(String fileID, String coll res.setChecksumValue(Base16Utils.encodeBase16(entry.getChecksum())); return res; } - + /** - * Ensures, that all files are up to date, and retrieves the requested entries. + * Ensures, that all files are up-to-date, and retrieves the requested entries. + * * @param minTimestamp The minimum date for the timestamp of the extracted checksum entries. * @param maxTimestamp The maximum date for the timestamp of the extracted checksum entries. - * @param maxResults The maximum number of results. + * @param maxResults The maximum number of results. * @param collectionID The id of the collection. - * @param csSpec The checksum specification. - * @return If default checksum, then the checksum entries from the store. Otherwise calculate all the requested + * @param csSpec The checksum specification. + * @return If default checksum, then the checksum entries from the store. Otherwise, calculate all the requested * checksums. * @throws RequestHandlerException If it is a non-default checksum specification, which is not supported (e.g. if - * it is a ChecksumPillar). + * it is a ChecksumPillar). */ - public ExtractedChecksumResultSet getChecksumResultSet(XMLGregorianCalendar minTimestamp, - XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID, ChecksumSpecTYPE csSpec) - throws RequestHandlerException { + public ExtractedChecksumResultSet getChecksumResultSet(XMLGregorianCalendar minTimestamp, XMLGregorianCalendar maxTimestamp, + Long maxResults, String collectionID, ChecksumSpecTYPE csSpec) + throws RequestHandlerException { verifyFileToCacheConsistencyOfAllDataIfRequired(collectionID); - if(csSpec.equals(defaultChecksumSpec)) { + if (csSpec.equals(defaultChecksumSpec)) { return cache.getChecksumResults(minTimestamp, maxTimestamp, maxResults, collectionID); } else { - log.info("Bulk-extraction of non-default checksums for spec: " + csSpec - + ", on collection " + collectionID + ", with maximum " + maxResults + " results."); + log.info( + "Bulk-extraction of non-default checksums for spec: " + csSpec + ", on collection " + collectionID + ", with maximum " + + maxResults + " results."); // We ignore minTimestamp and maxTimestamp when dealing with non-default checksums. return getNonDefaultChecksumResultSet(maxResults, collectionID, csSpec); } } - + /** * Extracts the results set for a given checksum entry. - * If it has the file, but its calculation date is not within the timestamp restrictions, then an empty - * resultset is returned. - * @param fileID The ID of the file. + * If it has the file, but its calculation date is not within the timestamp restrictions, then an empty + * result-set is returned. + * + * @param fileID The ID of the file. * @param collectionID The id of the collection. * @param minTimestamp Optional restrictions for the minimum timestamp for the checksum calculation date. * @param maxTimestamp Optional restrictions for the maximum timestamp for the checksum calculation date. - * @param csSpec The checksum specification. + * @param csSpec The checksum specification. * @return The extracted checksum result set. - * @throws RequestHandlerException If it is not possible to extract the checksum result, e.g. due to unsupported - * checksum specification. + * @throws RequestHandlerException If it is not possible to extract the checksum result, e.g. due to unsupported + * checksum specification. */ - public ExtractedChecksumResultSet getSingleChecksumResultSet(String fileID, String collectionID, - XMLGregorianCalendar minTimestamp, XMLGregorianCalendar maxTimestamp, ChecksumSpecTYPE csSpec) - throws RequestHandlerException { + public ExtractedChecksumResultSet getSingleChecksumResultSet(String fileID, String collectionID, XMLGregorianCalendar minTimestamp, + XMLGregorianCalendar maxTimestamp, ChecksumSpecTYPE csSpec) + throws RequestHandlerException { ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); ChecksumEntry entry = getChecksumEntryForFile(fileID, collectionID, csSpec); - if((minTimestamp == null || CalendarUtils.convertFromXMLGregorianCalendar(minTimestamp).getTime() - <= entry.getCalculationDate().getTime()) && (maxTimestamp == null || - CalendarUtils.convertFromXMLGregorianCalendar(maxTimestamp).getTime() - >= entry.getCalculationDate().getTime())) { + if ((minTimestamp == null || + CalendarUtils.convertFromXMLGregorianCalendar(minTimestamp).getTime() <= entry.getCalculationDate().getTime()) && + (maxTimestamp == null || + CalendarUtils.convertFromXMLGregorianCalendar(maxTimestamp).getTime() >= entry.getCalculationDate().getTime())) { res.insertChecksumEntry(entry); } return res; } - + /** * Removes the entry for the given file. * Both from the cache, and if an archive exists, then also removed/deprecated the actual file. - * @param fileID The id of the file to remove. + * + * @param fileID The id of the file to remove. * @param collectionID The id of the collection of the file. */ public void deleteFile(String fileID, String collectionID) { - if(fileArchive != null) { + if (fileArchive != null) { fileArchive.deleteFile(fileID, collectionID); } cache.deleteEntry(fileID, collectionID); } - + /** * Ensuring that the file is not in tmpDir is only relevant, if the file-archives exists. - * @param fileID The id of the file to ensure not exist in tmpDir. + * + * @param fileID The id of the file to ensure not exist in tmpDir. * @param collectionID The id of the collection */ public void ensureFileNotInTmpDir(String fileID, String collectionID) { - if(fileArchive != null) { + if (fileArchive != null) { fileArchive.ensureFileNotInTmpDir(fileID, collectionID); } } @@ -262,20 +262,18 @@ public void ensureFileNotInTmpDir(String fileID, String collectionID) { * Verifies the handling of a specific checksum algorithm. * * @param checksumSpec The checksum specification to verify. - * @param collectionID The ID for the collection. * @throws RequestHandlerException If the checksum specification is not supported. */ - public void verifyChecksumAlgorithm(ChecksumSpecTYPE checksumSpec, String collectionID) - throws RequestHandlerException{ - if(checksumSpec == null) { + public void verifyChecksumAlgorithm(ChecksumSpecTYPE checksumSpec) throws RequestHandlerException { + if (checksumSpec == null) { return; } - + // Validate against ChecksumPillar specific algorithm (if is a ChecksumPillar). - if(getChecksumPillarSpec() != null && !(getChecksumPillarSpec().equals(checksumSpec))) { - throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, "Cannot handle the checksum " - + "specification '" + checksumSpec + "'.This checksum pillar can only handle '" - + getChecksumPillarSpec() + "'"); + if (getChecksumPillarSpec() != null && !(getChecksumPillarSpec().equals(checksumSpec))) { + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_SUPPORTED, + "Cannot handle the checksum " + "specification '" + checksumSpec + "'.This checksum pillar can only handle '" + + getChecksumPillarSpec() + "'"); } try { @@ -288,16 +286,16 @@ public void verifyChecksumAlgorithm(ChecksumSpecTYPE checksumSpec, String collec /** * Retrieves the ChecksumEntry for the given file in the given collection, where the checksum is calculated with the * non-default checksum specification. - * - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection. - * @param csType The non-defaults checksum specification. + * @param csType The non-defaults checksum specification. * @return The requested checksum entry. - * @throws RequestHandlerException If the checksum specification cannot be handled (e.g. if this is a - * ChecksumPillar). + * @throws RequestHandlerException If the checksum specification cannot be handled (e.g. if this is a + * ChecksumPillar). */ - protected ChecksumEntry retrieveNonDefaultChecksumEntry(String fileID, String collectionID, - ChecksumSpecTYPE csType) throws RequestHandlerException { + protected ChecksumEntry retrieveNonDefaultChecksumEntry(String fileID, String collectionID, ChecksumSpecTYPE csType) + throws RequestHandlerException { String checksum = getNonDefaultChecksum(fileID, collectionID, csType); return new ChecksumEntry(fileID, checksum, new Date()); } @@ -305,56 +303,61 @@ protected ChecksumEntry retrieveNonDefaultChecksumEntry(String fileID, String co /** * Retrieves the checksum specification, if it is a ChecksumPillar. * A Full ReferencePillar must return null here. + * * @return The checksum specification if it is a ChecksumPillar, otherwise it returns null. */ public abstract ChecksumSpecTYPE getChecksumPillarSpec(); /** * Verifies that there is enough space left for the given collection for a file with the given fileSize. - * @param fileSize The size for the file to have enough space left for. + * + * @param fileSize The size for the file to have enough space left for. * @param collectionID The id of the collection. * @throws RequestHandlerException If it is not possible to store a file with the given size within the - * archive of the given collection. + * archive of the given collection. */ - public abstract void verifyEnoughFreeSpaceLeftForFile(Long fileSize, String collectionID) - throws RequestHandlerException; + public abstract void verifyEnoughFreeSpaceLeftForFile(Long fileSize, String collectionID) throws RequestHandlerException; /** * Handles the ReplaceFile operation. - * @param fileID The id of the file. - * @param collectionID The id of the collection. - * @param fileAddress The address to retrieve the file from. + * + * @param fileID The id of the file. + * @param collectionID The id of the collection. + * @param fileAddress The address to retrieve the file from. * @param validationChecksum The expected checksum for the file (validate when it has been downloaded). * @throws RequestHandlerException If something goes wrong, e.g. the downloaded file does not have the expected - * checksum. + * checksum. */ - public abstract void replaceFile(String fileID, String collectionID, String fileAddress, - ChecksumDataForFileTYPE validationChecksum) throws RequestHandlerException; - + public abstract void replaceFile(String fileID, String collectionID, String fileAddress, ChecksumDataForFileTYPE validationChecksum) + throws RequestHandlerException; + /** * Handles the PutFile operation. - * @param fileID The id of the file. - * @param collectionID The id of the collection. - * @param fileAddress The address to retrieve the file from. + * + * @param fileID The id of the file. + * @param collectionID The id of the collection. + * @param fileAddress The address to retrieve the file from. * @param expectedChecksum The expected checksum for the file (validate when it has been downloaded). * @throws RequestHandlerException If something goes wrong, e.g. the downloaded file does not have the expected - * checksum. + * checksum. */ - public abstract void putFile(String collectionID, String fileID, String fileAddress, - ChecksumDataForFileTYPE expectedChecksum) throws RequestHandlerException; + public abstract void putFile(String collectionID, String fileID, String fileAddress, ChecksumDataForFileTYPE expectedChecksum) + throws RequestHandlerException; /** - * Verify the consistency between all the data in the file archive and in the cache, if it is required by the + * Verify the consistency between all the data in the file archive and in the cache, if it is required by the * settings. * This will not be performed by ChecksumPillars, since they do not have file archive. + * * @param collectionID The id of the collection to verify the consistency for. */ public abstract void verifyFileToCacheConsistencyOfAllDataIfRequired(String collectionID); - + /** * Verify the consistency for a given file in the file archive and in the cache, if it is required by the settings. * This will not be performed by ChecksumPillars, since they do not have file archive. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection to verify the consistency for. */ protected abstract void verifyFileToCacheConsistencyIfRequired(String fileID, String collectionID); @@ -362,63 +365,68 @@ public abstract void putFile(String collectionID, String fileID, String fileAddr /** * Validates that all files in the cache is also in the archive, and that all files in the archive * is also in the cache. + * * @param collectionID The id of the collection where the data should be ensured. */ public abstract void verifyFileToCacheConsistencyOfAllData(String collectionID); /** - * Retrieves the non-default checksum for a file, thus calculating the checksum of the file with the new + * Retrieves the non-default checksum for a file, thus calculating the checksum of the file with the new * checksum specification. * It will also recalculate the default checksum and update the cache with it. * A ChecksumPillar will throw an exception, since it does not have the actual files to calculate checksums with. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection. - * @param csType The checksum specification to calculate the checksum with. + * @param csType The checksum specification to calculate the checksum with. * @return The checksum of the file calculated with the given checksum specification. * @throws RequestHandlerException If it is a ChecksumPillar. */ protected abstract String getNonDefaultChecksum(String fileID, String collectionID, ChecksumSpecTYPE csType) throws RequestHandlerException; - + /** * Retrieves the FileInfo for the actual file. * Will throw an exception for the ChecksumPillar. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection. * @return The fileInfo for the file. * @throws RequestHandlerException If it is a ChecksumPillar. */ - public abstract FileInfo getFileInfoForActualFile(String fileID, String collectionID) - throws RequestHandlerException; - + public abstract FileInfo getFileInfoForActualFile(String fileID, String collectionID) throws RequestHandlerException; + /** * Extracts a set of file ids according to the given restrictions. - * @param fileID The id of the file (thus only the id of a specific file). + * + * @param fileID The id of the file (thus only the id of a specific file). * @param minTimestamp The minimum date for the LastModifiedDate of the files. * @param maxTimestamp The maximum date for the LastModifiedDate of the files. - * @param maxResults The maximum number of results. + * @param maxResults The maximum number of results. * @param collectionID The id of the collection. * @return The extracted file ids. */ - public abstract ExtractedFileIDsResultSet getFileIDsResultSet(String fileID, XMLGregorianCalendar minTimestamp, - XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID); - + public abstract ExtractedFileIDsResultSet getFileIDsResultSet(String fileID, XMLGregorianCalendar minTimestamp, + XMLGregorianCalendar maxTimestamp, Long maxResults, String collectionID); + /** * Retrieves the checksums with a non-default checksum specification for some files. - * @param maxResults The maximum number of results. + * + * @param maxResults The maximum number of results. * @param collectionID The id of the collection. - * @param csSpec The checksum specification. + * @param csSpec The checksum specification. * @return A set of checksum-results for the non-default checksum specification. * @throws RequestHandlerException If the non-default checksum specification is not supported, e.g. if it is a - * ChecksumPillar. + * ChecksumPillar. */ - protected abstract ExtractedChecksumResultSet getNonDefaultChecksumResultSet(Long maxResults, String collectionID, - ChecksumSpecTYPE csSpec) throws RequestHandlerException; + protected abstract ExtractedChecksumResultSet getNonDefaultChecksumResultSet(Long maxResults, String collectionID, + ChecksumSpecTYPE csSpec) throws RequestHandlerException; /** * Throws an exception unless the actual file exists and is available. * Thus the ChecksumPillar will always throw an exception. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection. * @throws RequestHandlerException If it is a ChecksumPillar, or if the file does not exist. */ @@ -429,7 +437,7 @@ protected abstract ExtractedChecksumResultSet getNonDefaultChecksumResultSet(Lon */ public void close() { cache.close(); - if(fileArchive != null) { + if (fileArchive != null) { fileArchive.close(); } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDAO.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDAO.java index 854879904..245cbd10a 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDAO.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDAO.java @@ -5,62 +5,57 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.common.ArgumentValidator; import org.bitrepository.service.database.DBConnector; import org.bitrepository.service.database.DatabaseManager; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.Collection; +import java.util.Date; +import java.util.List; + /** * The checksum store backed by a database. * Mediates the operations of the database to either the extractor or the ingestor. */ public class ChecksumDAO implements ChecksumStore { - /** The ingestors for the database.*/ private final ChecksumIngestor ingestor; - /** The extractor for the database.*/ private final ChecksumExtractor extractor; - /** The connector for the database.*/ private final DBConnector connector; - + /** - * Constructor. * @param databaseManager The manager for the checksum database. */ public ChecksumDAO(DatabaseManager databaseManager) { - synchronized(this) { + synchronized (this) { connector = databaseManager.getConnector(); this.ingestor = new ChecksumIngestor(connector); this.extractor = new ChecksumExtractor(connector); } } - + @Override public void insertChecksumCalculation(String fileID, String collectionID, String checksum, Date calculationDate) { ArgumentValidator.checkNotNull(fileID, "String fileID"); ArgumentValidator.checkNotNull(collectionID, "String collectionID"); - - if(extractor.hasFile(fileID, collectionID)) { + + if (extractor.hasFile(fileID, collectionID)) { ingestor.updateEntry(fileID, collectionID, checksum, calculationDate); } else { ingestor.insertNewEntry(fileID, collectionID, checksum, calculationDate); @@ -72,7 +67,7 @@ public void deleteEntry(String fileID, String collectionID) { ArgumentValidator.checkNotNull(fileID, "String fileID"); ArgumentValidator.checkNotNull(collectionID, "String collectionID"); - if(!extractor.hasFile(fileID, collectionID)) { + if (!extractor.hasFile(fileID, collectionID)) { throw new IllegalStateException("No entry for file '" + fileID + "' to delete."); } ingestor.removeEntry(fileID, collectionID); @@ -82,33 +77,33 @@ public void deleteEntry(String fileID, String collectionID) { public ChecksumEntry getEntry(String fileID, String collectionID) { ArgumentValidator.checkNotNull(fileID, "String fileID"); ArgumentValidator.checkNotNull(collectionID, "String collectionID"); - + return extractor.extractSingleEntry(fileID, collectionID); } - + @Override - public ExtractedChecksumResultSet getChecksumResults(XMLGregorianCalendar minTimeStamp, - XMLGregorianCalendar maxTimeStamp, Long maxNumberOfResults, String collectionID) { + public ExtractedChecksumResultSet getChecksumResults(XMLGregorianCalendar minTimeStamp, + XMLGregorianCalendar maxTimeStamp, Long maxNumberOfResults, String collectionID) { ArgumentValidator.checkNotNull(collectionID, "String collectionID"); return extractor.extractEntries(minTimeStamp, maxTimeStamp, maxNumberOfResults, collectionID); } - + @Override public Date getCalculationDate(String fileID, String collectionID) { ArgumentValidator.checkNotNull(fileID, "String fileID"); ArgumentValidator.checkNotNull(collectionID, "String collectionID"); Date res = extractor.extractDateForFile(fileID, collectionID); - if(res == null) { + if (res == null) { throw new IllegalStateException("No entry for file '" + fileID + "' to delete."); } return res; - + } - + @Override - public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, - Long maxNumberOfResults, String fileID, String collectionID) { + public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, + Long maxNumberOfResults, String fileID, String collectionID) { ArgumentValidator.checkNotNull(collectionID, "String collectionID"); return extractor.getFileIDs(minTimeStamp, maxTimeStamp, maxNumberOfResults, fileID, collectionID); } @@ -127,7 +122,7 @@ public String getChecksum(String fileID, String collectionID) { ArgumentValidator.checkNotNull(collectionID, "String collectionID"); String res = extractor.extractChecksumForFile(fileID, collectionID); - if(res == null) { + if (res == null) { throw new IllegalStateException("No entry for file '" + fileID + "' to delete."); } return res; @@ -145,12 +140,12 @@ public void close() { } @Override - public ExtractedChecksumResultSet getChecksumResult(XMLGregorianCalendar minTimeStamp, - XMLGregorianCalendar maxTimeStamp, String fileID, String collectionID) { - ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); - ChecksumEntry entry = extractor.extractSingleEntryWithRestrictions(minTimeStamp, maxTimeStamp, fileID, + public ExtractedChecksumResultSet getChecksumResult(XMLGregorianCalendar minTimeStamp, + XMLGregorianCalendar maxTimeStamp, String fileID, String collectionID) { + ExtractedChecksumResultSet res = new ExtractedChecksumResultSet(); + ChecksumEntry entry = extractor.extractSingleEntryWithRestrictions(minTimeStamp, maxTimeStamp, fileID, collectionID); - if(entry != null) { + if (entry != null) { res.insertChecksumEntry(entry); } return res; diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDBMigrator.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDBMigrator.java index 42bed4cbf..8826ce4f3 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDBMigrator.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDBMigrator.java @@ -5,24 +5,22 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; -import java.util.Map; - import org.bitrepository.common.settings.Settings; import org.bitrepository.service.database.DBConnector; import org.bitrepository.service.database.DatabaseMigrator; @@ -30,6 +28,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; + import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CHECKSUM_TABLE; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_COLLECTION_ID; @@ -37,59 +37,60 @@ * Migration class for the ChecksumDatabase of the ReferencePillar and ChecksumPillar. */ public class ChecksumDBMigrator extends DatabaseMigrator { - /** The log.*/ private static final Logger log = LoggerFactory.getLogger(DatabaseUtils.class); - /** The settings.*/ private final Settings settings; - /** The current version of the database. */ private final Integer currentVersion = 4; - /** The name of the update script for version 2 to 3.*/ + /** + * The name of the update script for version 2 to 3. + */ private static final String UPDATE_SCRIPT_VERSION_2_TO_3 = "sql/derby/checksumDB2to3Migration.sql"; - /** The name of the update script for version 3 to 4.*/ + /** + * The name of the update script for version 3 to 4. + */ private static final String UPDATE_SCRIPT_VERSION_3_TO_4 = "sql/derby/checksumDB3to4Migration.sql"; - + /** * @param connector The connection to the database. - * @param settings The settings. + * @param settings The settings. */ public ChecksumDBMigrator(DBConnector connector, Settings settings) { super(connector); this.settings = settings; } - + @Override public void migrate() { Map versions = getTableVersions(); - - if(!versions.containsKey(CHECKSUM_TABLE)) { - throw new IllegalStateException("The database does not contain '" + CHECKSUM_TABLE + + if (!versions.containsKey(CHECKSUM_TABLE)) { + throw new IllegalStateException("The database does not contain '" + CHECKSUM_TABLE + "' table as required."); } - if(versions.get(CHECKSUM_TABLE) == 1) { + if (versions.get(CHECKSUM_TABLE) == 1) { migrateChecksumsTableFromVersion1To2(); } - if(!versions.containsKey(CHECKSUM_TABLE) || versions.get(CHECKSUM_TABLE) < 3) { + if (!versions.containsKey(CHECKSUM_TABLE) || versions.get(CHECKSUM_TABLE) < 3) { log.warn("Migrating ChecksumDB from version 2 to 3."); migrateDerbyDatabase(UPDATE_SCRIPT_VERSION_2_TO_3); } - if(!versions.containsKey(CHECKSUM_TABLE) || versions.get(CHECKSUM_TABLE) < 4) { + if (!versions.containsKey(CHECKSUM_TABLE) || versions.get(CHECKSUM_TABLE) < 4) { log.warn("Migrating ChecksumDB from version 3 to 4."); migrateDerbyDatabase(UPDATE_SCRIPT_VERSION_3_TO_4); } } - + /** * Migrate the ChecksumTable from version 1 to 2. * Just adds the column 'collectionid', which is set to the current (or first) collection id. */ private void migrateChecksumsTableFromVersion1To2() { log.warn("Migrating the " + CHECKSUM_TABLE + " table from version 1 to 2 in the ChecksumDatabase."); - + String alterSql = "ALTER TABLE " + CHECKSUM_TABLE + " ADD COLUMN " + CS_COLLECTION_ID + " VARCHAR(255)"; - updateTable(CHECKSUM_TABLE, 2, alterSql, new Object[0]); - - String updateAfterwards = "UPDATE " + CHECKSUM_TABLE + " SET " + CS_COLLECTION_ID + " = ? WHERE " + updateTable(CHECKSUM_TABLE, 2, alterSql); + + String updateAfterwards = "UPDATE " + CHECKSUM_TABLE + " SET " + CS_COLLECTION_ID + " = ? WHERE " + CS_COLLECTION_ID + " IS NULL"; DatabaseUtils.executeStatement(connector, updateAfterwards, settings.getCollections().get(0).getID()); } @@ -97,12 +98,12 @@ private void migrateChecksumsTableFromVersion1To2() { @Override public boolean needsMigration() { Map versions = getTableVersions(); - - if(!versions.containsKey(CHECKSUM_TABLE)) { - throw new IllegalStateException("The database does not contain '" + CHECKSUM_TABLE + + if (!versions.containsKey(CHECKSUM_TABLE)) { + throw new IllegalStateException("The database does not contain '" + CHECKSUM_TABLE + "' table as required."); } - + return versions.get(CHECKSUM_TABLE) < currentVersion; } } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDatabaseManager.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDatabaseManager.java index fb94adf48..0f59498e0 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDatabaseManager.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumDatabaseManager.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -28,17 +28,16 @@ import org.bitrepository.settings.referencesettings.DatabaseSpecifics; /** - * Class to manage the connection to the Checksum database used in the reference and checksum pillars. + * Class to manage the connection to the Checksum database used in the reference and checksum pillars. */ public class ChecksumDatabaseManager extends DatabaseManager { - private final Settings settings; private DatabaseMigrator migrator = null; - + public ChecksumDatabaseManager(Settings settings) { this.settings = settings; } - + @Override protected DatabaseSpecifics getDatabaseSpecifics() { return settings.getReferenceSettings().getPillarSettings().getChecksumDatabase(); @@ -46,7 +45,7 @@ protected DatabaseSpecifics getDatabaseSpecifics() { @Override protected synchronized DatabaseMigrator getMigrator() { - if(migrator == null) { + if (migrator == null) { migrator = new ChecksumDBMigrator(connector, settings); } return migrator; diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumEntry.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumEntry.java index 301d54278..97f8597f1 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumEntry.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumEntry.java @@ -5,65 +5,61 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; -import java.util.Date; - import org.bitrepository.common.ArgumentValidator; +import java.util.Date; + /** * Container for the information about the checksum of a file. */ public class ChecksumEntry { - /** The id of the file.*/ protected final String fileID; - /** The checksum of the file.*/ protected final String checksum; - /** The calculation date for the checksum of the file.*/ protected final Date calculationDate; - + /** - * Constructor. - * @param fileID The id of the file. - * @param checksum The checksum of the file. + * @param fileID The id of the file. + * @param checksum The checksum of the file. * @param calculationDate The calculation date for the checksum of the file. */ public ChecksumEntry(String fileID, String checksum, Date calculationDate) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - + this.fileID = fileID; this.checksum = checksum; this.calculationDate = new Date(calculationDate.getTime()); } - + /** * @return The id of the file. */ public String getFileId() { return fileID; } - + /** * @return The checksum of the file. */ public String getChecksum() { return checksum; } - + /** * @return The calculation date for the checksum of the file. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumExtractor.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumExtractor.java index 8b60f470a..c0d6a15f9 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumExtractor.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumExtractor.java @@ -5,28 +5,30 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; -import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CHECKSUM_TABLE; -import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_CHECKSUM; -import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_COLLECTION_ID; -import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_DATE; -import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_FILE_ID; +import org.bitrepository.common.ArgumentValidator; +import org.bitrepository.common.utils.CalendarUtils; +import org.bitrepository.service.database.DBConnector; +import org.bitrepository.service.database.DatabaseUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import javax.xml.datatype.XMLGregorianCalendar; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -35,99 +37,94 @@ import java.util.Date; import java.util.List; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.bitrepository.common.ArgumentValidator; -import org.bitrepository.common.utils.CalendarUtils; -import org.bitrepository.service.database.DBConnector; -import org.bitrepository.service.database.DatabaseUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CHECKSUM_TABLE; +import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_CHECKSUM; +import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_COLLECTION_ID; +import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_DATE; +import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_FILE_ID; /** * Extracts data from the checksum database. */ public class ChecksumExtractor { - /** The log.*/ private final Logger log = LoggerFactory.getLogger(getClass()); - - /** The default amount of results to fetch out of the database for each call.*/ protected static final int DEFAULT_FETCH_SIZE = 100; - - /** The connector for the database.*/ private final DBConnector connector; - + /** - * Constructor. * @param connector The connector for the database. */ public ChecksumExtractor(DBConnector connector) { ArgumentValidator.checkNotNull(connector, "DBConnector connector"); - + this.connector = connector; } - + /** * Extracts the date for a given file. - * @param fileID The id of the file to extract the date for. + * + * @param fileID The id of the file to extract the date for. * @param collectionID The collection id for the file. * @return The date for the given file. */ public Date extractDateForFile(String fileID, String collectionID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - - String sql = "SELECT " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + + String sql = "SELECT " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"; Long dateInMillis = DatabaseUtils.selectFirstLongValue(connector, sql, fileID, collectionID); - if(dateInMillis == null) { + if (dateInMillis == null) { return null; } return new Date(dateInMillis); } - + /** * Extracts the checksum for a given file. - * @param fileID The id of the file to extract the checksum for. + * + * @param fileID The id of the file to extract the checksum for. * @param collectionID The collection id for the file. * @return The checksum for the given file. */ public String extractChecksumForFile(String fileID, String collectionID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - - String sql = "SELECT " + CS_CHECKSUM + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + + String sql = "SELECT " + CS_CHECKSUM + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"; return DatabaseUtils.selectStringValue(connector, sql, fileID, collectionID); } - + /** * Extracts whether a given file exists. - * @param fileID The id of the file to extract whose existence is in question. + * + * @param fileID The id of the file to extract whose existence is in question. * @param collectionID The collection id for the file. * @return Whether the given file exists. */ public boolean hasFile(String fileID, String collectionID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - String sql = "SELECT COUNT(*) FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + String sql = "SELECT COUNT(*) FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"; return DatabaseUtils.selectIntValue(connector, sql, fileID, collectionID) != 0; } - + /** * Extracts the checksum entry for a single file. - * @param fileID The id of the file whose checksum entry should be extracted. + * + * @param fileID The id of the file whose checksum entry should be extracted. * @param collectionID The collection id for the extraction. * @return The checksum entry for the file. */ public ChecksumEntry extractSingleEntry(String fileID, String collectionID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - String sql = "SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + String sql = "SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"; try (Connection conn = connector.getConnection(); PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql, fileID, collectionID)) { try (ResultSet res = ps.executeQuery()) { - if(!res.next()) { + if (!res.next()) { throw new IllegalStateException("No entry for the file '" + fileID + "'."); } return extractChecksumEntry(res); @@ -139,29 +136,30 @@ public ChecksumEntry extractSingleEntry(String fileID, String collectionID) { /** * Extracts the checksum entry for a single file, with restrictions on time interval. + * * @param minTimeStamp The minimum timestamp for the checksum calculation date. * @param maxTimeStamp The maximum timestamp for the checksum calculation date. - * @param fileID The id of the file. + * @param fileID The id of the file. * @param collectionID The id of the collection. * @return The entry for the file, or null if it is not within the restrictions. */ - public ChecksumEntry extractSingleEntryWithRestrictions(XMLGregorianCalendar minTimeStamp, - XMLGregorianCalendar maxTimeStamp, String fileID, String collectionID) { + public ChecksumEntry extractSingleEntryWithRestrictions(XMLGregorianCalendar minTimeStamp, + XMLGregorianCalendar maxTimeStamp, String fileID, String collectionID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); List args = new ArrayList<>(); StringBuilder sql = new StringBuilder(); - sql.append("SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + sql.append("SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"); args.add(fileID); args.add(collectionID); - - if(minTimeStamp != null) { + + if (minTimeStamp != null) { sql.append(" AND " + CS_DATE + " > ? "); args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp).getTime()); } - if(maxTimeStamp != null) { + if (maxTimeStamp != null) { sql.append(" AND " + CS_DATE + " <= ? "); args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp).getTime()); } @@ -170,13 +168,13 @@ public ChecksumEntry extractSingleEntryWithRestrictions(XMLGregorianCalendar min try (Connection conn = connector.getConnection(); PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray())) { try (ResultSet res = ps.executeQuery()) { - if(!res.next()) { + if (!res.next()) { log.debug("No checksum entry found for file '" + fileID + "' at collection '" + collectionID + "', with calculation date interval: [" + minTimeStamp + " , " + maxTimeStamp + "]"); return null; } return extractChecksumEntry(res); - } + } } catch (SQLException e) { throw new IllegalStateException("Cannot extract the ChecksumEntry for '" + fileID + "'", e); } @@ -192,124 +190,125 @@ public ChecksumEntry extractSingleEntryWithRestrictions(XMLGregorianCalendar min * @param collectionID The collection id for the extraction. * @return The requested collection of file ids. */ - public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, - Long maxNumberOfResults, String fileID, String collectionID) { + public ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, + Long maxNumberOfResults, String fileID, String collectionID) { List args = new ArrayList<>(); StringBuilder sql = new StringBuilder(); - sql.append("SELECT " + CS_FILE_ID + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + sql.append("SELECT " + CS_FILE_ID + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID + " = ?"); args.add(collectionID); - - if(minTimeStamp != null) { + + if (minTimeStamp != null) { sql.append(" AND " + CS_DATE + " >= ? "); args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp).getTime()); } - if(maxTimeStamp != null) { + if (maxTimeStamp != null) { sql.append(" AND " + CS_DATE + " <= ? "); args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp).getTime()); } - if(fileID != null) { + if (fileID != null) { sql.append(" AND " + CS_FILE_ID + " = ? "); args.add(fileID); } sql.append(" ORDER BY " + CS_DATE + " ASC "); - + ExtractedFileIDsResultSet results = new ExtractedFileIDsResultSet(); try (Connection conn = connector.getConnection(); - PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray())){ + PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray())) { conn.setAutoCommit(false); ps.setFetchSize(DEFAULT_FETCH_SIZE); - try (ResultSet res = ps.executeQuery()){ + try (ResultSet res = ps.executeQuery()) { int i = 0; - while(res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) { - results.insertFileID(res.getString(DatabaseConstants.CS_FILE_ID), + while (res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) { + results.insertFileID(res.getString(DatabaseConstants.CS_FILE_ID), new Date(res.getLong(DatabaseConstants.CS_DATE))); i++; } - - if(maxNumberOfResults != null && i >= maxNumberOfResults) { + + if (maxNumberOfResults != null && i >= maxNumberOfResults) { results.reportMoreEntriesFound(); } } finally { conn.setAutoCommit(true); } } catch (SQLException e) { - throw new IllegalStateException("Cannot extract the file ids with the arguments, minTimestamp = '" - + minTimeStamp + "', maxTimestamp = '"+ maxTimeStamp + "', maxNumberOfResults = '" + throw new IllegalStateException("Cannot extract the file ids with the arguments, minTimestamp = '" + + minTimeStamp + "', maxTimestamp = '" + maxTimeStamp + "', maxNumberOfResults = '" + maxNumberOfResults + "'", e); } - + return results; } - + /** * Retrieves all the file ids for a given collection id within the database. + * * @param collectionID The collection id for the extraction. * @return The list of file ids extracted from the database. */ public List extractAllFileIDs(String collectionID) { - String sql = "SELECT " + CS_FILE_ID + " FROM " + CHECKSUM_TABLE + String sql = "SELECT " + CS_FILE_ID + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID + " = ?"; return DatabaseUtils.selectStringList(connector, sql, collectionID); } - + /** * Extracts the checksum entries within the given optional limitations. - * - * @param minTimeStamp The minimum date for the timestamp of the extracted checksum entries. - * @param maxTimeStamp The maximum date for the timestamp of the extracted checksum entries. + * + * @param minTimeStamp The minimum date for the timestamp of the extracted checksum entries. + * @param maxTimeStamp The maximum date for the timestamp of the extracted checksum entries. * @param maxNumberOfResults The maximum number of results. - * @param collectionID The collection id for the extraction. + * @param collectionID The collection id for the extraction. * @return The requested collection of file ids. */ - public ExtractedChecksumResultSet extractEntries(XMLGregorianCalendar minTimeStamp, - XMLGregorianCalendar maxTimeStamp, Long maxNumberOfResults, String collectionID) { + public ExtractedChecksumResultSet extractEntries(XMLGregorianCalendar minTimeStamp, + XMLGregorianCalendar maxTimeStamp, Long maxNumberOfResults, String collectionID) { List args = new ArrayList<>(); StringBuilder sql = new StringBuilder(); - sql.append("SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + sql.append("SELECT " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID + " = ?"); args.add(collectionID); - - if(minTimeStamp != null) { + + if (minTimeStamp != null) { sql.append(" AND " + CS_DATE + " >= ? "); args.add(CalendarUtils.convertFromXMLGregorianCalendar(minTimeStamp).getTime()); } - if(maxTimeStamp != null) { + if (maxTimeStamp != null) { sql.append(" AND " + CS_DATE + " <= ? "); args.add(CalendarUtils.convertFromXMLGregorianCalendar(maxTimeStamp).getTime()); } sql.append(" ORDER BY " + CS_DATE + " ASC "); - + ExtractedChecksumResultSet results = new ExtractedChecksumResultSet(); try (Connection conn = connector.getConnection(); - PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray())){ + PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql.toString(), args.toArray())) { conn.setAutoCommit(false); ps.setFetchSize(DEFAULT_FETCH_SIZE); try (ResultSet res = ps.executeQuery()) { int i = 0; - while(res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) { + while (res.next() && (maxNumberOfResults == null || i < maxNumberOfResults)) { results.insertChecksumEntry(extractChecksumEntry(res)); i++; } - - if(maxNumberOfResults != null && i >= maxNumberOfResults) { + + if (maxNumberOfResults != null && i >= maxNumberOfResults) { results.reportMoreEntriesFound(); } } finally { conn.setAutoCommit(true); } } catch (SQLException e) { - throw new IllegalStateException("Cannot extract the checksum entries with the arguments, minTimestamp = '" - + minTimeStamp + "', maxTimestamp = '"+ maxTimeStamp + "', maxNumberOfResults = '" + throw new IllegalStateException("Cannot extract the checksum entries with the arguments, minTimestamp = '" + + minTimeStamp + "', maxTimestamp = '" + maxTimeStamp + "', maxNumberOfResults = '" + maxNumberOfResults + "'", e); } - + return results; } - + /** * Extracts the file ids of the entries where the checksum calculation date is lower than a given date. - * + * * @param maxTimeStamp The maximum date for the checksum calculation date. * @param collectionID The collection id for the extraction. * @return The requested collection of file ids. @@ -320,7 +319,7 @@ public List extractFileIDsWithMaxChecksumDate(Long maxTimeStamp, String List args = new ArrayList<>(); args.add(collectionID); args.add(maxTimeStamp); - + List results = new ArrayList<>(); String sql = "SELECT " + CS_FILE_ID + " FROM " + CHECKSUM_TABLE + " WHERE " + CS_COLLECTION_ID + " = ? AND " + CS_DATE + " <= ? " + " ORDER BY " + CS_DATE + " ASC "; @@ -329,8 +328,8 @@ public List extractFileIDsWithMaxChecksumDate(Long maxTimeStamp, String conn.setAutoCommit(false); ps.setFetchSize(DEFAULT_FETCH_SIZE); try (ResultSet res = ps.executeQuery()) { - while(res.next() ) { - if(!res.wasNull()) { + while (res.next()) { + if (!res.wasNull()) { results.add(res.getString(DatabaseConstants.CS_FILE_ID)); } } @@ -341,18 +340,18 @@ public List extractFileIDsWithMaxChecksumDate(Long maxTimeStamp, String throw new IllegalStateException("Cannot extract the checksum entries with the arguments, maxTimestamp = '" + maxTimeStamp + "'", e); } - + return results; } - + /** - * Extracts a checksum entry from a result set. + * Extracts a checksum entry from a result set. * The result set needs to have requested the elements in the right order: - * - File id. - * - Checksum. - * - Date. - * - * @param resSet The resultset from the database. + * - File id. + * - Checksum. + * - Date. + * + * @param resSet The resultSet from the database. * @return The checksum entry extracted from the result set. */ private ChecksumEntry extractChecksumEntry(ResultSet resSet) throws SQLException { diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumIngestor.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumIngestor.java index 43c599d74..3b65b4e8b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumIngestor.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumIngestor.java @@ -5,84 +5,85 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; +import org.bitrepository.common.ArgumentValidator; +import org.bitrepository.service.database.DBConnector; +import org.bitrepository.service.database.DatabaseUtils; + +import java.util.Date; + import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CHECKSUM_TABLE; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_CHECKSUM; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_COLLECTION_ID; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_DATE; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_FILE_ID; -import java.util.Date; - -import org.bitrepository.common.ArgumentValidator; -import org.bitrepository.service.database.DBConnector; -import org.bitrepository.service.database.DatabaseUtils; - /** * Ingests data to the checksum database. And also deals with the deletion of entries. */ public class ChecksumIngestor { - /** The connector for the database.*/ private final DBConnector connector; - + /** - * Constructor. * @param connector The connector for the database. */ public ChecksumIngestor(DBConnector connector) { ArgumentValidator.checkNotNull(connector, "DBConnector connector"); - + this.connector = connector; } - + /** * Inserts a new entry into the database. - * @param fileID The id of the file for the entry. + * + * @param fileID The id of the file for the entry. * @param collectionID The id of the collection of the file. - * @param checksum The checksum of the file. - * @param date The calculation timestamp for the file. + * @param checksum The checksum of the file. + * @param date The calculation timestamp for the file. */ public synchronized void insertNewEntry(String fileID, String collectionID, String checksum, Date date) { - String sql = "INSERT INTO " + CHECKSUM_TABLE + " ( " + CS_FILE_ID + " , " + String sql = "INSERT INTO " + CHECKSUM_TABLE + " ( " + CS_FILE_ID + " , " + CS_CHECKSUM + " , " + CS_DATE + " , " + CS_COLLECTION_ID + " ) VALUES ( ? , ? , ? , ? )"; DatabaseUtils.executeStatement(connector, sql, fileID, checksum, date.getTime(), collectionID); } - + /** * Updates an existing entry in the database. - * @param fileID The id of the file to update. + * + * @param fileID The id of the file to update. * @param collectionID The id of the collection of the file. - * @param checksum The new checksum for the file. - * @param date The new date for the calculation of the checksum of the file. + * @param checksum The new checksum for the file. + * @param date The new date for the calculation of the checksum of the file. */ public void updateEntry(String fileID, String collectionID, String checksum, Date date) { - String sql = "UPDATE " + CHECKSUM_TABLE + " SET " + CS_CHECKSUM + " = ? , " + CS_DATE + " = ? WHERE " + String sql = "UPDATE " + CHECKSUM_TABLE + " SET " + CS_CHECKSUM + " = ? , " + CS_DATE + " = ? WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"; DatabaseUtils.executeStatement(connector, sql, checksum, date.getTime(), fileID, collectionID); } - + /** * Removes an entry from the database. - * @param fileID The id of the file whose entry should be removed. + * + * @param fileID The id of the file whose entry should be removed. * @param collectionID The id of the collection of the file. */ public void removeEntry(String fileID, String collectionID) { - String sql = "DELETE FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + String sql = "DELETE FROM " + CHECKSUM_TABLE + " WHERE " + CS_FILE_ID + " = ? AND " + CS_COLLECTION_ID + " = ?"; DatabaseUtils.executeStatement(connector, sql, fileID, collectionID); } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumStore.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumStore.java index f1ae65881..1b117089b 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumStore.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ChecksumStore.java @@ -5,128 +5,137 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; +import javax.xml.datatype.XMLGregorianCalendar; import java.util.Collection; import java.util.Date; import java.util.List; -import javax.xml.datatype.XMLGregorianCalendar; - /** * Interface for the storage of checksums. */ public interface ChecksumStore { /** * Retrieve the calculation date for the checksum of the file. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection for the file. * @return The calculation date for the checksum of the file at the collection. */ Date getCalculationDate(String fileID, String collectionID); - + /** * Retrieve the checksum for the given file. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param collectionID The id of the collection for the file. * @return The checksum of the file. */ String getChecksum(String fileID, String collectionID); - + /** - * @param fileID The id of the file. + * @param fileID The id of the file. * @param collectionID The id of the collection for the file. * @return The entry with the checksum information about the file. */ ChecksumEntry getEntry(String fileID, String collectionID); - + /** * Retrieves the checksum result entries for the given restrictions from the store. - * @param minTimeStamp The minimum date for the timestamp of the extracted checksum entries. - * @param maxTimeStamp The maximum date for the timestamp of the extracted checksum entries. + * + * @param minTimeStamp The minimum date for the timestamp of the extracted checksum entries. + * @param maxTimeStamp The maximum date for the timestamp of the extracted checksum entries. * @param maxNumberOfResults The maximum number of results. - * @param collectionID The id of the collection for the files. + * @param collectionID The id of the collection for the files. * @return The checksum entries from the store. */ - ExtractedChecksumResultSet getChecksumResults(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, - Long maxNumberOfResults, String collectionID); + ExtractedChecksumResultSet getChecksumResults(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, + Long maxNumberOfResults, String collectionID); /** * Retrieves the checksum result entry for the given file from the store. + * * @param minTimeStamp The minimum date for the timestamp of the extracted checksum entry. * @param maxTimeStamp The maximum date for the timestamp of the extracted checksum entry. - * @param fileID The id of the file to retrieve the checksum result for. + * @param fileID The id of the file to retrieve the checksum result for. * @param collectionID The id of the collection for the file. * @return The checksum entries from the store. */ ExtractedChecksumResultSet getChecksumResult(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, - String fileID, String collectionID); + String fileID, String collectionID); /** * Inserts a checksum calculation for a given file. - * @param fileID The id of the file. - * @param collectionID The id of the collection for the file. - * @param checksum The checksum of the file. + * + * @param fileID The id of the file. + * @param collectionID The id of the collection for the file. + * @param checksum The checksum of the file. * @param calculationDate The date for the calculation of the checksum for the file. */ void insertChecksumCalculation(String fileID, String collectionID, String checksum, Date calculationDate); - + /** * Retrieval of file ids. - * @param minTimeStamp The minimum date for the timestamp of the extracted file ids. - * @param maxTimeStamp The maximum date for the timestamp of the extracted file ids. + * + * @param minTimeStamp The minimum date for the timestamp of the extracted file ids. + * @param maxTimeStamp The maximum date for the timestamp of the extracted file ids. * @param maxNumberOfResults The maximum number of results. - * @param fileID The id of the file. If null or empty string, then all files. - * @param collectionID The id of the collection for the file. + * @param fileID The id of the file. If null or empty string, then all files. + * @param collectionID The id of the collection for the file. * @return The file ids in the store within the restrictions. */ - ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, - Long maxNumberOfResults, String fileID, String collectionID); - + ExtractedFileIDsResultSet getFileIDs(XMLGregorianCalendar minTimeStamp, XMLGregorianCalendar maxTimeStamp, + Long maxNumberOfResults, String fileID, String collectionID); + /** * Retrieval of all the file ids in the store. + * * @param collectionID The id of the collection for the files. * @return The collection of file ids in the store. */ Collection getAllFileIDs(String collectionID); - + /** * Retrieval of the ids for the files where the checksum was calculated earlier than a certain date. + * * @param checksumDate The max calculation date for the checksums to retrieve. * @param collectionID The id of the collection for the files. * @return The collection of ids for the files with old checksums. */ List getFileIDsWithOldChecksums(Date checksumDate, String collectionID); - + /** * Deletes a given entry from the cache. - * @param fileID The id of the file, whose entry should be removed from the cache. + * + * @param fileID The id of the file, whose entry should be removed from the cache. * @param collectionID The id of the collection for the file. */ void deleteEntry(String fileID, String collectionID); - + /** * Tells whether a given file id can be found in the cache. - * @param fileID The id of the file to find in the cache. + * + * @param fileID The id of the file to find in the cache. * @param collectionID The id of the collection for the file. * @return Whether the file could be found. */ boolean hasFile(String fileID, String collectionID); - + /** * Closes and cleans up the ChecksumStore. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/DatabaseConstants.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/DatabaseConstants.java index 41be6db08..1989c03d7 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/DatabaseConstants.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/DatabaseConstants.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -25,21 +25,31 @@ * Container for the constants for the checksum database. */ public final class DatabaseConstants { - /** Private constructor to prevent instantiation of this constant container.*/ - private DatabaseConstants() {} - - /** The table with the checksum entries.*/ + /** + * The table with the checksum entries. + */ public static final String CHECKSUM_TABLE = "checksums"; - /** The column for the id of file.*/ + /** + * The column for the id of file. + */ public static final String CS_FILE_ID = "fileid"; - /** The column for the checksum of the file.*/ + /** + * The column for the checksum of the file. + */ public static final String CS_CHECKSUM = "checksum"; - /** The column for the date for the calculation of the checksum.*/ + /** + * The column for the date for the calculation of the checksum. + */ public static final String CS_DATE = "calculationdate"; - /** The column for the collection id for the file.*/ + /** + * The column for the collection id for the file. + */ public static final String CS_COLLECTION_ID = "collectionid"; - - /** The column for the guid of the entry.*/ + + /** + * The column for the guid of the entry. + */ public static final String CS_GUID = "guid"; - + + private DatabaseConstants() {} } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedChecksumResultSet.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedChecksumResultSet.java index 4c25340b9..247d524ff 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedChecksumResultSet.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedChecksumResultSet.java @@ -5,56 +5,53 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; -import java.util.ArrayList; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.common.utils.Base16Utils; import org.bitrepository.common.utils.CalendarUtils; +import java.util.ArrayList; +import java.util.List; + /** - * Container of the results of a checksum database exctraction. + * Container of the results of a checksum database extraction. */ public class ExtractedChecksumResultSet { - /** The list of checksum entries.*/ protected final List entries; - /** Whether more results has been found.*/ protected boolean moreEntriesReported; - - /** - * Constructor. - */ + public ExtractedChecksumResultSet() { entries = new ArrayList<>(); moreEntriesReported = false; } - + /** - * Adds an entry to this result set. + * Adds an entry to this result set. + * * @param entry The entry to add. */ public void insertChecksumEntry(ChecksumDataForChecksumSpecTYPE entry) { entries.add(entry); } - + /** - * Adds an entry to this result set. + * Adds an entry to this result set. + * * @param entry The entry to add. */ public void insertChecksumEntry(ChecksumEntry entry) { @@ -64,21 +61,21 @@ public void insertChecksumEntry(ChecksumEntry entry) { res.setFileID(entry.getFileId()); entries.add(res); } - + /** * @return A list with all the reported entries. */ public List getEntries() { return new ArrayList<>(entries); } - + /** - * Set that more entries has been found. + * Set that more entries has been found. */ public void reportMoreEntriesFound() { moreEntriesReported = true; } - + /** * @return Whether it has been reported, that more results exists. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedFileIDsResultSet.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedFileIDsResultSet.java index ca24fec7f..5cc4a9e70 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedFileIDsResultSet.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/checksumdatabase/ExtractedFileIDsResultSet.java @@ -5,74 +5,71 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.checksumdatabase; -import java.math.BigInteger; -import java.util.Date; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.FileIDsData; import org.bitrepository.bitrepositoryelements.FileIDsData.FileIDsDataItems; import org.bitrepository.bitrepositoryelements.FileIDsDataItem; import org.bitrepository.common.filestore.FileInfo; import org.bitrepository.common.utils.CalendarUtils; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigInteger; +import java.util.Date; + /** - * Container of the results of a checksum database extraction for file ids. + * Container of the results of a checksum database extraction for file ids. */ public class ExtractedFileIDsResultSet { - /** The results of the file ids extraction.*/ protected final FileIDsData results; - /** Whether more results has been found.*/ protected boolean moreEntriesReported; - - /** - * Constructor. - */ + public ExtractedFileIDsResultSet() { results = new FileIDsData(); results.setFileIDsDataItems(new FileIDsDataItems()); moreEntriesReported = false; } - + /** - * Adds a file id to this result set. - * @param fileInfo The fileinfo for the file to insert. + * Adds a file id to this result set. + * + * @param fileInfo The file-info for the file to insert. */ public void insertFileInfo(FileInfo fileInfo) { - insertFileID(fileInfo.getFileID(), BigInteger.valueOf(fileInfo.getSize()), + insertFileID(fileInfo.getFileID(), BigInteger.valueOf(fileInfo.getSize()), CalendarUtils.getFromMillis(fileInfo.getLastModifiedDate())); } - + /** * Inserts a file id with date, but without the size. * Intended for the ChecksumPillar, which cannot deliver any size. - * @param fileID The id of the file. + * + * @param fileID The id of the file. * @param lastModified The last modified timestamp. */ public void insertFileID(String fileID, Date lastModified) { insertFileID(fileID, null, CalendarUtils.getXmlGregorianCalendar(lastModified)); } - + /** - * Adds a file id to this result set. - * @param fileID The id of the file to add. - * @param size The size of the file. + * Adds a file id to this result set. + * + * @param fileID The id of the file to add. + * @param size The size of the file. * @param lastModified The last modified date for the file. */ public void insertFileID(String fileID, BigInteger size, XMLGregorianCalendar lastModified) { @@ -82,21 +79,21 @@ public void insertFileID(String fileID, BigInteger size, XMLGregorianCalendar la item.setLastModificationTime(lastModified); results.getFileIDsDataItems().getFileIDsDataItem().add(item); } - + /** * @return The data results of the extraction. */ public FileIDsData getEntries() { return results; } - + /** - * Set that more entries has been found. + * Set that more entries has been found. */ public void reportMoreEntriesFound() { moreEntriesReported = true; } - + /** * @return Whether it has been reported, that more results exists. */ diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ArchiveDirectory.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ArchiveDirectory.java index 3d9c7339d..f98d350ae 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ArchiveDirectory.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ArchiveDirectory.java @@ -5,63 +5,83 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.filearchive; +import org.bitrepository.common.ArgumentValidator; +import org.bitrepository.common.utils.FileUtils; + import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import org.bitrepository.common.ArgumentValidator; -import org.bitrepository.common.utils.FileUtils; +import java.util.Objects; /** - * Manager interface for a given archival directory, with the subdirectories 'tempDir', 'fileDir', 'folderDir' + * Manager interface for a given archival directory, with the subdirectories 'tempDir', 'fileDir', 'folderDir' * and 'retainDir'. * A new file is ingested into the 'tempDir', where it can be validated before it is moved to the actual archive. - * Depending on whether the file-id contains a directory-structure path, then it is either moved to the 'fileDir' + * Depending on whether the file-id contains a directory-structure path, then it is either moved to the 'fileDir' * or the 'folderDir'. * If a file is to be deleted, then it is moved from the 'fileDir' or 'folderDir' to the 'retainDir'. */ public class ArchiveDirectory { - /** Constant for the temporary directory name.*/ + /** + * Constant for the temporary directory name. + */ public static final String TEMPORARY_DIR = "tmpDir"; - /** Constant for the file archive name.*/ + /** + * Constant for the file archive name. + */ public static final String ARCHIVE_DIR = "fileDir"; - /** Constant for the retain directory name.*/ + /** + * Constant for the "retain" directory name. + */ public static final String RETAIN_DIR = "retainDir"; - /** The constant for the folder directory name.*/ + /** + * The constant for the folder directory name. + */ public static final String FOLDER_DIR = "folderDir"; - - /** The directory for the files. Contains three sub directories: tempDir, fileDir and retainDir.*/ - private File baseDepositDir; - /** The directory where files are being downloaded to before they are put into the filedir. */ - private File tmpDir; - /** The directory where the files are being stored.*/ + /** + * The directory for the files. Contains three subdirectories: tempDir, fileDir and retainDir. + */ + private final File baseDepositDir; + + /** + * The directory where files are being downloaded to before they are put into the fileDir. + */ + private final File tmpDir; + /** + * The directory where the files are being stored. + */ private final File fileDir; - /** The directory where the files are moved, when they are removed from the archive.*/ + /** + * The directory where the files are moved, when they are removed from the archive. + */ private final File retainDir; - /** The directory where the files where the file-id contains a directory-path are stored.*/ + /** + * The directory where the files where the file-id contains a directory-path are stored. + */ private final File folderDir; + private final Object lock = new Object(); - /** - * Constructor. Initialises the file directory. - * + /** + * Constructor. Initialises the file directory. + * * @param dirName The directory for this archive. */ public ArchiveDirectory(String dirName) { @@ -74,43 +94,46 @@ public ArchiveDirectory(String dirName) { retainDir = FileUtils.retrieveSubDirectory(baseDepositDir, RETAIN_DIR); folderDir = FileUtils.retrieveSubDirectory(baseDepositDir, FOLDER_DIR); } - + /** * Retrieves the file for the given fileID, or returns a null, if no such file exists. + * * @param fileID The id of the file to retrieve. * @return The requested file, or a null if no such file exists. */ public File retrieveFile(String fileID) { File res = getFile(fileID); - if(res.isFile()) { + if (res.isFile()) { return res; } else { return null; } } - + /** * Method for retrieving the abstract file for the given fileID, no matter whether the actual file exists or not. + * * @param fileID The id of the file to retrieve. * @return The file. */ protected File getFile(String fileID) { - if(isFolderFile(fileID)) { + if (isFolderFile(fileID)) { return new File(folderDir, fileID); } else { return new File(fileDir, fileID); } } - + /** * Checks whether the fileID contains a directory-path, and thus should be placed in the folderDir. + * * @param fileID The fileID to check. * @return Whether the fileID contains a directory-path. */ protected boolean isFolderFile(String fileID) { return fileID.contains(File.separator); } - + /** * @param fileID The file id to test whether it exists. * @return Whether the given file exists within the archive. @@ -118,53 +141,53 @@ protected boolean isFolderFile(String fileID) { public boolean hasFile(String fileID) { return getFile(fileID).isFile(); } - + /** * @return Retrieves the list of archived files. */ public List getFileIds() { List res = new ArrayList<>(); - res.addAll(Arrays.asList(fileDir.list())); + res.addAll(Arrays.asList(Objects.requireNonNull(fileDir.list()))); res.addAll(getSubFolderFileIDs(folderDir, "")); return res; } - + /** * @return The number of bytes left for the base directory. */ public Long getBytesLeft() { return baseDepositDir.getFreeSpace(); } - + /** * @param fileID The id of the file * @return A new file in the temporary directory. */ public File getFileInTempDir(String fileID) { File res = new File(tmpDir, fileID); - if(!res.exists()) { + if (!res.exists()) { throw new IllegalStateException("The file '" + fileID + "' does not exist within the tmpDir."); } return res; } - + /** * @param fileID The id of the file * @return A new file in the temporary directory. */ public File getNewFileInTempDir(String fileID) { File res = new File(tmpDir, fileID); - if(res.exists()) { + if (res.exists()) { throw new IllegalStateException("Cannot create a new file in the temporary directory."); } - if(!res.getParentFile().isDirectory()) { - synchronized(tmpDir) { + if (!res.getParentFile().isDirectory()) { + synchronized (tmpDir) { FileUtils.retrieveDirectory(res.getParent()); } } return res; } - + /** * @param fileID The id of the file. * @return Whether a given file exist in the temporary directory. @@ -172,85 +195,88 @@ public File getNewFileInTempDir(String fileID) { public boolean hasFileInTempDir(String fileID) { return new File(tmpDir, fileID).isFile(); } - + /** * Moves a file from the tmpDir to the archive dir. + * * @param fileID The id of the file to */ public void moveFromTmpToArchive(String fileID) { File tmpFile = new File(tmpDir, fileID); File archiveFile = getFile(fileID); - - if(!tmpFile.isFile()) { + + if (!tmpFile.isFile()) { throw new IllegalStateException("The file '" + fileID + "' does not exist within the tmpDir."); } - if(archiveFile.isFile()) { + if (archiveFile.isFile()) { throw new IllegalStateException("The file '" + fileID + "' does already exist within the fileDir."); } - + // Move the file to the fileDir. - synchronized(folderDir) { + synchronized (folderDir) { FileUtils.moveFile(tmpFile, archiveFile); } cleanupDirs(fileID, tmpDir); } - + /** - * The file to remove from the archive. The file is just moved from the fileDir to the retainDir. + * The file to remove from the archive. The file is just moved from the fileDir to the retainDir. + * * @param fileID The id of the file to remove from archive. */ public void removeFileFromArchive(String fileID) { File oldFile = getFile(fileID); - if(!oldFile.isFile()) { - throw new IllegalStateException("Cannot locate the file to delete '" + fileID + "' from location '" - + oldFile.getAbsolutePath() + "'!"); + if (!oldFile.isFile()) { + throw new IllegalStateException( + "Cannot locate the file to delete '" + fileID + "' from location '" + oldFile.getAbsolutePath() + "'!"); } File retainFile = new File(retainDir, fileID); - + // If a version of the file already has been retained, then it should be deprecated. - if(retainFile.exists()) { + if (retainFile.exists()) { FileUtils.deprecateFile(retainFile); } - + FileUtils.moveFile(oldFile, retainFile); cleanupDirs(fileID, folderDir); } /** * The file to remove from the temporary directory. The file is just moved from the fileDir to the retainDir. - * This should be used e.g. to clean up after a failed PutFile. + * This should be used e.g. to clean up after a failed PutFile. + * * @param fileID The id of the file to remove from tmpdir. */ public void removeFileFromTmp(String fileID) { File oldFile = new File(tmpDir, fileID); - if(!oldFile.isFile()) { + if (!oldFile.isFile()) { throw new IllegalStateException("Cannot locate the file to delete '" + oldFile.getAbsolutePath() + "'!"); } File retainFile = new File(retainDir, fileID); - + // If a version of the file already has been retained, then it should be deprecated. // If it does not exist, then it must be ensured that the parent folder exists. - if(retainFile.exists()) { + if (retainFile.exists()) { FileUtils.deprecateFile(retainFile); } - + FileUtils.moveFile(oldFile, retainFile); cleanupDirs(fileID, tmpDir); } - + /** - * Retrieves the file-ids of the files within the subdirs of the folder-dir. - * It recursive goes through the sub-directories - * @param dir The current directory. + * Retrieves the file-ids of the files within the subdirectories of the folder-dir by recursively going through them. + * + * @param dir The current directory. * @param dirPath The relative path to the current directory. Is used as prefix for the files in this folder. * @return The list of file-ids in the current folder and all the sub-folders. */ protected List getSubFolderFileIDs(File dir, String dirPath) { List res = new ArrayList<>(); - if(dir.list() != null) { - for(File f : dir.listFiles()) { + if (dir.list() != null) { + for (File f : Objects.requireNonNull(dir.listFiles())) { String path = dirPath + f.getName(); - if(f.isFile()) { + if (f.isFile()) { res.add(path); } else { res.addAll(getSubFolderFileIDs(f, path + File.separator)); @@ -259,18 +285,19 @@ protected List getSubFolderFileIDs(File dir, String dirPath) { } return res; } - + /** * Cleanup directories after use. * Only removes empty directories. - * @param fileID The ID of the file. + * + * @param fileID The ID of the file. * @param rootDir The root directory. */ protected void cleanupDirs(String fileID, File rootDir) { - if(!isFolderFile(fileID)) { + if (!isFolderFile(fileID)) { return; } - synchronized(rootDir) { + synchronized (lock) { File origFile = new File(rootDir, fileID); FileUtils.cleanupEmptyDirectories(origFile.getParentFile(), rootDir); } diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/CollectionArchiveManager.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/CollectionArchiveManager.java index 49ecd0af1..f23570f65 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/CollectionArchiveManager.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/CollectionArchiveManager.java @@ -5,22 +5,29 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.filearchive; +import org.bitrepository.common.filestore.DefaultFileInfo; +import org.bitrepository.common.filestore.FileInfo; +import org.bitrepository.common.filestore.FileStore; +import org.bitrepository.common.settings.Settings; +import org.bitrepository.common.utils.SettingsUtils; +import org.bitrepository.settings.referencesettings.CollectionDirs; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -30,71 +37,62 @@ import java.util.List; import java.util.Map; -import org.bitrepository.common.filestore.DefaultFileInfo; -import org.bitrepository.common.filestore.FileInfo; -import org.bitrepository.common.filestore.FileStore; -import org.bitrepository.common.settings.Settings; -import org.bitrepository.common.utils.SettingsUtils; -import org.bitrepository.settings.referencesettings.CollectionDirs; - /** * The CollectionArchiveManager manages the archives of the different collections for the Pillar. */ public class CollectionArchiveManager implements FileStore { - /** The mapping between the collections and their archives.*/ private final Map archives = new HashMap<>(); - + /** - * Constructor. * @param settings The settings for the repository. */ public CollectionArchiveManager(Settings settings) { initiateSpecificDirs(settings); initiateDefaultDirs(settings); } - + /** * Initiates the specified archive directories. + * * @param settings The settings. */ private void initiateSpecificDirs(Settings settings) { - for(CollectionDirs cd : settings.getReferenceSettings().getPillarSettings().getCollectionDirs()){ - if(cd.getCollectionID().isEmpty()) { - continue; - } else { + for (CollectionDirs cd : settings.getReferenceSettings().getPillarSettings().getCollectionDirs()) { + if (!cd.getCollectionID().isEmpty()) { initiateArchive(cd.getCollectionID(), cd.getFileDirs()); } - } + } } - + /** * Initiates the default archive directories. * These will only be used for the collections, which does not have a specified directory. + * * @param settings The settings. */ private void initiateDefaultDirs(Settings settings) { - for(CollectionDirs cd : settings.getReferenceSettings().getPillarSettings().getCollectionDirs()){ - if(cd.getCollectionID().isEmpty()) { - initiateArchive(SettingsUtils.getCollectionIDsForPillar(settings.getComponentID()), - cd.getFileDirs()); + for (CollectionDirs cd : settings.getReferenceSettings().getPillarSettings().getCollectionDirs()) { + if (cd.getCollectionID().isEmpty()) { + initiateArchive(SettingsUtils.getCollectionIDsForPillar(settings.getComponentID()), cd.getFileDirs()); } - } + } } - + /** * Initiates the archives for a set of collection ids and their respective directory paths. - * Only creates archives for the collection, if it does not already has one. + * Only creates archives for the collection, if it does not already have one. + * * @param collectionIDs The ids of the collections. - * @param fileDirs The paths to the directories. + * @param fileDirs The paths to the directories. */ private void initiateArchive(Collection collectionIDs, Collection fileDirs) { - for(String colId : collectionIDs) { + for (String colId : collectionIDs) { List dirs = new ArrayList<>(); - for(String dir : fileDirs) { + for (String dir : fileDirs) { dirs.add(new File(dir, colId).getPath()); } - - if(!archives.containsKey(colId)) { + + if (!archives.containsKey(colId)) { archives.put(colId, new ReferenceArchive(dirs)); } } @@ -116,8 +114,7 @@ public Collection getAllFileIds(String collectionID) { } @Override - public FileInfo downloadFileForValidation(String fileID, String collectionID, InputStream inputStream) - throws IOException { + public FileInfo downloadFileForValidation(String fileID, String collectionID, InputStream inputStream) throws IOException { return new DefaultFileInfo(getArchive(collectionID).downloadFileForValidation(fileID, inputStream)); } @@ -130,42 +127,43 @@ public void moveToArchive(String fileID, String collectionID) { public void deleteFile(String fileID, String collectionID) { getArchive(collectionID).deleteFile(fileID); } - + @Override public synchronized void replaceFile(String fileID, String collectionID) { getArchive(collectionID).replaceFile(fileID); } - + @Override public long sizeLeftInArchive(String collectionID) { return getArchive(collectionID).sizeLeftInArchive(); } - + @Override public FileInfo getFileInTmpDir(String fileID, String collectionID) { return new DefaultFileInfo(getArchive(collectionID).getFileInTmpDir(fileID)); } - + @Override public void ensureFileNotInTmpDir(String fileID, String collectionID) { getArchive(collectionID).ensureFileNotInTmpDir(fileID); } - + @Override public void close() { - for(ReferenceArchive ra : archives.values()){ + for (ReferenceArchive ra : archives.values()) { ra.close(); } } - + /** * Validates the existence of the archive before accessing it. - * If it does not exist, then an IllegalStateException is thrown. + * If it does not exist, then an IllegalStateException is thrown. + * * @param collectionID The id of the collection. * @return The archive for the collection. */ private ReferenceArchive getArchive(String collectionID) { - if(archives.containsKey(collectionID)) { + if (archives.containsKey(collectionID)) { return archives.get(collectionID); } else { throw new IllegalStateException("The collection '" + collectionID + "' has no attached archive."); diff --git a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ReferenceArchive.java b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ReferenceArchive.java index 600bd0ce4..0a3b0de65 100644 --- a/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ReferenceArchive.java +++ b/bitrepository-reference-pillar/src/main/java/org/bitrepository/pillar/store/filearchive/ReferenceArchive.java @@ -1,29 +1,33 @@ /* * #%L * Bitmagasin integrationstest - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.filearchive; +import org.bitrepository.common.ArgumentValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; @@ -34,44 +38,37 @@ import java.util.Collection; import java.util.List; -import org.bitrepository.common.ArgumentValidator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * Class for managing the files for the reference pillar. This supports a single CollectionID. */ public class ReferenceArchive { - private Logger log = LoggerFactory.getLogger(getClass()); - /** The maximum buffer for the stream interaction.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); + private final Object lock = new Object(); public static final int MAX_BUFFER_SIZE = 32 * 1024; - - /** The list of directories to manage.*/ private final List directories = new ArrayList<>(); - - /** - * Constructor. Initializes the file directory. - * + + /** * @param dirPaths The list of paths to the archival base directories. */ public ReferenceArchive(List dirPaths) { ArgumentValidator.checkNotNullOrEmpty(dirPaths, "List dirPaths"); - for(String dir : dirPaths) { + for (String dir : dirPaths) { directories.add(new ArchiveDirectory(dir)); } } /** * Retrieves the file for the given file id. + * * @param fileID The id of the file to retrieve. * @return The file. */ public File getFile(String fileID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - - for(ArchiveDirectory dir : directories) { - if(dir.hasFile(fileID)) { + + for (ArchiveDirectory dir : directories) { + if (dir.hasFile(fileID)) { return dir.retrieveFile(fileID); } } @@ -84,9 +81,9 @@ public File getFile(String fileID) { */ public boolean hasFile(String fileID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - - for(ArchiveDirectory dir : directories) { - if(dir.hasFile(fileID)) { + + for (ArchiveDirectory dir : directories) { + if (dir.hasFile(fileID)) { return true; } } @@ -98,29 +95,30 @@ public boolean hasFile(String fileID) { */ public Collection getAllFileIds() { List res = new ArrayList<>(); - for(ArchiveDirectory dir : directories) { + for (ArchiveDirectory dir : directories) { res.addAll(dir.getFileIds()); } return res; } /** - * Retrieves an inputstream to the given file. + * Retrieves an input-stream to the given file. + * * @param fileID The id of the file. - * @return The inputstream to the file. - * @throws IOException If no inputstream can be made. + * @return The input-stream to the file. + * @throws IOException If no input-stream can be made. */ - public FileInputStream getFileAsInputstream(String fileID) throws IOException { + public FileInputStream getFileAsInputStream(String fileID) throws IOException { return new FileInputStream(getFile(fileID)); } /** - * Creates a file from the data in the inputstream. + * Creates a file from the data in the input-stream. * The file will be placed in the temporary directory, and requires validation before it can be moved to the * file archive. * * @param fileID The id of the file to create. - * @param inputStream The inputstream to extract the content of the file from. + * @param inputStream The input-stream to extract the content of the file from. * @return The file, which should be validated. * @throws IOException If it fails to download the file. */ @@ -129,147 +127,153 @@ public File downloadFileForValidation(String fileID, InputStream inputStream) th ArgumentValidator.checkNotNull(inputStream, "inputStream"); ArchiveDirectory dir = getDirWithMostSpace(); - File downloadedFile = null; - synchronized(dir) { + File downloadedFile; + synchronized (lock) { downloadedFile = dir.getNewFileInTempDir(fileID); log.debug("Downloading the file '" + fileID + "' for validation."); - + // Save InputStream to the file. - try (BufferedOutputStream bufferedOutputstream - = new BufferedOutputStream(new FileOutputStream(downloadedFile))){ + try (BufferedOutputStream bufferedOutputstream + = new BufferedOutputStream(new FileOutputStream(downloadedFile))) { byte[] buffer = new byte[MAX_BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer)) != -1) { bufferedOutputstream.write(buffer, 0, bytesRead); } - } + } } return downloadedFile; } - + /** * Moves a file from the tmpDir to fileDir. + * * @param fileID The id of the file. */ public void moveToArchive(String fileID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); log.info("Moving the file '" + fileID + "' to archive."); - ArchiveDirectory dir = getDirWithTmpFile(fileID); - synchronized(dir) { + synchronized (lock) { + ArchiveDirectory dir = getDirWithTmpFile(fileID); dir.moveFromTmpToArchive(fileID); } } /** * Removes a file from the archive. + * * @param fileID The id of the file. */ public void deleteFile(String fileID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - ArchiveDirectory dir = getDirWithFile(fileID); - synchronized(dir) { + synchronized (lock) { + ArchiveDirectory dir = getDirWithFile(fileID); dir.removeFileFromArchive(fileID); } } - + /** * The replace operation atomically. * Removes the archived file from its directory, and moves the tmpFile into the archive dir. - * + * * @param fileID The id of the file to perform the replace function upon. */ public synchronized void replaceFile(String fileID) { ArgumentValidator.checkNotNullOrEmpty(fileID, "String fileID"); - - ArchiveDirectory tmpDir = getDirWithTmpFile(fileID); - - synchronized(tmpDir) { + + synchronized (lock) { + ArchiveDirectory tmpDir = getDirWithTmpFile(fileID); ArchiveDirectory fileDir = getDirWithFile(fileID); fileDir.removeFileFromArchive(fileID); tmpDir.moveFromTmpToArchive(fileID); } } - + /** * For retrieval of the size left in this archive. + * * @return The number of bytes left in the archive. */ public long sizeLeftInArchive() { return getDirWithMostSpace().getBytesLeft(); } - + /** * Retrieves the file within a tmpDir. + * * @param fileID The id of the file to locate within the tmpDir. * @return The file in the tmpDir. */ public File getFileInTmpDir(String fileID) { return getDirWithTmpFile(fileID).getFileInTempDir(fileID); } - + /** * Ensures that no such file exists within the tmp directory. - * + * * @param fileID The id of the file to clean up after. */ public void ensureFileNotInTmpDir(String fileID) { - for(ArchiveDirectory dir : directories) { - if(dir.hasFileInTempDir(fileID)) { + for (ArchiveDirectory dir : directories) { + if (dir.hasFileInTempDir(fileID)) { log.info("Removing tmp file '" + fileID + "' from tmp dir '" + dir + "'."); dir.removeFileFromTmp(fileID); } } } - + /** * Finds the directory with the most space left. + * * @return The archive directory with the most space left. */ private ArchiveDirectory getDirWithMostSpace() { Long largestSize = -1L; ArchiveDirectory res = null; - - for(ArchiveDirectory dir : directories) { - if(largestSize < dir.getBytesLeft()) { + + for (ArchiveDirectory dir : directories) { + if (largestSize < dir.getBytesLeft()) { largestSize = dir.getBytesLeft(); res = dir; } } return res; } - + /** * Finds the archive directory with the given file within its archive directory. + * * @param fileID The id of the file. * @return The archive directory with the file. */ private ArchiveDirectory getDirWithFile(String fileID) { - for(ArchiveDirectory dir : directories) { - if(dir.hasFile(fileID)) { + for (ArchiveDirectory dir : directories) { + if (dir.hasFile(fileID)) { return dir; } } - + throw new IllegalStateException("Does not have the file '" + fileID + "' within any archive dirs."); } /** * Finds the archive directory with the given file within its tmp directory, ready for archival. + * * @param fileID The id of the file. * @return The archive directory with the file in its tmp dir. */ private ArchiveDirectory getDirWithTmpFile(String fileID) { - for(ArchiveDirectory dir : directories) { - if(dir.hasFileInTempDir(fileID)) { + for (ArchiveDirectory dir : directories) { + if (dir.hasFileInTempDir(fileID)) { return dir; } } - + throw new IllegalStateException("Does not have the file '" + fileID + "' within any archive dirs."); } - + /** * Closes the reference archive. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java index a39f1fc1c..e7ab8ea31 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/DefaultPillarTest.java @@ -21,10 +21,6 @@ */ package org.bitrepository.pillar; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.util.Date; import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumType; @@ -46,6 +42,11 @@ import org.bitrepository.service.AlarmDispatcher; import org.bitrepository.service.audit.MockAuditManager; import org.bitrepository.service.contributor.ResponseDispatcher; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.util.Date; public abstract class DefaultPillarTest extends DefaultFixturePillarTest { protected FileStore archives; protected StorageModel model; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java index b9929b5a8..d30d78929 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MediatorTest.java @@ -21,10 +21,6 @@ */ package org.bitrepository.pillar; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.AlarmMessage; import org.bitrepository.bitrepositorymessages.IdentifyContributorsForGetStatusRequest; @@ -44,6 +40,11 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + public class MediatorTest extends DefaultFixturePillarTest { MockAuditManager audits; MessageHandlerContext context; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MockedPillarTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MockedPillarTest.java index b8f2ebe1e..a84686204 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MockedPillarTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/MockedPillarTest.java @@ -21,8 +21,6 @@ */ package org.bitrepository.pillar; -import static org.mockito.Mockito.mock; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumType; @@ -36,7 +34,8 @@ import org.bitrepository.protocol.FileExchange; import org.bitrepository.service.audit.MockAuditManager; import org.bitrepository.service.contributor.ResponseDispatcher; -import org.mockito.Mock; + +import static org.mockito.Mockito.mock; public abstract class MockedPillarTest extends DefaultFixturePillarTest { protected PillarMediator mediator; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/FileInfoStub.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/FileInfoStub.java index 68f3a25ed..383900cd2 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/FileInfoStub.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/FileInfoStub.java @@ -21,11 +21,11 @@ */ package org.bitrepository.pillar.common; +import org.bitrepository.common.filestore.FileInfo; + import java.io.IOException; import java.io.InputStream; -import org.bitrepository.common.filestore.FileInfo; - public class FileInfoStub implements FileInfo { @@ -47,7 +47,7 @@ public String getFileID() { } @Override - public InputStream getInputstream() throws IOException { + public InputStream getInputStream() throws IOException { return is; } diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java index 9545f22c8..c64ba2f3f 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/common/SettingsHelperTest.java @@ -22,15 +22,15 @@ package org.bitrepository.pillar.common; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import org.bitrepository.pillar.integration.func.Assert; import org.bitrepository.settings.repositorysettings.Collection; import org.bitrepository.settings.repositorysettings.PillarIDs; import org.testng.annotations.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + public class SettingsHelperTest { @Test( groups = {"regressiontest"}) public void getPillarCollectionsTest() { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/CollectionTestHelper.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/CollectionTestHelper.java index 914376e39..c4676e322 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/CollectionTestHelper.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/CollectionTestHelper.java @@ -21,8 +21,6 @@ * #L% */ -import java.util.Collection; - import org.bitrepository.access.AccessComponentFactory; import org.bitrepository.access.getfileids.GetFileIDsClient; import org.bitrepository.common.settings.Settings; @@ -30,10 +28,11 @@ import org.bitrepository.modify.deletefile.DeleteFileClient; import org.bitrepository.modify.putfile.PutFileClient; import org.bitrepository.protocol.fileexchange.HttpServerConfiguration; -import org.bitrepository.protocol.fileexchange.HttpServerConnector; import org.bitrepository.protocol.security.DummySecurityManager; import org.bitrepository.protocol.security.SecurityManager; +import java.util.Collection; + @SuppressWarnings("unused") public class CollectionTestHelper { private final Settings settings; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java index 1b5ade804..0abeef08b 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/EmbeddedPillar.java @@ -22,22 +22,18 @@ */ -import java.io.File; -import java.util.Arrays; - import org.bitrepository.common.settings.Settings; import org.bitrepository.common.utils.FileUtils; import org.bitrepository.pillar.Pillar; import org.bitrepository.pillar.PillarComponentFactory; -import org.bitrepository.protocol.activemq.ActiveMQMessageBus; import org.bitrepository.protocol.messagebus.MessageBus; import org.bitrepository.protocol.messagebus.MessageBusManager; -import org.bitrepository.protocol.messagebus.SimpleMessageBus; -import org.bitrepository.protocol.security.DummySecurityManager; import org.bitrepository.service.LifeCycledService; import org.bitrepository.settings.referencesettings.CollectionDirs; import org.bitrepository.settings.referencesettings.PillarType; +import java.io.File; + public class EmbeddedPillar implements LifeCycledService { private final Pillar pillar; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java index b0b31fadc..352e4f9ff 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/PillarIntegrationTest.java @@ -55,12 +55,11 @@ import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; +import javax.jms.JMSException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; -import javax.jms.JMSException; - /** * Super class for all tests which should test functionality on a single pillar. * diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java index 6afa81ea2..31e3c5a6a 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/PillarFunctionTest.java @@ -21,15 +21,15 @@ */ package org.bitrepository.pillar.integration.func; -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.Collection; - import org.bitrepository.pillar.integration.PillarIntegrationTest; import org.bitrepository.pillar.messagefactories.PutFileMessageFactory; import org.bitrepository.protocol.bus.MessageReceiver; import org.testng.annotations.BeforeMethod; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Collection; + /** * The parent class for pillar acceptance tests. The tests can be run in a multi pillar collection has the tests will * ignore responses from other pillars. diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java index 15debce47..7ed6b42b1 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/deletefile/DeleteFileRequestIT.java @@ -21,19 +21,16 @@ */ package org.bitrepository.pillar.integration.func.deletefile; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumType; import org.bitrepository.bitrepositoryelements.ResponseCode; +import org.bitrepository.bitrepositorymessages.DeleteFileFinalResponse; +import org.bitrepository.bitrepositorymessages.DeleteFileProgressResponse; +import org.bitrepository.bitrepositorymessages.DeleteFileRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForDeleteFileRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForDeleteFileResponse; import org.bitrepository.bitrepositorymessages.MessageRequest; import org.bitrepository.bitrepositorymessages.MessageResponse; -import org.bitrepository.bitrepositorymessages.DeleteFileFinalResponse; -import org.bitrepository.bitrepositorymessages.DeleteFileProgressResponse; -import org.bitrepository.bitrepositorymessages.DeleteFileRequest; import org.bitrepository.common.utils.Base16Utils; import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.pillar.PillarTestGroups; @@ -43,6 +40,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; + public class DeleteFileRequestIT extends DefaultPillarOperationTest { protected DeleteFileMessageFactory msgFactory; private String pillarDestination; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java index c380674d2..50224a84f 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getaudittrails/GetAuditTrailsTest.java @@ -21,11 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getaudittrails; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.List; - import org.bitrepository.access.getaudittrails.AuditTrailQuery; import org.bitrepository.access.getaudittrails.client.AuditTrailResult; import org.bitrepository.bitrepositoryelements.AuditTrailEvent; @@ -34,6 +29,11 @@ import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.testng.annotations.Test; +import java.util.List; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + public class GetAuditTrailsTest extends PillarFunctionTest { @Override protected void initializeCUT() { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java index bebd943a3..507fd185f 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumQueryTest.java @@ -21,11 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getchecksums; -import java.util.GregorianCalendar; -import java.util.List; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.access.ContributorQuery; import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.common.utils.CalendarUtils; @@ -34,6 +29,10 @@ import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.testng.annotations.Test; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.GregorianCalendar; +import java.util.List; + public class GetChecksumQueryTest extends PillarFunctionTest { @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java index f04e4fa40..4ce8bf901 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/GetChecksumTest.java @@ -21,11 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getchecksums; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.assertNotNull; - -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumType; @@ -36,6 +31,11 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import java.util.List; + +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + public class GetChecksumTest extends PillarFunctionTest { @BeforeClass diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java index 620bd74f5..51fd55102 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getchecksums/IdentifyPillarsForGetChecksumsIT.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getchecksums; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -39,6 +36,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + public class IdentifyPillarsForGetChecksumsIT extends DefaultPillarIdentificationTest { protected GetChecksumsMessageFactory msgFactory; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java index c43c222c1..49d453d36 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfile/IdentifyPillarsForGetFileIT.java @@ -21,8 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getfile; -import static org.testng.Assert.assertEquals; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForGetFileRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForGetFileResponse; @@ -32,6 +30,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; + public class IdentifyPillarsForGetFileIT extends PillarFunctionTest { protected GetFileMessageFactory msgFactory; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java index bdacd6f06..fb0794b65 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsQueryTest.java @@ -21,16 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getfileids; -import static org.bitrepository.pillar.integration.func.Assert.assertEmpty; -import static org.bitrepository.pillar.integration.func.Assert.assertEquals; -import static org.bitrepository.pillar.integration.func.Assert.assertTrue; -import static org.testng.Assert.assertFalse; - -import java.util.GregorianCalendar; -import java.util.List; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.access.ContributorQuery; import org.bitrepository.bitrepositoryelements.FileIDsDataItem; import org.bitrepository.common.utils.CalendarUtils; @@ -38,6 +28,15 @@ import org.bitrepository.pillar.integration.func.PillarFunctionTest; import org.testng.annotations.Test; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.GregorianCalendar; +import java.util.List; + +import static org.bitrepository.pillar.integration.func.Assert.assertEmpty; +import static org.bitrepository.pillar.integration.func.Assert.assertEquals; +import static org.bitrepository.pillar.integration.func.Assert.assertTrue; +import static org.testng.Assert.assertFalse; + public class GetFileIDsQueryTest extends PillarFunctionTest { @Test ( groups = {PillarTestGroups.FULL_PILLAR_TEST, PillarTestGroups.CHECKSUM_PILLAR_TEST} ) diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java index 20258232d..2114671b2 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/GetFileIDsTest.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getfileids; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.GetFileIDsFinalResponse; @@ -39,6 +36,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; + import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java index 61389ea01..8d946361e 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getfileids/IdentifyPillarsForGetFileIDsIT.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.integration.func.getfileids; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForGetFileIDsRequest; @@ -37,6 +34,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + public class IdentifyPillarsForGetFileIDsIT extends DefaultPillarIdentificationTest { protected GetFileIDsMessageFactory msgFactory; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java index ccae68e91..3b786cb70 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/GetStatusRequestIT.java @@ -22,8 +22,6 @@ package org.bitrepository.pillar.integration.func.getstatus; -import java.lang.reflect.Method; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.AlarmMessage; import org.bitrepository.bitrepositorymessages.GetStatusFinalResponse; @@ -38,6 +36,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.lang.reflect.Method; + public class GetStatusRequestIT extends PillarFunctionTest { protected GetStatusMessageFactory msgFactory; private String pillarDestination; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java index 643cb4f6a..15ede00e3 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/getstatus/IdentifyContributorsForGetStatusIT.java @@ -22,10 +22,6 @@ package org.bitrepository.pillar.integration.func.getstatus; -import static org.testng.Assert.assertEquals; - -import java.lang.reflect.Method; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.IdentifyContributorsForGetStatusRequest; import org.bitrepository.bitrepositorymessages.IdentifyContributorsForGetStatusResponse; @@ -35,6 +31,10 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.lang.reflect.Method; + +import static org.testng.Assert.assertEquals; + public class IdentifyContributorsForGetStatusIT extends PillarFunctionTest { protected GetStatusMessageFactory msgFactory; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java index d0158835b..46c8c6f8d 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/multicollection/MultipleCollectionIT.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.integration.func.multicollection; -import java.util.Arrays; -import java.util.Collection; - import org.bitrepository.access.ContributorQuery; import org.bitrepository.client.exceptions.NegativeResponseException; import org.bitrepository.common.utils.TestFileHelper; @@ -33,6 +30,9 @@ import org.bitrepository.protocol.bus.MessageReceiver; import org.testng.annotations.Test; +import java.util.Arrays; +import java.util.Collection; + public class MultipleCollectionIT extends PillarIntegrationTest { /** Used for receiving responses from the pillar */ protected MessageReceiver clientReceiver; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java index 2c33ddfac..eff5fbac7 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/putfile/PutFileRequestIT.java @@ -21,13 +21,6 @@ */ package org.bitrepository.pillar.integration.func.putfile; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; - -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForPutFileRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForPutFileResponse; @@ -44,6 +37,13 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + public class PutFileRequestIT extends DefaultPillarOperationTest { protected PutFileMessageFactory msgFactory; private String pillarDestination; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java index 8ad1cf9d8..b11857b8c 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/func/replacefile/ReplaceFileRequestIT.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.integration.func.replacefile; -import java.lang.reflect.Method; -import java.util.concurrent.TimeUnit; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForReplaceFileRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForReplaceFileResponse; @@ -40,6 +37,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.lang.reflect.Method; +import java.util.concurrent.TimeUnit; + public class ReplaceFileRequestIT extends DefaultPillarOperationTest { protected ReplaceFileMessageFactory msgFactory; private String pillarDestination; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/model/PillarFileManager.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/model/PillarFileManager.java index d758b3690..f56880923 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/model/PillarFileManager.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/model/PillarFileManager.java @@ -22,8 +22,6 @@ package org.bitrepository.pillar.integration.model; -import java.util.List; - import org.bitrepository.access.ContributorQuery; import org.bitrepository.access.getchecksums.conversation.ChecksumsCompletePillarEvent; import org.bitrepository.access.getfileids.conversation.FileIDsCompletePillarEvent; @@ -38,9 +36,10 @@ import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.pillar.integration.ClientProvider; import org.bitrepository.protocol.fileexchange.HttpServerConfiguration; -import org.bitrepository.protocol.fileexchange.HttpServerConnector; import org.jaccept.TestEventManager; +import java.util.List; + public class PillarFileManager { private final String collectionID; private final String pillarID; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java index 1688d60cf..76b212d9f 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/integration/perf/PutFileStressIT.java @@ -21,8 +21,6 @@ * #L% */ -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; import org.bitrepository.client.eventhandler.EventHandler; import org.bitrepository.client.eventhandler.OperationEvent; import org.bitrepository.common.utils.TestFileHelper; @@ -33,6 +31,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + public class PutFileStressIT extends PillarPerformanceTest { protected PutFileClient putClient; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetChecksumsMessageFactory.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetChecksumsMessageFactory.java index 148cb715f..edf7a5b60 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetChecksumsMessageFactory.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetChecksumsMessageFactory.java @@ -24,16 +24,15 @@ */ package org.bitrepository.pillar.messagefactories; -import java.math.BigInteger; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositorymessages.GetChecksumsRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForGetChecksumsRequest; import org.bitrepository.common.settings.Settings; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigInteger; + public class GetChecksumsMessageFactory extends PillarTestMessageFactory { public GetChecksumsMessageFactory(String collectionID, Settings clientSettings, String pillarID, String pillarDestination) { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetFileIDsMessageFactory.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetFileIDsMessageFactory.java index aef4897d4..ab574177b 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetFileIDsMessageFactory.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/GetFileIDsMessageFactory.java @@ -24,15 +24,14 @@ */ package org.bitrepository.pillar.messagefactories; -import java.math.BigInteger; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositorymessages.GetFileIDsRequest; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForGetFileIDsRequest; import org.bitrepository.common.settings.Settings; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigInteger; + public class GetFileIDsMessageFactory extends PillarTestMessageFactory { public GetFileIDsMessageFactory(String collectionID, Settings clientSettings, String pillarID, String pillarDestination) { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PillarTestMessageFactory.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PillarTestMessageFactory.java index 87229ac5e..536055ad5 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PillarTestMessageFactory.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PillarTestMessageFactory.java @@ -21,12 +21,12 @@ */ package org.bitrepository.pillar.messagefactories; -import java.util.UUID; - import org.bitrepository.bitrepositorymessages.MessageRequest; import org.bitrepository.common.settings.Settings; import org.bitrepository.protocol.message.ComponentTestMessageFactory; +import java.util.UUID; + public abstract class PillarTestMessageFactory { private final ComponentTestMessageFactory componentTestMessageFactory; private final String pillarDestinationID; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PutFileMessageFactory.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PutFileMessageFactory.java index 9094ec72c..05c16cf29 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PutFileMessageFactory.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/PutFileMessageFactory.java @@ -39,14 +39,14 @@ */ package org.bitrepository.pillar.messagefactories; -import java.math.BigInteger; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForPutFileRequest; import org.bitrepository.bitrepositorymessages.PutFileRequest; import org.bitrepository.common.settings.Settings; +import java.math.BigInteger; + public class PutFileMessageFactory extends PillarTestMessageFactory { public PutFileMessageFactory( diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/ReplaceFileMessageFactory.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/ReplaceFileMessageFactory.java index a901a265c..4c9ac8bef 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/ReplaceFileMessageFactory.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagefactories/ReplaceFileMessageFactory.java @@ -39,14 +39,14 @@ */ package org.bitrepository.pillar.messagefactories; -import java.math.BigInteger; - import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositorymessages.IdentifyPillarsForReplaceFileRequest; import org.bitrepository.bitrepositorymessages.ReplaceFileRequest; import org.bitrepository.common.settings.Settings; +import java.math.BigInteger; + public class ReplaceFileMessageFactory extends PillarTestMessageFactory { public ReplaceFileMessageFactory(String collectionID, Settings clientSettings, String pillarID, String pillarDestination) { diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java index b50ea89d1..fa3e760c6 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/DeleteFileTest.java @@ -24,12 +24,6 @@ */ package org.bitrepository.pillar.messagehandling; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; - import org.bitrepository.bitrepositoryelements.AlarmCode; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -45,6 +39,12 @@ import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.testng.Assert.assertEquals; + /** * Tests the PutFile functionality on the ReferencePillar. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java index c571dd479..10ee4ed1d 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetAuditTrailsTest.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.messagehandling; -import java.math.BigInteger; -import java.util.Date; -import javax.xml.datatype.XMLGregorianCalendar; import org.bitrepository.bitrepositoryelements.AuditTrailEvent; import org.bitrepository.bitrepositoryelements.FileAction; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -37,6 +34,10 @@ import org.bitrepository.pillar.messagefactories.GetAuditTrailsMessageFactory; import org.testng.annotations.Test; +import javax.xml.datatype.XMLGregorianCalendar; +import java.math.BigInteger; +import java.util.Date; + import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java index 9acfbb9ea..3625ecb76 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetChecksumsTest.java @@ -24,20 +24,7 @@ */ package org.bitrepository.pillar.messagehandling; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; - -import java.util.Date; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; -import org.bitrepository.bitrepositoryelements.ChecksumType; import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.AlarmMessage; @@ -56,6 +43,16 @@ import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.Date; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + /** * Tests the PutFile functionality on the ReferencePillar. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java index b45b568e4..2d1c5e0c9 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileIDsTest.java @@ -24,19 +24,6 @@ */ package org.bitrepository.pillar.messagehandling; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; -import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; - -import java.util.Date; - -import javax.xml.datatype.XMLGregorianCalendar; - import org.bitrepository.bitrepositoryelements.FileIDs; import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.AlarmMessage; @@ -54,6 +41,18 @@ import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import javax.xml.datatype.XMLGregorianCalendar; +import java.util.Date; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doAnswer; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + /** * Tests the PutFile functionality on the ReferencePillar. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java index fc0a3fabc..7b511a005 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/GetFileTest.java @@ -24,13 +24,6 @@ */ package org.bitrepository.pillar.messagehandling; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; - -import java.io.ByteArrayInputStream; - import org.bitrepository.bitrepositoryelements.ResponseCode; import org.bitrepository.bitrepositorymessages.AlarmMessage; import org.bitrepository.bitrepositorymessages.GetFileFinalResponse; @@ -49,6 +42,13 @@ import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import java.io.ByteArrayInputStream; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.testng.Assert.assertEquals; + /** * Tests the PutFile functionality on the ReferencePillar. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java index 3092fc0c0..a14b096f3 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/PutFileTest.java @@ -24,15 +24,6 @@ */ package org.bitrepository.pillar.messagehandling; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; - import org.bitrepository.bitrepositoryelements.AlarmCode; import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; @@ -51,6 +42,15 @@ import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + /** * Tests the PutFile functionality on the ReferencePillar. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java index 0151ff5bf..53bab5e94 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/messagehandling/ReplaceFileTest.java @@ -24,14 +24,6 @@ */ package org.bitrepository.pillar.messagehandling; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertNotNull; - import org.bitrepository.bitrepositoryelements.AlarmCode; import org.bitrepository.bitrepositoryelements.ChecksumDataForFileTYPE; import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; @@ -50,6 +42,14 @@ import org.mockito.stubbing.Answer; import org.testng.annotations.Test; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + /** * Tests the ReplaceFile functionality on the ReferencePillar. */ diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java index 61f27c25c..06688702e 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/schedulablejobs/RecalculateChecksumWorkflowTest.java @@ -22,7 +22,6 @@ */ import org.bitrepository.pillar.DefaultPillarTest; -import org.bitrepository.pillar.schedulablejobs.RecalculateChecksumJob; import org.bitrepository.service.workflow.SchedulableJob; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java index 4bd0580d6..cc8f7fd67 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/ChecksumPillarModelTest.java @@ -21,15 +21,6 @@ */ package org.bitrepository.pillar.store; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.io.IOException; -import java.util.Date; - import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumType; import org.bitrepository.common.utils.ChecksumUtils; @@ -41,6 +32,15 @@ import org.bitrepository.settings.referencesettings.ChecksumPillarFileDownload; import org.testng.annotations.Test; +import java.io.IOException; +import java.util.Date; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + public class ChecksumPillarModelTest extends DefaultFixturePillarTest { ChecksumStorageModel pillarModel; ChecksumStore cache; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java index 246f097c0..0733bc2a1 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/FullPillarModelTest.java @@ -21,15 +21,6 @@ */ package org.bitrepository.pillar.store; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.IOException; - import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE; import org.bitrepository.bitrepositoryelements.ChecksumType; import org.bitrepository.common.filestore.FileInfo; @@ -44,6 +35,15 @@ import org.bitrepository.service.exception.RequestHandlerException; import org.testng.annotations.Test; +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + public class FullPillarModelTest extends DefaultFixturePillarTest { FileStorageModel pillarModel; ChecksumStore cache; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java index ab843d8af..97d62b8ea 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ArchiveDirectoryTest.java @@ -21,15 +21,6 @@ * #L% */ -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - import org.bitrepository.common.utils.FileUtils; import org.bitrepository.common.utils.TestFileHelper; import org.bitrepository.pillar.store.filearchive.ArchiveDirectory; @@ -38,6 +29,14 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; +import java.io.File; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + public class ArchiveDirectoryTest extends ExtendedTestCase { private static String DIR_NAME = "archive-directory"; private static String FILE_DIR_NAME = DIR_NAME + "/fileDir"; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java index a0c64c242..892446721 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/archive/ReferenceArchiveTest.java @@ -1,36 +1,30 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id: PutFileOnReferencePillarTest.java 589 2011-12-01 15:34:42Z jolf $ - * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/PutFileOnReferencePillarTest.java $ + * $HeadURL: https://sbforge.org/svn/bitrepository/bitrepository-reference/trunk/bitrepository-reference-pillar/src/test/java/org + * /bitrepository/pillar/PutFileOnReferencePillarTest.java $ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.pillar.store.archive; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - import org.bitrepository.common.utils.FileUtils; import org.bitrepository.pillar.DefaultPillarTest; import org.bitrepository.pillar.common.MessageHandlerContext; @@ -40,15 +34,22 @@ import org.testng.Assert; import org.testng.annotations.Test; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.List; + public class ReferenceArchiveTest extends DefaultPillarTest { protected ReferenceArchive archive; protected PillarMediator mediator; protected MockAuditManager audits; protected MessageHandlerContext context; - + private static String DIR_NAME = "archive-directory"; private static String FILE_DIR_NAME = DIR_NAME + "/fileDir"; - + private static String EXISTING_FILE = "file1"; private static String MISSING_FILE = "Missing-filE"; @@ -60,19 +61,19 @@ protected void shutdownCUT() { } super.shutdownCUT(); } - - @Test( groups = {"regressiontest", "pillartest"}) + + @Test(groups = {"regressiontest", "pillartest"}) public void testReferenceArchive() throws Exception { addDescription("Test the ReferenceArchive."); addStep("Setup", "Should be OK."); - - ReferenceArchive archive = new ReferenceArchive(Arrays.asList(DIR_NAME)); + + ReferenceArchive archive = new ReferenceArchive(List.of(DIR_NAME)); createExistingFile(); - + addStep("test 'hasFile'", "Should be true for the existing one and false for the missing one."); Assert.assertTrue(archive.hasFile(EXISTING_FILE)); Assert.assertFalse(archive.hasFile(MISSING_FILE)); - + addStep("Test 'getFile'", "Should be ok for the existing file and throw an exception on the missing"); archive.getFile(EXISTING_FILE); try { @@ -81,26 +82,27 @@ public void testReferenceArchive() throws Exception { } catch (Exception e) { // expected } - + addStep("Test getAllFileIDs", "Should only deliver the existing file"); - Assert.assertEquals(archive.getAllFileIds(), Arrays.asList(EXISTING_FILE)); - - addStep("Test 'getFileAsInputstream'", "Should only be able to deliver the existing file."); - archive.getFileAsInputstream(EXISTING_FILE); + Assert.assertEquals(archive.getAllFileIds(), List.of(EXISTING_FILE)); + + addStep("Test 'getFileAsInputStream'", "Should only be able to deliver the existing file."); + FileInputStream fileAsInputStream = archive.getFileAsInputStream(EXISTING_FILE); + assert fileAsInputStream != null; try { - archive.getFileAsInputstream(MISSING_FILE); + archive.getFileAsInputStream(MISSING_FILE); Assert.fail("Should throw an exception when getting a missing file."); } catch (Exception e) { // expected } - + addStep("Delete, recreate and delete again", "Should be moved to retain dir twice."); archive.deleteFile(EXISTING_FILE); createExistingFile(); archive.deleteFile(EXISTING_FILE); createExistingFile(); Assert.assertTrue(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE + ".old").isFile()); - + addStep("Try to delete missing file.", "Should throw an exception"); try { archive.deleteFile(MISSING_FILE); @@ -108,7 +110,7 @@ public void testReferenceArchive() throws Exception { } catch (IllegalStateException e) { // Expected. } - + addStep("Replace a file, which does not exist in the filedir.", "Should throw an exception"); try { archive.replaceFile(MISSING_FILE); @@ -116,14 +118,15 @@ public void testReferenceArchive() throws Exception { } catch (IllegalStateException e) { // Expected. } - - addStep("Copy a file into the tmpDir and then use replace.", "Should create another file in retain dir and remove the one in tmpDir."); - FileUtils.copyFile(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE), + + addStep("Copy a file into the tmpDir and then use replace.", + "Should create another file in retain dir and remove the one in tmpDir."); + FileUtils.copyFile(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE), new File(DIR_NAME + "/tmpDir/" + EXISTING_FILE)); archive.replaceFile(EXISTING_FILE); Assert.assertFalse(new File(DIR_NAME + "/tmpDir/" + EXISTING_FILE).isFile()); Assert.assertTrue(new File(DIR_NAME + "/retainDir/" + EXISTING_FILE + ".old.old").isFile()); - + addStep("Try performing the replace, when the file in the tempdir has been removed.", "Should throw an exception"); try { archive.replaceFile(EXISTING_FILE); @@ -131,12 +134,13 @@ public void testReferenceArchive() throws Exception { } catch (IllegalStateException e) { // Expected. } - + archive.close(); } - + private void createExistingFile() throws Exception { - OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(FILE_DIR_NAME, EXISTING_FILE), false), StandardCharsets.UTF_8); + OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File(FILE_DIR_NAME, EXISTING_FILE), false), + StandardCharsets.UTF_8); osw.write("test-data\n"); osw.flush(); osw.close(); diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java index 6db87e046..04ec51809 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseMigrationTest.java @@ -21,16 +21,8 @@ */ package org.bitrepository.pillar.store.checksumcache; -import java.io.File; -import java.io.IOException; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; -import org.bitrepository.common.utils.CalendarUtils; import org.bitrepository.common.utils.FileUtils; import org.bitrepository.pillar.store.checksumdatabase.ChecksumDBMigrator; import org.bitrepository.service.database.DBConnector; @@ -43,6 +35,12 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.io.File; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; + import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CHECKSUM_TABLE; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_CHECKSUM; import static org.bitrepository.pillar.store.checksumdatabase.DatabaseConstants.CS_COLLECTION_ID; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java index 76a85febe..48934e014 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumDatabaseTest.java @@ -21,9 +21,6 @@ */ package org.bitrepository.pillar.store.checksumcache; -import java.util.Date; -import java.util.List; - import org.bitrepository.bitrepositoryelements.ChecksumDataForChecksumSpecTYPE; import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; @@ -43,6 +40,9 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.util.Date; +import java.util.List; + public class ChecksumDatabaseTest extends ExtendedTestCase { private String collectionID; protected Settings settings; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java index 88e53471d..f52b9379a 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/ChecksumEntryTest.java @@ -21,13 +21,13 @@ * #L% */ -import java.util.Date; - import org.bitrepository.pillar.store.checksumdatabase.ChecksumEntry; import org.jaccept.structure.ExtendedTestCase; import org.testng.Assert; import org.testng.annotations.Test; +import java.util.Date; + public class ChecksumEntryTest extends ExtendedTestCase { private static final String CE_FILE = "file"; private static final String CE_CHECKSUM = "checksum"; diff --git a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java index 7dfa83e55..3025fe18c 100644 --- a/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java +++ b/bitrepository-reference-pillar/src/test/java/org/bitrepository/pillar/store/checksumcache/MemoryCacheMock.java @@ -21,6 +21,12 @@ */ package org.bitrepository.pillar.store.checksumcache; +import org.bitrepository.pillar.store.checksumdatabase.ChecksumEntry; +import org.bitrepository.pillar.store.checksumdatabase.ChecksumStore; +import org.bitrepository.pillar.store.checksumdatabase.ExtractedChecksumResultSet; +import org.bitrepository.pillar.store.checksumdatabase.ExtractedFileIDsResultSet; + +import javax.xml.datatype.XMLGregorianCalendar; import java.util.ArrayList; import java.util.Collection; import java.util.Date; @@ -28,13 +34,6 @@ import java.util.List; import java.util.Map; -import javax.xml.datatype.XMLGregorianCalendar; - -import org.bitrepository.pillar.store.checksumdatabase.ChecksumEntry; -import org.bitrepository.pillar.store.checksumdatabase.ChecksumStore; -import org.bitrepository.pillar.store.checksumdatabase.ExtractedChecksumResultSet; -import org.bitrepository.pillar.store.checksumdatabase.ExtractedFileIDsResultSet; - /** * Very simple memory based implementation of the ChecksumCache. * Everything is kept within a map between the file ids and their checksum. diff --git a/bitrepository-reference-settings/src/main/resources/xsd/ReferenceSettings.xsd b/bitrepository-reference-settings/src/main/resources/xsd/ReferenceSettings.xsd index 5ce9b7da0..6aab9a6db 100644 --- a/bitrepository-reference-settings/src/main/resources/xsd/ReferenceSettings.xsd +++ b/bitrepository-reference-settings/src/main/resources/xsd/ReferenceSettings.xsd @@ -23,7 +23,7 @@ +> diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/AbstractBitrepositoryContextListener.java b/bitrepository-service/src/main/java/org/bitrepository/service/AbstractBitrepositoryContextListener.java index 178c209b1..1235774f1 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/AbstractBitrepositoryContextListener.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/AbstractBitrepositoryContextListener.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,48 +30,51 @@ /** * The Listener has two intentions - * 1) Acquire necessary information at startup to locate configuration files and create the first instance - * of the basic client, so everything is setup before the first users start using the webservice. - * 2) In time shut the service down in a proper manner, so no threads will be orphaned. + * 1) Acquire necessary information at startup to locate configuration files and create the first instance + * of the basic client, so everything is set up before the first users start using the webservice. + * 2) In time shut the service down in a proper manner, so no threads will be orphaned. */ public abstract class AbstractBitrepositoryContextListener implements ServletContextListener { - /** The log.*/ private final Logger log = LoggerFactory.getLogger(getClass()); - + /** * Return the path to the service's configuration directory. + * * @return the path to the service's configuration directory */ public abstract String getSettingsParameter(); - + /** * Method to get an instance of the service for the context. + * * @return an instance of the service for the context */ public abstract LifeCycledService getService(); - + /** * Sets up the configuration. + * * @param configurationDir the configuration dir */ public abstract void initialize(String configurationDir); - + /** * Method called at servlet initialization. + * * @param sce the servlet context event for the initialization */ public void contextInitialized(ServletContextEvent sce) { String confDir = sce.getServletContext().getInitParameter(getSettingsParameter()); - if(confDir == null) { + if (confDir == null) { throw new RuntimeException("No configuration directory specified!"); } log.debug("Configuration dir = " + confDir); - + try { new LogbackConfigLoader(confDir + "/logback.xml"); } catch (Exception e) { log.info("Failed to read log configuration file. Falling back to default."); - } + } try { initialize(confDir); getService(); @@ -83,11 +86,12 @@ public void contextInitialized(ServletContextEvent sce) { throw e; } log.debug("Servlet context initialized"); - + } - + /** * Method called at servlet shutdown. + * * @param sce the servlet context event for the shutdown */ public void contextDestroyed(ServletContextEvent sce) { diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/AlarmDispatcher.java b/bitrepository-service/src/main/java/org/bitrepository/service/AlarmDispatcher.java index a577e08b7..97abea6da 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/AlarmDispatcher.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/AlarmDispatcher.java @@ -1,30 +1,29 @@ /* * #%L * Bitrepository Integration - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service; -import java.util.UUID; import org.bitrepository.bitrepositoryelements.Alarm; import org.bitrepository.bitrepositorymessages.AlarmMessage; import org.bitrepository.common.ArgumentValidator; @@ -36,77 +35,81 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Objects; +import java.util.UUID; + /** * The class for dispatching alarms. */ public class AlarmDispatcher extends MessageDispatcher { - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); private final AlarmLevel alarmLevel; - + /** - * @param sender Used for sending the alarms. - * @param settings The configuration. + * @param sender Used for sending the alarms. + * @param settings The configuration. * @param alarmLevel The alarm level, if null set to ERROR */ public AlarmDispatcher(Settings settings, MessageSender sender, AlarmLevel alarmLevel) { super(settings, sender); - if (alarmLevel == null) { - this.alarmLevel = AlarmLevel.ERROR; - } else { - this.alarmLevel = alarmLevel; - } + this.alarmLevel = Objects.requireNonNullElse(alarmLevel, AlarmLevel.ERROR); } /** * Delegates to #AlarmDispatcher(MessageSender, AlarmLevel) with a ERROR alarm level. - * @param sender Used for sending the alarms. + * + * @param sender Used for sending the alarms. * @param settings The configuration. */ public AlarmDispatcher(Settings settings, MessageSender sender) { this(settings, sender, AlarmLevel.ERROR); } - + /** - * Send an alarm at warning-level. + * Send an alarm at warning-level. * If the settings does not have alarm level at 'warning', then a log is made instead. + * * @param alarm The alarm to send. */ public void warning(Alarm alarm) { ArgumentValidator.checkNotNull(alarm, "alarm"); - if(alarmLevel != AlarmLevel.WARNING) { + if (alarmLevel != AlarmLevel.WARNING) { log.debug("Will send a '" + AlarmLevel.WARNING + "' alarm, when the alarm level is '" + alarmLevel + "'{}", alarm); } else { sendAlarm(alarm); } } - + /** - * Send an alarm at error-level. + * Send an alarm at error-level. * If the settings does not have alarm level at 'error', then a log is made instead. + * * @param alarm The alarm to send. */ public void error(Alarm alarm) { ArgumentValidator.checkNotNull(alarm, "alarm"); - if(alarmLevel == AlarmLevel.EMERGENCY) { + if (alarmLevel == AlarmLevel.EMERGENCY) { log.debug("Cannot send a '" + AlarmLevel.ERROR + "' alarm, when the alarm level is '" + alarmLevel + "'{}", alarm); } else { sendAlarm(alarm); } } - + /** * Send an alarm at emergency-level. At this level all alarms will be sent. + * * @param alarm The alarm to send. */ public void emergency(Alarm alarm) { ArgumentValidator.checkNotNull(alarm, "alarm"); sendAlarm(alarm); } - - /** + + /** * Method for sending an Alarm when something bad happens. + * * @param alarm The alarm to send to the destination for the alarm service. */ protected void sendAlarm(Alarm alarm) { @@ -119,7 +122,7 @@ protected void sendAlarm(Alarm alarm) { message.setReplyTo(settings.getContributorDestinationID()); message.setDestination(settings.getAlarmDestination()); message.setCollectionID(alarm.getCollectionID()); - + log.warn("Sending alarm: " + alarm); dispatchMessage(message); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/LifeCycledService.java b/bitrepository-service/src/main/java/org/bitrepository/service/LifeCycledService.java index 48669bcb2..5c852c8a3 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/LifeCycledService.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/LifeCycledService.java @@ -5,29 +5,31 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service; -/** Provides start() and shutdown() methods. */ +/** + * Provides start() and shutdown() methods. + */ public interface LifeCycledService { void start(); - + /** - * Method called to shutdown the service. + * Method called to shut down the service. */ void shutdown(); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/ServiceSettingsProvider.java b/bitrepository-service/src/main/java/org/bitrepository/service/ServiceSettingsProvider.java index d296cb09c..910c45c22 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/ServiceSettingsProvider.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/ServiceSettingsProvider.java @@ -1,7 +1,7 @@ /* -* #%L + * #%L * * Bitrepository Protocol - * + * * * $Id$ * * $HeadURL$ * * @@ -10,20 +10,20 @@ * * * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% -*/ + */ package org.bitrepository.service; @@ -39,11 +39,11 @@ public class ServiceSettingsProvider extends SettingsProvider { private final ServiceType serviceType; /** - * Creates a SettingsProvider which will use the provided SettingsLoader for loading the + * Creates a {@link SettingsProvider} which will use the provided {@link SettingsLoader} for loading the * settings. * * @param settingsReader Use for loading the settings. - * @param serviceType Will be used to load a componentID for the service based on the type. + * @param serviceType Will be used to load a componentID for the service based on the type. */ public ServiceSettingsProvider(SettingsLoader settingsReader, ServiceType serviceType) { super(settingsReader, null); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseConstants.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseConstants.java index 1472f0144..2c89ac3e1 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseConstants.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseConstants.java @@ -1,20 +1,20 @@ /* * #%L - * Bitrepository Reference Pillar + * BitRepository Reference Pillar * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -26,47 +26,81 @@ * All the names of the tables and the fields in these tables. */ public final class AuditDatabaseConstants { - - /** Private constructor to prevent instantiation of this constants class.*/ - private AuditDatabaseConstants() { } - - /** The name of the audit trail table.*/ - public final static String AUDITTRAIL_TABLE = "audittrail"; - /** The name of the sequence number field in the audit trail table. */ - public final static String AUDITTRAIL_SEQUENCE_NUMBER = "sequence_number"; - /** The name of the file guid field in the audit trail table. */ - public final static String AUDITTRAIL_FILE_GUID = "file_guid"; - /** The name of the actor guid field in the audit trail table. */ - public final static String AUDITTRAIL_ACTOR_GUID = "actor_guid"; - /** The name of the operation field in the audit trail table. */ - public final static String AUDITTRAIL_OPERATION = "operation"; - /** The name of the operation date field in the audit trail table. */ - public final static String AUDITTRAIL_OPERATION_DATE = "operation_date"; - /** The name of the information field in the audit trail table. */ - public final static String AUDITTRAIL_INFORMATION = "information"; - /** The name of the information field in the audit trail table. */ - public final static String AUDITTRAIL_OPERATIONID = "operationID"; - /** The name of the information field in the audit trail table. */ - public final static String AUDITTRAIL_FINGERPRINT = "fingerprint"; - /** The name of the audit field in the audit trail table. */ - public final static String AUDITTRAIL_AUDIT = "audit"; - - /** The name of the file table.*/ + private AuditDatabaseConstants() {} + + /** + * The name of the 'audit trail' table. + */ + public final static String AUDIT_TRAIL_TABLE = "audittrail"; + /** + * The name of the 'sequence number' field in the audit trail table. + */ + public final static String AUDIT_TRAIL_SEQUENCE_NUMBER = "sequence_number"; + /** + * The name of the 'file guid' field in the audit trail table. + */ + public final static String AUDIT_TRAIL_FILE_GUID = "file_guid"; + /** + * The name of the 'actor guid' field in the audit trail table. + */ + public final static String AUDIT_TRAIL_ACTOR_GUID = "actor_guid"; + /** + * The name of the 'operation' field in the audit trail table. + */ + public final static String AUDIT_TRAIL_OPERATION = "operation"; + /** + * The name of the 'operation date 'field in the audit trail table. + */ + public final static String AUDIT_TRAIL_OPERATION_DATE = "operation_date"; + /** + * The name of the information field in the audit trail table. + */ + public final static String AUDIT_TRAIL_INFORMATION = "information"; + /** + * The name of the information field in the audit trail table. + */ + public final static String AUDIT_TRAIL_OPERATIONID = "operationID"; + /** + * The name of the information field in the audit trail table. + */ + public final static String AUDIT_TRAIL_FINGERPRINT = "fingerprint"; + /** + * The name of the 'audit field' in the audit trail table. + */ + public final static String AUDIT_TRAIL_AUDIT = "audit"; + + /** + * The name of the 'file' table. + */ public final static String FILE_TABLE = "file"; - /** The name of the file guid field in the file table.*/ + /** + * The name of the 'file guid' field in the file table. + */ public final static String FILE_GUID = "file_guid"; - /** The name of the fileid field in the file table.*/ - public final static String FILE_FILEID = "fileid"; - /** The name of the collectionid field in the file table.*/ - public final static String FILE_COLLECTIONID = "collectionid"; - - /** The name of the actor table.*/ + /** + * The name of the 'fileid' field in the file table. + */ + public final static String FILE_FILE_ID = "fileid"; + /** + * The name of the 'collectionid' field in the file table. + */ + public final static String FILE_COLLECTION_ID = "collectionid"; + + /** + * The name of the 'actor' table. + */ public final static String ACTOR_TABLE = "actor"; - /** The name of the actor guid field in the actor table.*/ + /** + * The name of the 'actor guid' field in the actor table. + */ public final static String ACTOR_GUID = "actor_guid"; - /** The name of the actor name field in the actor table.*/ + /** + * The name of the 'actor name' field in the actor table. + */ public final static String ACTOR_NAME = "actor_name"; - - /** The name of the version table entry for the database.*/ + + /** + * The name of the version table entry for the database. + */ public final static String DATABASE_VERSION_ENTRY = "auditcontributordb"; } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseManager.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseManager.java index 0ac0afe00..efaca8bc6 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseManager.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditDatabaseManager.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -26,18 +26,18 @@ import org.bitrepository.settings.referencesettings.DatabaseSpecifics; /** - * Manager for the audit trail contributor database. For usage, see @DatabaseManager. + * Manager for the audit trail contributor database. For usage, see @DatabaseManager. */ public class AuditDatabaseManager extends DatabaseManager { private final DatabaseSpecifics databaseSpecifics; private DatabaseMigrator migrator; public final static String AUDIT_CONTRIBUTOR_DATABASE_SCHEMA = "sql/derby/auditContributorDBCreation.sql"; - + public AuditDatabaseManager(DatabaseSpecifics databaseSpecifics) { this.databaseSpecifics = databaseSpecifics; } - + @Override protected DatabaseSpecifics getDatabaseSpecifics() { return databaseSpecifics; @@ -45,7 +45,7 @@ protected DatabaseSpecifics getDatabaseSpecifics() { @Override protected synchronized DatabaseMigrator getMigrator() { - if(migrator == null) { + if (migrator == null) { migrator = new AuditTrailContributorDatabaseMigrator(connector); } return migrator; diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAOFactory.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAOFactory.java index e7ba8ee7f..7703d16b5 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAOFactory.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAOFactory.java @@ -26,25 +26,25 @@ import org.bitrepository.settings.referencesettings.DatabaseSpecifics; /** - * A DatabaseFactory which can return Derby and Postgres AuditTrailContributerDAO's. + * A DatabaseFactory which can return Derby and Postgres AuditTrailContributorDAO's. * * FIXME: Code does not reflect generic type. */ -public class AuditTrailContributerDAOFactory extends DatabaseFactory { +public class AuditTrailContributerDAOFactory extends DatabaseFactory { - public AuditTrailContributerDAO getAuditTrailContributorDAO(DatabaseSpecifics ds, String componentID) { - AuditTrailContributerDAO dao = getDAOInstance(ds); + public AuditTrailContributorDAO getAuditTrailContributorDAO(DatabaseSpecifics ds, String componentID) { + AuditTrailContributorDAO dao = getDAOInstance(ds); dao.initialize(componentID); return dao; } @Override - protected AuditTrailContributerDAO getDerbyDAO(DatabaseManager dm) { + protected AuditTrailContributorDAO getDerbyDAO(DatabaseManager dm) { return new DerbyAuditTrailContributorDAO(dm); } @Override - protected AuditTrailContributerDAO getPostgresDAO(DatabaseManager dm) { + protected AuditTrailContributorDAO getPostgresDAO(DatabaseManager dm) { return new PostgresAuditTrailContributorDAO(dm); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAO.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDAO.java similarity index 71% rename from bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAO.java rename to bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDAO.java index f422fb6a9..872078e09 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributerDAO.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDAO.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -42,46 +42,43 @@ import static org.bitrepository.service.audit.AuditDatabaseConstants.ACTOR_GUID; import static org.bitrepository.service.audit.AuditDatabaseConstants.ACTOR_NAME; import static org.bitrepository.service.audit.AuditDatabaseConstants.ACTOR_TABLE; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_ACTOR_GUID; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_AUDIT; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_FILE_GUID; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_FINGERPRINT; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_INFORMATION; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_OPERATION; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_OPERATIONID; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_OPERATION_DATE; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_SEQUENCE_NUMBER; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_TABLE; -import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_COLLECTIONID; -import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_FILEID; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_ACTOR_GUID; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_AUDIT; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_FILE_GUID; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_FINGERPRINT; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_INFORMATION; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_OPERATION; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_OPERATIONID; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_OPERATION_DATE; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_SEQUENCE_NUMBER; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_TABLE; +import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_COLLECTION_ID; +import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_FILE_ID; import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_GUID; import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_TABLE; /** * Access interface for communication with the audit trail database. - * + *

      * In the case of 'All-FileIDs', then the 'fileID' is given the string-value 'null'. */ -public abstract class AuditTrailContributerDAO implements AuditTrailManager { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The connection to the database.*/ - private DBConnector dbConnector; - /** The componentID.*/ +public abstract class AuditTrailContributorDAO implements AuditTrailManager { + private final Logger log = LoggerFactory.getLogger(getClass()); + private final DBConnector dbConnector; private String componentID; /** - * Constructor. * @param manager the database manager */ - public AuditTrailContributerDAO(DatabaseManager manager) { + public AuditTrailContributorDAO(DatabaseManager manager) { this.dbConnector = manager.getConnector(); getConnection(); } - + /** - * Initialization method, needed to setup the instance. - * @param componentID The ID of the component using the AuditTrailContributerDAO instance + * Initialization method, needed to set up the instance. + * + * @param componentID The ID of the component using the AuditTrailContributorDAO instance */ public void initialize(String componentID) { this.componentID = componentID; @@ -89,69 +86,69 @@ public void initialize(String componentID) { /** * Retrieve the connection to the database. - * TODO improve performance (only reconnect every-so-often)... + * TODO improve performance (only reconnect every-so-often)... + * * @return The connection to the database. * @throws IllegalStateException if the connection could not be established */ protected Connection getConnection() throws IllegalStateException { try { - Connection dbConnection = dbConnector.getConnection(); - return dbConnection; + return dbConnector.getConnection(); } catch (Exception e) { throw new IllegalStateException("Could not instantiate the database", e); } } - + @Override public void addAuditEvent(String collectionID, String fileID, String actor, String info, String auditTrail, - FileAction operation, String operationID, String fingerprint) { + FileAction operation, String operationID, String fingerprint) { ArgumentValidator.checkNotNull(collectionID, "String collectionID"); ArgumentValidator.checkNotNull(operation, "FileAction operation"); addAuditEvent(collectionID, fileID, new Date(), actor, info, auditTrail, operation, operationID, fingerprint); } - + /** - * Inner method to handle the insertion of audit events. - * The inner method is separated out to be able to test specifics timestamps. + * Inner method to handle the insertion of audit events. + * The inner method is separated out to be able to test specifics timestamps. */ - protected void addAuditEvent(String collectionID, String fileID, Date auditTime, String actor, String info, - String auditTrail, FileAction operation, String operationID, String fingerprint) { + protected void addAuditEvent(String collectionID, String fileID, Date auditTime, String actor, String info, + String auditTrail, FileAction operation, String operationID, String fingerprint) { ArgumentValidator.checkNotNull(collectionID, "String collectionID"); ArgumentValidator.checkNotNull(operation, "FileAction operation"); log.debug("Inserting an audit event for file '" + fileID + "', from actor '" + actor + "' performing operation '" + operation + "', with the audit trail information '" + auditTrail + "'"); long fileGuid; - if(fileID == null || fileID.isEmpty()) { + if (fileID == null || fileID.isEmpty()) { fileGuid = retrieveFileGuid(collectionID, "null"); } else { fileGuid = retrieveFileGuid(collectionID, fileID); } long actorGuid; - if(actor == null || actor.isEmpty()) { + if (actor == null || actor.isEmpty()) { actorGuid = retrieveActorGuid("null"); } else { actorGuid = retrieveActorGuid(actor); } - if(auditTrail == null) { + if (auditTrail == null) { auditTrail = ""; } - if(info == null) { + if (info == null) { info = ""; } - if(operationID == null) { + if (operationID == null) { operationID = ""; } - if(fingerprint == null) { + if (fingerprint == null) { fingerprint = ""; } - synchronized(this) { - String insertSql = "INSERT INTO " + AUDITTRAIL_TABLE + " ( " + AUDITTRAIL_FILE_GUID + " , " - + AUDITTRAIL_ACTOR_GUID + " , " + AUDITTRAIL_OPERATION + " , " + AUDITTRAIL_OPERATION_DATE + " , " - + AUDITTRAIL_AUDIT + " , " + AUDITTRAIL_INFORMATION + " , " + AUDITTRAIL_OPERATIONID + " , " + - AUDITTRAIL_FINGERPRINT + " ) VALUES ( ? , ? , ? , ? , ? , ? , ? , ?)"; + synchronized (this) { + String insertSql = "INSERT INTO " + AUDIT_TRAIL_TABLE + " ( " + AUDIT_TRAIL_FILE_GUID + " , " + + AUDIT_TRAIL_ACTOR_GUID + " , " + AUDIT_TRAIL_OPERATION + " , " + AUDIT_TRAIL_OPERATION_DATE + " , " + + AUDIT_TRAIL_AUDIT + " , " + AUDIT_TRAIL_INFORMATION + " , " + AUDIT_TRAIL_OPERATIONID + " , " + + AUDIT_TRAIL_FINGERPRINT + " ) VALUES ( ? , ? , ? , ? , ? , ? , ? , ?)"; DatabaseUtils.executeStatement(dbConnector, insertSql, fileGuid, actorGuid, operation.toString(), auditTime.getTime(), auditTrail, info, operationID, fingerprint); } @@ -159,23 +156,24 @@ protected void addAuditEvent(String collectionID, String fileID, Date auditTime, @Override public AuditTrailDatabaseResults getAudits(String collectionID, String fileID, Long minSeqNumber, - Long maxSeqNumber, Date minDate, Date maxDate, Long maxNumberOfResults) { + Long maxSeqNumber, Date minDate, Date maxDate, Long maxNumberOfResults) { return extractEvents(new AuditTrailExtractor(collectionID, fileID, minSeqNumber, maxSeqNumber, minDate, maxDate, maxNumberOfResults)); } /** - * Extracts the largest sequence number from the database. + * Extracts the largest sequence number from the database. + * * @return The largest sequence number. If no entry exists, then zero is returned. */ public Long extractLargestSequenceNumber() { - String sql = "SELECT " + AUDITTRAIL_SEQUENCE_NUMBER + " FROM " + AUDITTRAIL_TABLE + " ORDER BY " - + AUDITTRAIL_SEQUENCE_NUMBER + " DESC"; + String sql = "SELECT " + AUDIT_TRAIL_SEQUENCE_NUMBER + " FROM " + AUDIT_TRAIL_TABLE + " ORDER BY " + + AUDIT_TRAIL_SEQUENCE_NUMBER + " DESC"; try (Connection conn = getConnection(); PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql)) { try (ResultSet res = ps.executeQuery()) { - if(!res.next()) { + if (!res.next()) { return 0L; } return res.getLong(1); @@ -186,15 +184,17 @@ public Long extractLargestSequenceNumber() { } } - + /** * Method to obtain the database specific sql to limit the number of results. - * @return string The database specific SQL to limit the number of results in a database query + * + * @return string The database specific SQL to limit the number of results in a database query */ protected abstract String createQueryResultsLimit(); /** * Extracts the the audit trail information based on the given sql query and arguments. + * * @param extractor The entity for extracting the audit trails. * @return The extracted audit trails. */ @@ -209,29 +209,29 @@ private AuditTrailDatabaseResults extractEvents(AuditTrailExtractor extractor) { final int infoPosition = 7; final int operationIDPosition = 8; final int fingerprintPosition = 9; - - String sql = "SELECT " + AUDITTRAIL_SEQUENCE_NUMBER + ", " - + FILE_FILEID + " , " - + AUDITTRAIL_ACTOR_GUID + " , " - + AUDITTRAIL_OPERATION_DATE + " , " - + AUDITTRAIL_OPERATION + " , " - + AUDITTRAIL_AUDIT + " , " - + AUDITTRAIL_INFORMATION + " , " - + AUDITTRAIL_OPERATIONID + " , " - + AUDITTRAIL_FINGERPRINT - + " FROM " - + AUDITTRAIL_TABLE + " JOIN " + FILE_TABLE - + " ON " + AUDITTRAIL_TABLE + "." + AUDITTRAIL_FILE_GUID + " = " - + FILE_TABLE + "." + FILE_GUID - + " " + extractor.createRestriction(); + + String sql = "SELECT " + AUDIT_TRAIL_SEQUENCE_NUMBER + ", " + + FILE_FILE_ID + " , " + + AUDIT_TRAIL_ACTOR_GUID + " , " + + AUDIT_TRAIL_OPERATION_DATE + " , " + + AUDIT_TRAIL_OPERATION + " , " + + AUDIT_TRAIL_AUDIT + " , " + + AUDIT_TRAIL_INFORMATION + " , " + + AUDIT_TRAIL_OPERATIONID + " , " + + AUDIT_TRAIL_FINGERPRINT + + " FROM " + + AUDIT_TRAIL_TABLE + " JOIN " + FILE_TABLE + + " ON " + AUDIT_TRAIL_TABLE + "." + AUDIT_TRAIL_FILE_GUID + " = " + + FILE_TABLE + "." + FILE_GUID + + " " + extractor.createRestriction(); AuditTrailDatabaseResults auditResults = new AuditTrailDatabaseResults(); try (Connection conn = getConnection(); PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql, extractor.getArguments())) { conn.setAutoCommit(false); ps.setFetchSize(100); - try (ResultSet results = ps.executeQuery()) { - while(results.next()) { + try (ResultSet results = ps.executeQuery()) { + while (results.next()) { AuditTrailEvent event = new AuditTrailEvent(); event.setSequenceNumber(BigInteger.valueOf(results.getLong(sequencePosition))); @@ -246,9 +246,9 @@ private AuditTrailDatabaseResults extractEvents(AuditTrailExtractor extractor) { event.setCertificateID(results.getString(fingerprintPosition)); auditResults.addAuditTrailEvent(event); } - + Long maxResults = extractor.getMaxResults(); - if(maxResults != null && auditResults.getAuditTrailEvents().getAuditTrailEvent().size() >= maxResults) { + if (maxResults != null && auditResults.getAuditTrailEvents().getAuditTrailEvent().size() >= maxResults) { log.debug("More than the maximum {} results found.", maxResults); auditResults.reportMoreResultsFound(); } @@ -267,24 +267,24 @@ private AuditTrailDatabaseResults extractEvents(AuditTrailExtractor extractor) { * Retrieve the guid for a given file id. If the file id does not exist within the table, then it is created. * * @param collectionID The collection id for the file. - * @param fileID The id of the file to retrieve. + * @param fileID The id of the file to retrieve. * @return The guid for the given file id. */ private synchronized long retrieveFileGuid(String collectionID, String fileID) { - String sqlRetrieve = "SELECT " + FILE_GUID + " FROM " + FILE_TABLE + " WHERE " + FILE_FILEID + " = ? AND " - + FILE_COLLECTIONID + " = ?"; + String sqlRetrieve = "SELECT " + FILE_GUID + " FROM " + FILE_TABLE + " WHERE " + FILE_FILE_ID + " = ? AND " + + FILE_COLLECTION_ID + " = ?"; Long guid = DatabaseUtils.selectLongValue(dbConnector, sqlRetrieve, fileID, collectionID); - if(guid == null) { + if (guid == null) { log.debug("Inserting fileid '" + fileID + "' into the file table."); - String sqlInsert = "INSERT INTO " + FILE_TABLE + " ( " + FILE_FILEID + " , " + FILE_COLLECTIONID + String sqlInsert = "INSERT INTO " + FILE_TABLE + " ( " + FILE_FILE_ID + " , " + FILE_COLLECTION_ID + " ) VALUES ( ? , ? )"; DatabaseUtils.executeStatement(dbConnector, sqlInsert, fileID, collectionID); guid = DatabaseUtils.selectLongValue(dbConnector, sqlRetrieve, fileID, collectionID); } - + assert guid != null; return guid; } @@ -299,19 +299,20 @@ private synchronized long retrieveActorGuid(String actorName) { Long guid = DatabaseUtils.selectLongValue(dbConnector, sqlRetrieve, actorName); - if(guid == null) { + if (guid == null) { log.debug("Inserting actor '" + actorName + "' into the actor table."); String sqlInsert = "INSERT INTO " + ACTOR_TABLE + " ( " + ACTOR_NAME + " ) VALUES ( ? )"; DatabaseUtils.executeStatement(dbConnector, sqlInsert, actorName); guid = DatabaseUtils.selectLongValue(dbConnector, sqlRetrieve, actorName); } - + assert guid != null; return guid; } /** - * Retrieves a name of an actor based on the guid. + * Retrieves a name of an actor based on the guid. + * * @param actorGuid The guid of the actor. * @return The name of the actor corresponding to guid. */ @@ -322,23 +323,16 @@ private String retrieveActorName(long actorGuid) { } /** - * Class for encapsulating the request for extracting. + * Private class for encapsulating the request for extracting. */ private class AuditTrailExtractor { - /** The collection id limitation for the request.*/ - private String collectionID; - /** The file id limitation for the request. */ - private String fileID; - /** The minimum sequence number limitation for the request.*/ - private Long minSeqNumber; - /** The maximum sequence number limitation for the request.*/ - private Long maxSeqNumber; - /** The minimum date limitation for the request.*/ - private Date minDate; - /** The maxmimum date limitation for the request.*/ - private Date maxDate; - /** The maximum number of results. */ - private Long maxResults; + private final String collectionID; + private final String fileID; + private final Long minSeqNumber; + private final Long maxSeqNumber; + private final Date minDate; + private final Date maxDate; + private final Long maxResults; /** * @param collectionID The id of the collection to retrieve the audit trails for. @@ -359,7 +353,7 @@ public AuditTrailExtractor(String collectionID, String fileID, Long minSeqNumber this.maxDate = maxDate; this.maxResults = maxResults; } - + /** * @return the maximum number of results as a Long. */ @@ -372,46 +366,46 @@ public Long getMaxResults() { */ public String createRestriction() { // Handle the case with no restrictions. - if(collectionID == null && fileID == null && minSeqNumber == null && maxSeqNumber == null + if (collectionID == null && fileID == null && minSeqNumber == null && maxSeqNumber == null && minDate == null && maxDate == null && maxResults == null) { return ""; } StringBuilder res = new StringBuilder(); - if(collectionID != null) { + if (collectionID != null) { nextArgument(res); - res.append(FILE_COLLECTIONID + " = ?"); + res.append(FILE_COLLECTION_ID + " = ?"); } - if(fileID != null) { + if (fileID != null) { nextArgument(res); - res.append(FILE_FILEID + " = ?"); + res.append(FILE_FILE_ID + " = ?"); } - if(minSeqNumber != null) { + if (minSeqNumber != null) { nextArgument(res); - res.append(AUDITTRAIL_SEQUENCE_NUMBER + " >= ?"); + res.append(AUDIT_TRAIL_SEQUENCE_NUMBER + " >= ?"); } - if(maxSeqNumber != null) { + if (maxSeqNumber != null) { nextArgument(res); - res.append(AUDITTRAIL_SEQUENCE_NUMBER + " <= ?"); + res.append(AUDIT_TRAIL_SEQUENCE_NUMBER + " <= ?"); } - if(minDate != null) { + if (minDate != null) { nextArgument(res); - res.append(AUDITTRAIL_OPERATION_DATE + " >= ?"); + res.append(AUDIT_TRAIL_OPERATION_DATE + " >= ?"); } - if(maxDate != null) { + if (maxDate != null) { nextArgument(res); - res.append(AUDITTRAIL_OPERATION_DATE + " <= ?"); + res.append(AUDIT_TRAIL_OPERATION_DATE + " <= ?"); } - - res.append(" ORDER BY " + AUDITTRAIL_SEQUENCE_NUMBER); - - if(maxResults != null) { + + res.append(" ORDER BY " + AUDIT_TRAIL_SEQUENCE_NUMBER); + + if (maxResults != null) { res.append(createQueryResultsLimit()); } @@ -420,10 +414,11 @@ public String createRestriction() { /** * Adds either ' AND ' or 'WHERE ' depending on whether it is the first restriction. + * * @param res The StringBuilder where the restrictions are combined. */ private void nextArgument(StringBuilder res) { - if(res.length() > 0) { + if (res.length() > 0) { res.append(" AND "); } else { res.append("WHERE "); @@ -435,28 +430,28 @@ private void nextArgument(StringBuilder res) { */ public Object[] getArguments() { List res = new ArrayList<>(); - if(collectionID != null) { + if (collectionID != null) { res.add(collectionID); } - if(fileID != null) { + if (fileID != null) { res.add(fileID); } - if(minSeqNumber != null) { + if (minSeqNumber != null) { res.add(minSeqNumber); } - if(maxSeqNumber != null) { + if (maxSeqNumber != null) { res.add(maxSeqNumber); } - if(minDate != null) { + if (minDate != null) { res.add(minDate.getTime()); } - if(maxDate != null) { + if (maxDate != null) { res.add(maxDate.getTime()); } - if(maxResults != null) { + if (maxResults != null) { res.add(maxResults); } - + return res.toArray(); } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrator.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrator.java index 176fc5632..67c284627 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrator.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrator.java @@ -5,85 +5,76 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service.audit; -import java.util.Map; - import org.bitrepository.service.database.DBConnector; import org.bitrepository.service.database.DatabaseMigrator; import org.bitrepository.service.database.DatabaseUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Map; + import static org.bitrepository.service.audit.AuditDatabaseConstants.DATABASE_VERSION_ENTRY; import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_TABLE; /** - * Migration class for the AuditTrailContributorDatabase of the ReferencePillar, ChecksumPillar + * Migration class for the AuditTrailContributorDatabase of the ReferencePillar, ChecksumPillar * and the IntegrityService. * Will only try to perform the migration on an embedded derby database. */ public class AuditTrailContributorDatabaseMigrator extends DatabaseMigrator { - /** The log.*/ private static final Logger log = LoggerFactory.getLogger(DatabaseUtils.class); - - /** The name of the script for updating the database from version 1 to 2.*/ private static final String UPDATE_SCRIPT_VERSION_1_TO_2 = "sql/derby/auditContributorDBUpdate1to2.sql"; - /** The name of the script for updating the database from version 2 to 3.*/ private static final String UPDATE_SCRIPT_VERSION_2_TO_3 = "sql/derby/auditContributorDBUpdate2to3.sql"; - /** The name of the script for updating the database from version 3 to 4.*/ private static final String UPDATE_SCRIPT_VERSION_3_TO_4 = "sql/derby/auditContributorDBUpdate3to4.sql"; - /** The name of the script for updating the database from version 4 to 5.*/ private static final String UPDATE_SCRIPT_VERSION_4_TO_5 = "sql/derby/auditContributorDBUpdate4to5.sql"; - /** The current version of the database. */ public static final int CURRENT_VERSION = 5; - + /** - * Constructor. * @param connector connection to the database. */ public AuditTrailContributorDatabaseMigrator(DBConnector connector) { super(connector); } - + @Override public void migrate() { Map versions = getTableVersions(); - - if(!versions.containsKey(FILE_TABLE)) { - throw new IllegalStateException("The database does not contain '" + FILE_TABLE - + "' table as required."); + + if (!versions.containsKey(FILE_TABLE)) { + throw new IllegalStateException("The database does not contain '" + FILE_TABLE + "' table as required."); } - if(versions.get(FILE_TABLE) == 1) { + if (versions.get(FILE_TABLE) == 1) { log.warn("Migrating AuditContributorDB from version 1 to 2."); migrateDerbyDatabase(UPDATE_SCRIPT_VERSION_1_TO_2); } - - if(!versions.containsKey(DATABASE_VERSION_ENTRY) || versions.get(DATABASE_VERSION_ENTRY) < 3) { + + if (!versions.containsKey(DATABASE_VERSION_ENTRY) || versions.get(DATABASE_VERSION_ENTRY) < 3) { log.warn("Migrating AuditContributorDB from version 2 to 3."); migrateDerbyDatabase(UPDATE_SCRIPT_VERSION_2_TO_3); } - if(!versions.containsKey(DATABASE_VERSION_ENTRY) || versions.get(DATABASE_VERSION_ENTRY) < 4) { + if (!versions.containsKey(DATABASE_VERSION_ENTRY) || versions.get(DATABASE_VERSION_ENTRY) < 4) { log.warn("Migrating AuditContributorDB from version 3 to 4."); migrateDerbyDatabase(UPDATE_SCRIPT_VERSION_3_TO_4); } - - if(!versions.containsKey(DATABASE_VERSION_ENTRY) || versions.get(DATABASE_VERSION_ENTRY) < 5) { + + if (!versions.containsKey(DATABASE_VERSION_ENTRY) || versions.get(DATABASE_VERSION_ENTRY) < 5) { log.warn("Migrating AuditContributorDB from version 4 to 5."); migrateDerbyDatabase(UPDATE_SCRIPT_VERSION_4_TO_5); } @@ -92,14 +83,10 @@ public void migrate() { @Override public boolean needsMigration() { Map versions = getTableVersions(); - - if(!versions.containsKey(DATABASE_VERSION_ENTRY)) { + + if (!versions.containsKey(DATABASE_VERSION_ENTRY)) { // Special case, as the first version of the database did not have DATABASE_VERSION_ENTRY! return true; - } else if(versions.get(DATABASE_VERSION_ENTRY) < CURRENT_VERSION) { - return true; - } else { - return false; - } + } else return versions.get(DATABASE_VERSION_ENTRY) < CURRENT_VERSION; } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailDatabaseResults.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailDatabaseResults.java index 2eb516483..76413920a 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailDatabaseResults.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailDatabaseResults.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -31,55 +31,49 @@ * Contains both the audit trails and whether more results was found. */ public class AuditTrailDatabaseResults { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - - /** The collection of audit trail events.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private final AuditTrailEvents events; - /** Whether more results has been reported.*/ private boolean hasMoreResults; - - /** - * Constructor. - */ + public AuditTrailDatabaseResults() { events = new AuditTrailEvents(); hasMoreResults = false; } - + /** * @return The entity for containing the audit trail events. */ public AuditTrailEvents getAuditTrailEvents() { return events; } - + /** * Adding an audit trail event to this result set. + * * @param event The audit trail event to add. */ public void addAuditTrailEvent(AuditTrailEvent event) { log.trace("Adding audit trail event to results: {}", event); events.getAuditTrailEvent().add(event); } - + /** * @return Whether more results has been reported. */ public boolean moreResults() { return hasMoreResults; } - + /** * Sets that more results has been found. */ public void reportMoreResultsFound() { hasMoreResults = true; } - + @Override public String toString() { - return super.toString() + ", contains " + events.getAuditTrailEvent().size() + return super.toString() + ", contains " + events.getAuditTrailEvent().size() + " audit trail events, and " + (hasMoreResults ? "has more results" : "does not have more results"); } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailManager.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailManager.java index d58c757eb..b00873f99 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailManager.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/AuditTrailManager.java @@ -1,63 +1,65 @@ /* * #%L * Bitmagasin integrationstest - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service.audit; -import java.util.Date; - import org.bitrepository.bitrepositoryelements.FileAction; +import java.util.Date; + /** * The interface for the audit trail handler. */ public interface AuditTrailManager { /** * Adds an audit trail event to the manager. - * @param collectionID The id of the collection for whom the audit applies. - * @param fileID The id of the file, where the operation has been performed. - * Use the argument null for indicating all file ids. - * @param actor The name of the actor. - * @param info Information about the reason for the audit trail to be logged. - * @param auditTrail The string for the audit trail information from the message performing the operation. - * @param operation The performed operation. - * @param operationID The conversationID of the operation + * + * @param collectionID The id of the collection for whom the audit applies. + * @param fileID The id of the file, where the operation has been performed. + * Use the argument null for indicating all file ids. + * @param actor The name of the actor. + * @param info Information about the reason for the audit trail to be logged. + * @param auditTrail The string for the audit trail information from the message performing the operation. + * @param operation The performed operation. + * @param operationID The conversationID of the operation * @param certificateID The certificate fingerprint for the message. */ void addAuditEvent(String collectionID, String fileID, String actor, String info, String auditTrail, FileAction operation, String operationID, String certificateID); - + /** * Method for extracting all the audit trails. - * @param collectionID The id of the collection for whom the audit applies. - * @param fileID [OPTIONAL] The id of the file to request audits for. - * @param minSeqNumber [OPTIONAL] The lower sequence number requested. - * @param maxSeqNumber [OPTIONAL] The upper sequence number requested. - * @param minDate [OPTIONAL] The earliest date requested. - * @param maxDate [OPTIONAL] The newest date requested. + * + * @param collectionID The id of the collection for whom the audit applies. + * @param fileID [OPTIONAL] The id of the file to request audits for. + * @param minSeqNumber [OPTIONAL] The lower sequence number requested. + * @param maxSeqNumber [OPTIONAL] The upper sequence number requested. + * @param minDate [OPTIONAL] The earliest date requested. + * @param maxDate [OPTIONAL] The newest date requested. * @param maxNumberOfResults [OPTIONAL] The maximum number of results. * @return The audit trails corresponding to the requested arguments. */ AuditTrailDatabaseResults getAudits(String collectionID, String fileID, Long minSeqNumber, Long maxSeqNumber, Date minDate, - Date maxDate, Long maxNumberOfResults); + Date maxDate, Long maxNumberOfResults); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/DerbyAuditTrailContributorDAO.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/DerbyAuditTrailContributorDAO.java index 68e8722b7..fc233b978 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/DerbyAuditTrailContributorDAO.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/DerbyAuditTrailContributorDAO.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -24,9 +24,9 @@ import org.bitrepository.service.database.DatabaseManager; /** - * AuditTrailContributerDAO which knows how to ask Derby to limit the number of results returned. + * AuditTrailContributorDAO which knows how to ask Derby to limit the number of results returned. */ -public class DerbyAuditTrailContributorDAO extends AuditTrailContributerDAO { +public class DerbyAuditTrailContributorDAO extends AuditTrailContributorDAO { public DerbyAuditTrailContributorDAO(DatabaseManager manager) { super(manager); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/audit/PostgresAuditTrailContributorDAO.java b/bitrepository-service/src/main/java/org/bitrepository/service/audit/PostgresAuditTrailContributorDAO.java index 925277124..48c725cae 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/audit/PostgresAuditTrailContributorDAO.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/audit/PostgresAuditTrailContributorDAO.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -24,10 +24,10 @@ import org.bitrepository.service.database.DatabaseManager; /** - * AuditTrailContributerDAO which knows how to ask Postgres to limit the number of results returned. + * AuditTrailContributorDAO which knows how to ask Postgres to limit the number of results returned. */ -public class PostgresAuditTrailContributorDAO extends AuditTrailContributerDAO { +public class PostgresAuditTrailContributorDAO extends AuditTrailContributorDAO { public PostgresAuditTrailContributorDAO(DatabaseManager manager) { super(manager); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/AbstractContributorMediator.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/AbstractContributorMediator.java index bd0548ab8..9827afd5a 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/AbstractContributorMediator.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/AbstractContributorMediator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -40,18 +40,13 @@ */ @SuppressWarnings("rawtypes") public abstract class AbstractContributorMediator implements ContributorMediator { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The map of request handlers. Mapping between request name and message handler for the given request.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private final Map handlerMap = new HashMap<>(); - /** The message bus.*/ private final MessageBus messageBus; - /** The intermediate message handler for retrieving the messages from the messagebus. */ private final GeneralRequestHandler messageHandler; /** - * Constructor. - * @param messageBus The messagebus for this mediator. + * @param messageBus The message-bus for this mediator. */ public AbstractContributorMediator(MessageBus messageBus) { this.messageBus = messageBus; @@ -71,7 +66,7 @@ public final void start() { } /** - * @return The set of RequestHandlers used for this contributor. + * @return The a RequestHandler array used for this contributor. */ protected abstract RequestHandler[] createListOfHandlers(); @@ -79,13 +74,14 @@ public final void start() { * @return The concrete context used for this contributor. */ protected abstract ContributorContext getContext(); - + /** - * Make the inheriting class create the environment for safely handling the request. + * Make the inheriting class create the environment for safely handling the request. * E.g. creating the specific fault barrier. - * @param request The request to handle. + * + * @param request The request to handle. * @param messageContext the message context - * @param handler The handler for the request. + * @param handler The handler for the request. */ protected abstract void handleRequest(MessageRequest request, MessageContext messageContext, RequestHandler handler); @@ -103,17 +99,17 @@ public void onMessage(Message message, MessageContext messageContext) { if (MessageUtils.isIdentifyRequest(message)) { log.trace("Received unhandled identity request: \n{}", message); } else - log.warn("Unable to handle messages of this type: \n{}", message); + log.warn("Unable to handle messages of this type: \n{}", message); } } else { log.trace("Can only handle message requests, but received: \n{}", message); } } } - + /** - * Closes the mediator by removing all the message handler. - */ + * Closes the mediator by removing all the message handler. + */ @Override public void close() { messageBus.removeListener(getContext().getSettings().getCollectionDestination(), messageHandler); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorContext.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorContext.java index 59b04a9de..9caacacd0 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorContext.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorContext.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -36,7 +36,8 @@ public class ContributorContext { public ContributorContext(ResponseDispatcher responseDispatcher, AlarmDispatcher alarmDispatcher, Settings settings, FileExchange fileExchange) { - this.responseDispatcher = responseDispatcher; this.alarmDispatcher = alarmDispatcher; + this.responseDispatcher = responseDispatcher; + this.alarmDispatcher = alarmDispatcher; this.settings = settings; this.fileExchange = fileExchange; } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorMediator.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorMediator.java index c00b776d6..1a2f0897e 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorMediator.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ContributorMediator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -30,7 +30,7 @@ public interface ContributorMediator { * Start the mediator before use. */ void start(); - + /** * Close the mediator after use. */ diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/MessageDispatcher.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/MessageDispatcher.java index 7bf85fdb8..fff8b90ad 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/MessageDispatcher.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/MessageDispatcher.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -28,7 +28,7 @@ import org.bitrepository.protocol.messagebus.MessageSender; /** - * Provides the general functionality for sending reponses from a pillar. + * Provides the general functionality for sending responses from a pillar. */ public class MessageDispatcher { protected final Settings settings; @@ -52,7 +52,7 @@ public MessageDispatcher(Settings settings, MessageSender sender) { *
    • Version
    • * * - * @param message The message which only needs the basic information to be send. + * @param message The message which only needs the basic information to be sent. */ protected void dispatchMessage(Message message) { message.setFrom(settings.getComponentID()); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ResponseDispatcher.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ResponseDispatcher.java index 33c80c6e8..c9ae5b3fb 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ResponseDispatcher.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/ResponseDispatcher.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,7 +27,7 @@ import org.bitrepository.protocol.messagebus.MessageSender; /** - * Provides the general functionality for sending reponses from a contributor. + * Provides the general functionality for sending responses from a contributor. */ public class ResponseDispatcher extends MessageDispatcher { @@ -49,8 +49,8 @@ public ResponseDispatcher(Settings settings, MessageSender sender) { *
    • Version
    • * * - * @param response The response which only needs the basic information to be send. - * @param request The original request to respond to. + * @param response The response which only needs the basic information to be sent. + * @param request The original request to respond to. */ public void dispatchResponse(MessageResponse response, MessageRequest request) { response.setCorrelationID(request.getCorrelationID()); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/SimpleContributorMediator.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/SimpleContributorMediator.java index 86b15c6a3..69979e24b 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/SimpleContributorMediator.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/SimpleContributorMediator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -46,19 +46,18 @@ /** * Simple implementation of a contributor mediator. * It supports the handling of the GetStatus and GetAuditTrail operations. - * - * If the optional AuditTrailManager is given as argument, then this mediator will also be able to handle the - * GetAuditTrails identification and operation. + *

      + * If the optional AuditTrailManager is given as argument, then this mediator will also be able to handle the + * GetAuditTrails identification and operation. */ public class SimpleContributorMediator extends AbstractContributorMediator { private final Logger log = LoggerFactory.getLogger(getClass()); private final ContributorContext context; - private AuditTrailManager auditManager; - + private final AuditTrailManager auditManager; + /** - * Constructor. - * @param messageBus The messagebus for the mediator. - * @param settings the settings for the mediator. + * @param messageBus The message-bus for the mediator. + * @param settings the settings for the mediator. * @param auditManager [OPTIONAL] The manager of audit trails. Only if the contributor has audit trails. * @param fileExchange the file exchange */ @@ -66,9 +65,9 @@ public SimpleContributorMediator( MessageBus messageBus, Settings settings, AuditTrailManager auditManager, FileExchange fileExchange) { super(messageBus); context = new ContributorContext( - new ResponseDispatcher(settings, messageBus), - new AlarmDispatcher(settings, messageBus), - settings, fileExchange); + new ResponseDispatcher(settings, messageBus), + new AlarmDispatcher(settings, messageBus), + settings, fileExchange); this.auditManager = auditManager; } @@ -76,24 +75,24 @@ public SimpleContributorMediator( @Override protected RequestHandler[] createListOfHandlers() { List handlers = new ArrayList<>(); - + handlers.add(new IdentifyContributorsForGetStatusRequestHandler(getContext())); handlers.add(new GetStatusRequestHandler(getContext())); - - if(auditManager != null) { + + if (auditManager != null) { handlers.add(new IdentifyContributorsForGetAuditTrailsRequestHandler(getContext())); handlers.add(new GetAuditTrailsRequestHandler(getContext(), auditManager)); } - - return handlers.toArray(new RequestHandler[handlers.size()]); + + return handlers.toArray(new RequestHandler[0]); } - + @Override protected ContributorContext getContext() { return context; } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @Override protected void handleRequest(MessageRequest request, MessageContext messageContext, RequestHandler handler) { try { @@ -108,7 +107,7 @@ protected void handleRequest(MessageRequest request, MessageContext messageConte ResponseInfo responseInfo = new ResponseInfo(); responseInfo.setResponseCode(ResponseCode.FAILURE); responseInfo.setResponseText(e.toString()); - + MessageResponse response = handler.generateFailedResponse(request); response.setResponseInfo(responseInfo); context.getResponseDispatcher().dispatchResponse(response, request); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/AbstractRequestHandler.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/AbstractRequestHandler.java index 7da84a0f8..1b4a21239 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/AbstractRequestHandler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/AbstractRequestHandler.java @@ -5,50 +5,43 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service.contributor.handler; -import java.math.BigInteger; - import org.bitrepository.bitrepositorymessages.MessageRequest; import org.bitrepository.bitrepositorymessages.MessageResponse; import org.bitrepository.common.ArgumentValidator; import org.bitrepository.protocol.ProtocolVersionLoader; import org.bitrepository.service.contributor.ContributorContext; +import java.math.BigInteger; + /** * The interface for the request handlers. + * * @param The request class for the specific type of requests to be handled by this request handler. */ public abstract class AbstractRequestHandler implements RequestHandler { - /** The constant for the VERSION of the messages.*/ protected static final BigInteger VERSION = ProtocolVersionLoader.loadProtocolVersion().getVersion(); - /** The constant for the MIN_VERSION of the messages.*/ protected static final BigInteger MIN_VERSION = ProtocolVersionLoader.loadProtocolVersion().getMinVersion(); - - /** The classpath to the 'xsd'.*/ protected static final String XSD_CLASSPATH = "xsd/"; - /** The name of the XSD containing the BitRepositoryData elements. */ protected static final String XSD_BR_DATA = "BitRepositoryData.xsd"; - - /** The context for the contributor.*/ private final ContributorContext context; - + /** - * Constructor. * @param context The context for this contributor. */ protected AbstractRequestHandler(ContributorContext context) { @@ -65,7 +58,8 @@ protected ContributorContext getContext() { /** * Delegates to the response dispatchers dispatchResponse method. - * @param request the request + * + * @param request the request * @param response the response */ protected void dispatchResponse(MessageResponse response, T request) { @@ -74,10 +68,11 @@ protected void dispatchResponse(MessageResponse response, T request) { /** * Validates that the collectionID has been set. + * * @param request The request to check the collectionID for. */ protected void validateCollectionID(T request) { - if(!request.isSetCollectionID()) { + if (!request.isSetCollectionID()) { throw new IllegalArgumentException(request.getClass().getSimpleName() + "'s requires a CollectionID"); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetAuditTrailsRequestHandler.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetAuditTrailsRequestHandler.java index 51aec3142..1800faa18 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetAuditTrailsRequestHandler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetAuditTrailsRequestHandler.java @@ -5,33 +5,22 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service.contributor.handler; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Date; - -import javax.xml.bind.JAXBException; - import org.apache.activemq.util.ByteArrayInputStream; import org.bitrepository.bitrepositorydata.GetAuditTrailsResults; import org.bitrepository.bitrepositoryelements.ResponseCode; @@ -54,18 +43,25 @@ import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; +import javax.xml.bind.JAXBException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Date; + /** * Class for handling the GetAuditTrails operation. */ public class GetAuditTrailsRequestHandler extends AbstractRequestHandler { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The audit trail manager.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private final AuditTrailManager auditManager; - + /** - * Constructor. - * @param context The context of the message handler. + * @param context The context of the message handler. * @param auditManager the audit manager */ public GetAuditTrailsRequestHandler(ContributorContext context, AuditTrailManager auditManager) { @@ -95,24 +91,24 @@ public MessageResponse generateFailedResponse(GetAuditTrailsRequest request) { /** * Method for validating the content of the message. + * * @param message The message requesting the operation, which should be validated. * @throws InvalidMessageException if the message was invalid */ protected void validateMessage(GetAuditTrailsRequest message) throws InvalidMessageException { - if(!message.getContributor().equals(getContext().getSettings().getComponentID())) { - throw new InvalidMessageException( - ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE, - "Invalid contributor id."); + if (!message.getContributor().equals(getContext().getSettings().getComponentID())) { + throw new InvalidMessageException(ResponseCode.REQUEST_NOT_UNDERSTOOD_FAILURE, "Invalid contributor id."); } } - + /** * The method for sending a progress response telling, that the operation is about to be performed. + * * @param request The request for the GetStatus operation. */ protected void sendProgressMessage(GetAuditTrailsRequest request) { GetAuditTrailsProgressResponse response = createProgressResponse(request); - + // set missing variables in the request: ResponseInfo ResponseInfo prInfo = new ResponseInfo(); prInfo.setResponseCode(ResponseCode.OPERATION_ACCEPTED_PROGRESS); @@ -121,135 +117,132 @@ protected void sendProgressMessage(GetAuditTrailsRequest request) { getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** * Collect the requested audit trails. + * * @param message The message requesting the collecting of audit trails. * @return The requested audit trails. */ protected AuditTrailDatabaseResults collectAudits(GetAuditTrailsRequest message) { Long minSeq = null; - if(message.getMinSequenceNumber() != null) { + if (message.getMinSequenceNumber() != null) { log.trace("Minimum sequence value: {}", message.getMinSequenceNumber().longValue()); minSeq = message.getMinSequenceNumber().longValue(); } Long maxSeq = null; - if(message.getMaxSequenceNumber() != null) { + if (message.getMaxSequenceNumber() != null) { log.trace("Maximum sequence value: {}", message.getMaxSequenceNumber().longValue()); maxSeq = message.getMaxSequenceNumber().longValue(); } Date minDate = null; - if(message.getMinTimestamp() != null) { + if (message.getMinTimestamp() != null) { log.trace("Minimum date value: {}", message.getMinTimestamp()); minDate = CalendarUtils.convertFromXMLGregorianCalendar(message.getMinTimestamp()); } Date maxDate = null; - if(message.getMaxTimestamp() != null) { + if (message.getMaxTimestamp() != null) { log.trace("Maximum date value: {}", message.getMaxTimestamp()); maxDate = CalendarUtils.convertFromXMLGregorianCalendar(message.getMaxTimestamp()); } Long maxNumberOfResults = null; - if(message.getMaxNumberOfResults() != null) { + if (message.getMaxNumberOfResults() != null) { log.trace("Maximum number of results: {}", message.getMaxNumberOfResults()); maxNumberOfResults = message.getMaxNumberOfResults().longValue(); } - - return auditManager.getAudits(message.getCollectionID(), message.getFileID(), minSeq, maxSeq, minDate, - maxDate, maxNumberOfResults); + + return auditManager.getAudits(message.getCollectionID(), message.getFileID(), minSeq, maxSeq, minDate, maxDate, maxNumberOfResults); } - + /** * Handles the potential upload of the audit trails to a given URL. - * @param message The request for the audit trails, which includes the URL for where the audit trails should be - * uploaded + * + * @param message The request for the audit trails, which includes the URL for where the audit trails should be + * uploaded * @param extractedAuditTrails The extracted audit trails. * @throws InvalidMessageException If the creation, serialization, validation or upload of the file fails. */ - protected void handleUpload(GetAuditTrailsRequest message, AuditTrailDatabaseResults extractedAuditTrails) throws InvalidMessageException { - if(message.getResultAddress() == null || message.getResultAddress().isEmpty()) { + protected void handleUpload(GetAuditTrailsRequest message, AuditTrailDatabaseResults extractedAuditTrails) + throws InvalidMessageException { + if (message.getResultAddress() == null || message.getResultAddress().isEmpty()) { log.trace("The audit trails are not uploaded."); return; } - + log.debug("Creating audit trail file and uploading it."); try { File fileToUpload = createAuditTrailFile(message, extractedAuditTrails); URL uploadUrl = new URL(message.getResultAddress()); - + log.debug("Uploading file: " + fileToUpload.getName() + " to " + uploadUrl.toExternalForm()); getContext().getFileExchange().putFile(new FileInputStream(fileToUpload), uploadUrl); } catch (Exception e) { - throw new InvalidMessageException( - ResponseCode.FILE_TRANSFER_FAILURE, + throw new InvalidMessageException(ResponseCode.FILE_TRANSFER_FAILURE, "Could not handle the creation and upload of the results due to: " + e.getMessage(), e); } } - + /** * Creates a file containing all the audit trails. - * @param request The request for the data. + * + * @param request The request for the data. * @param extractedAuditTrails The extracted audit trails. * @return The file containing the extracted audit trails. - * @throws IOException If something goes wrong when creating the file or finding the XSD. + * @throws IOException If something goes wrong when creating the file or finding the XSD. * @throws JAXBException If the resulting structure cannot be serialized. - * @throws SAXException If the results does not validate against the XSD. + * @throws SAXException If the results does not validate against the XSD. */ - protected File createAuditTrailFile(GetAuditTrailsRequest request, AuditTrailDatabaseResults extractedAuditTrails) + protected File createAuditTrailFile(GetAuditTrailsRequest request, AuditTrailDatabaseResults extractedAuditTrails) throws IOException, JAXBException, SAXException { File checksumResultFile = File.createTempFile(request.getCorrelationID(), new Date().getTime() + ".at"); - + GetAuditTrailsResults results = new GetAuditTrailsResults(); results.setVersion(ProtocolVersionLoader.loadProtocolVersion().getVersion()); results.setMinVersion(ProtocolVersionLoader.loadProtocolVersion().getMinVersion()); results.setCollectionID(request.getCollectionID()); results.getAuditTrailEvents().add(extractedAuditTrails.getAuditTrailEvents()); - OutputStream is = null; - try { - is = new FileOutputStream(checksumResultFile); + try (OutputStream is = new FileOutputStream(checksumResultFile)) { JaxbHelper jaxb = new JaxbHelper(XSD_CLASSPATH, XSD_BR_DATA); String xmlMessage = jaxb.serializeToXml(results); jaxb.validate(new ByteArrayInputStream(xmlMessage.getBytes(StandardCharsets.UTF_8))); is.write(xmlMessage.getBytes(StandardCharsets.UTF_8)); is.flush(); - } finally { - if(is != null) { - is.close(); - } } - + return checksumResultFile; } /** * Method for sending a positive final response. - * @param request The request to respond to. + * + * @param request The request to respond to. * @param auditExtract The retrieved audit trails. */ protected void sendFinalResponse(GetAuditTrailsRequest request, AuditTrailDatabaseResults auditExtract) { GetAuditTrailsFinalResponse response = createFinalResponse(request); ResultingAuditTrails resAuditTrails = new ResultingAuditTrails(); - if(request.getResultAddress() == null) { + if (request.getResultAddress() == null) { resAuditTrails.setAuditTrailEvents(auditExtract.getAuditTrailEvents()); } else { resAuditTrails.setResultAddress(request.getResultAddress()); } - + response.setResultingAuditTrails(resAuditTrails); response.setPartialResult(auditExtract.moreResults()); - + ResponseInfo responseInfo = new ResponseInfo(); responseInfo.setResponseCode(ResponseCode.OPERATION_COMPLETED); response.setResponseInfo(responseInfo); getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** - * Creates a GetStatusProgressResponse based on a GetStatusRequest. Missing the + * Creates a GetStatusProgressResponse based on a GetStatusRequest. Missing the * following fields (besides the ones in dispatchResponse): *
      - ResponseInfo - * + * * @param message The message to base the response upon. * @return The GetStatusProgressResponse based on the request. */ @@ -257,24 +250,25 @@ private GetAuditTrailsProgressResponse createProgressResponse(GetAuditTrailsRequ GetAuditTrailsProgressResponse res = new GetAuditTrailsProgressResponse(); res.setContributor(getContext().getSettings().getComponentID()); res.setResultAddress(message.getResultAddress()); - + return res; } - + /** - * Creates a GetStatusFinalResponse based on a GetStatusRequest. Missing the + * Creates a GetStatusFinalResponse based on a GetStatusRequest. Missing the * following fields (besides the ones in dispatchResponse): *

        *
      • ResponseInfo
      • *
      • ResultingAuditTrails
      • *
      + * * @param request the audit trail request. Ignored * @return The GetStatusFinalResponse based on the request. */ protected GetAuditTrailsFinalResponse createFinalResponse(GetAuditTrailsRequest request) { GetAuditTrailsFinalResponse res = new GetAuditTrailsFinalResponse(); res.setContributor(getContext().getSettings().getComponentID()); - + return res; } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetStatusRequestHandler.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetStatusRequestHandler.java index d65c06b81..5472ae5b1 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetStatusRequestHandler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/GetStatusRequestHandler.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -40,7 +40,6 @@ */ public class GetStatusRequestHandler extends AbstractRequestHandler { /** - * Constructor. * @param context The context for the contributor. */ public GetStatusRequestHandler(ContributorContext context) { @@ -58,20 +57,21 @@ public void processRequest(GetStatusRequest request, MessageContext messageConte responseProgress(request); sendFinalSuccess(request); } - + @Override public GetStatusFinalResponse generateFailedResponse(GetStatusRequest request) { GetStatusFinalResponse response = createFinalResponse(request); response.setResultingStatus(failedStatus()); return response; } - + /** * Validates the content of the message. + * * @param request The message to validate. */ private void validateMessage(GetStatusRequest request) { - if(!request.getContributor().equals(getContext().getSettings().getComponentID())) { + if (!request.getContributor().equals(getContext().getSettings().getComponentID())) { throw new IllegalArgumentException("Illegal argument exception. Expected: " + getContext().getSettings().getComponentID() + ", but it was " + request.getContributor()); } @@ -79,6 +79,7 @@ private void validateMessage(GetStatusRequest request) { /** * Creates and sends the progress response. + * * @param request The request to base the response upon. */ private void responseProgress(GetStatusRequest request) { @@ -87,9 +88,10 @@ private void responseProgress(GetStatusRequest request) { response.setContributor(getContext().getSettings().getComponentID()); getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** * Creates and sends the final response telling about success. + * * @param request The request to base the response upon. */ private void sendFinalSuccess(GetStatusRequest request) { @@ -103,13 +105,13 @@ private void sendFinalSuccess(GetStatusRequest request) { getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** * Creates the final response for the status message. * Missing: *
      ResponseInfo *
      ResultingStatus - * + * * @param request The request to base the response upon. * @return The final response. */ @@ -124,27 +126,27 @@ private GetStatusFinalResponse createFinalResponse(GetStatusRequest request) { */ protected ResultingStatus getStatus() { ResultingStatus res = new ResultingStatus(); - + StatusInfo status = new StatusInfo(); status.setStatusCode(StatusCode.OK); - status.setStatusText("Version: " + getClass().getPackage().getImplementationVersion() + + status.setStatusText("Version: " + getClass().getPackage().getImplementationVersion() + " MessageXML version: " + MessageVersionValidator.getProtocolVersion()); - + res.setStatusInfo(status); res.setStatusTimestamp(CalendarUtils.getNow()); return res; } - + /** * @return Negative status info for the contributor. */ protected ResultingStatus failedStatus() { ResultingStatus res = new ResultingStatus(); - + StatusInfo status = new StatusInfo(); status.setStatusCode(StatusCode.ERROR); status.setStatusText("Unexpected error."); - + res.setStatusInfo(status); res.setStatusTimestamp(CalendarUtils.getNow()); return res; diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetAuditTrailsRequestHandler.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetAuditTrailsRequestHandler.java index 67c005592..4811fede9 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetAuditTrailsRequestHandler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetAuditTrailsRequestHandler.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -33,10 +33,9 @@ /** * Class for handling the identification of this pillar for the purpose of performing the GetStatus operation. */ -public class IdentifyContributorsForGetAuditTrailsRequestHandler +public class IdentifyContributorsForGetAuditTrailsRequestHandler extends AbstractRequestHandler { /** - * Constructor. * @param context The context of the message handler. */ public IdentifyContributorsForGetAuditTrailsRequestHandler(ContributorContext context) { @@ -59,9 +58,10 @@ public void processRequest(IdentifyContributorsForGetAuditTrailsRequest message, public MessageResponse generateFailedResponse(IdentifyContributorsForGetAuditTrailsRequest request) { return createResponse(); } - + /** * Makes a success response for the identification. + * * @param request The request to base the response upon. */ protected void respondSuccessfulIdentification(IdentifyContributorsForGetAuditTrailsRequest request) { @@ -69,20 +69,20 @@ protected void respondSuccessfulIdentification(IdentifyContributorsForGetAuditTr response.setResponseInfo(ResponseInfoUtils.getPositiveIdentification()); getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** * Sends a bad response with the given cause. - * @param request The identification request to respond to. + * + * @param request The identification request to respond to. * @param responseInfo The cause of the bad identification (e.g. which file is missing). */ - protected void respondFailedIdentification(IdentifyContributorsForGetAuditTrailsRequest request, - ResponseInfo responseInfo) { + protected void respondFailedIdentification(IdentifyContributorsForGetAuditTrailsRequest request, ResponseInfo responseInfo) { IdentifyContributorsForGetAuditTrailsResponse response = createResponse(); - + response.setResponseInfo(responseInfo); getContext().getResponseDispatcher().dispatchResponse(response, request); } - + /** * Creates a IdentifyContributorsForGetAuditTrailsResponse based on a * IdentifyContributorsForGetAuditTrailsResponse. The following fields are not inserted: @@ -93,7 +93,6 @@ protected void respondFailedIdentification(IdentifyContributorsForGetAuditTrails * @return The response to the request. */ protected IdentifyContributorsForGetAuditTrailsResponse createResponse() { - IdentifyContributorsForGetAuditTrailsResponse res = new IdentifyContributorsForGetAuditTrailsResponse(); - return res; + return new IdentifyContributorsForGetAuditTrailsResponse(); } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetStatusRequestHandler.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetStatusRequestHandler.java index f1fb7bd78..de9f6e87d 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetStatusRequestHandler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/IdentifyContributorsForGetStatusRequestHandler.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -34,11 +34,10 @@ /** * Handler for the IdentifyContributorsForGetStatusRequest. */ -public class IdentifyContributorsForGetStatusRequestHandler +public class IdentifyContributorsForGetStatusRequestHandler extends AbstractRequestHandler { - + /** - * Constructor. * @param context The context for the contributor. */ public IdentifyContributorsForGetStatusRequestHandler(ContributorContext context) { @@ -60,12 +59,12 @@ public void processRequest(IdentifyContributorsForGetStatusRequest request, Mess @Override public MessageResponse generateFailedResponse(IdentifyContributorsForGetStatusRequest request) { - GetStatusFinalResponse response = new GetStatusFinalResponse(); - return response; + return new GetStatusFinalResponse(); } /** * Creates the default status info for the response. + * * @return The status info for the response. */ protected StatusInfo getStatus() { diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/RequestHandler.java b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/RequestHandler.java index dec8841a9..3c0681d44 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/RequestHandler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/contributor/handler/RequestHandler.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -28,18 +28,21 @@ /** * Provides functionality for handling a single type of request. + * * @param the type request handled by this handler */ public interface RequestHandler { - /** Return the request class which is handled by this handler. + /** + * Return the request class which is handled by this handler. + * * @return the class of requests handled by this RequestHandler - * */ + */ Class getRequestClass(); /** * Implements the concrete handling of a received request. * - * @param request The request to handle. + * @param request The request to handle. * @param messageContext the message context * @throws RequestHandlerException If something goes wrong while handling the */ @@ -48,6 +51,7 @@ public interface RequestHandler { /** * Used for creating responses signaling general failures to handle the request. * The response is missing the response info field. + * * @param request the request to create a response for * @return The failure response. */ diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DBConnector.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DBConnector.java index f65c121e1..7ce64f31c 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DBConnector.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DBConnector.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -23,27 +23,26 @@ import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; -import java.sql.Connection; -import java.sql.SQLException; -import java.util.Properties; import org.bitrepository.common.ArgumentValidator; import org.bitrepository.settings.referencesettings.DatabaseSpecifics; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; + /** * The connector to a database. */ public class DBConnector { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The specifications for connection to the database.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private final DatabaseSpecifics databaseSpecifics; - /** The pool with data sources for the database connections.*/ - private ComboPooledDataSource connectionPool; - + private final ComboPooledDataSource connectionPool; + /** * Constructor. + * * @param databaseSpecifics The specifics for the configuration of the database. */ public DBConnector(DatabaseSpecifics databaseSpecifics) { @@ -54,14 +53,14 @@ public DBConnector(DatabaseSpecifics databaseSpecifics) { this.connectionPool = new ComboPooledDataSource(); initialiseConnectionPool(); } - + /** * @return The class for the driver for the database. */ public String getDatabaseDriverClass() { return databaseSpecifics.getDriverClass(); } - + /** * Initialises the ConnectionPool for the connections to the database. */ @@ -70,14 +69,15 @@ private void initialiseConnectionPool() { log.info("Creating the connection to the database '" + DatabaseUtils.getDatabaseSpecificsDump(databaseSpecifics) + "'."); connectionPool.setDriverClass(databaseSpecifics.getDriverClass()); connectionPool.setJdbcUrl(databaseSpecifics.getDatabaseURL()); - if(databaseSpecifics.isSetUsername()) { + if (databaseSpecifics.isSetUsername()) { connectionPool.setUser(databaseSpecifics.getUsername()); } - if(databaseSpecifics.isSetPassword()) { + if (databaseSpecifics.isSetPassword()) { connectionPool.setPassword(databaseSpecifics.getPassword()); } } catch (Exception e) { - throw new IllegalStateException("Could not connect to the database '" + DatabaseUtils.getDatabaseSpecificsDump(databaseSpecifics) + "'", e); + throw new IllegalStateException( + "Could not connect to the database '" + DatabaseUtils.getDatabaseSpecificsDump(databaseSpecifics) + "'", e); } } @@ -90,9 +90,10 @@ private void silenceC3P0Logger() { p.put("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF"); // or any other System.setProperties(p); } - + /** * Creates and connects to the database. + * * @return The connection to the database. * @throws IllegalStateException if the database connection could not be established */ @@ -100,11 +101,12 @@ public Connection getConnection() throws IllegalStateException { try { return connectionPool.getConnection(); } catch (SQLException e) { - throw new IllegalStateException("Could not establish connection to the database: '" + DatabaseUtils.getDatabaseSpecificsDump(databaseSpecifics) - + "'", e); + throw new IllegalStateException( + "Could not establish connection to the database: '" + DatabaseUtils.getDatabaseSpecificsDump(databaseSpecifics) + + "'", e); } } - + /** * Cleans up after use. */ diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseCreator.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseCreator.java index 94d8101a2..4a8911bf1 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseCreator.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseCreator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -38,14 +38,14 @@ public class DatabaseCreator extends DatabaseMaintainer { /** * Creates a database by running the supplied script. - * @param scriptName The name of the script including path as part of the - * classpath. - * @param databaseSpecifics Specifies where to create the database. * + * @param scriptName The name of the script including path as part of the + * classpath. + * @param databaseSpecifics Specifies where to create the database. */ protected void createDatabase(DatabaseSpecifics databaseSpecifics, String scriptName) { DatabaseSpecifics databaseCreationSpecifics = updateDatabaseSpecificsForDBCreation(databaseSpecifics); - log.info("Creating database in " + DatabaseUtils.getDatabaseSpecificsDump(databaseCreationSpecifics) + log.info("Creating database in " + DatabaseUtils.getDatabaseSpecificsDump(databaseCreationSpecifics) + " from script " + scriptName); try { runScript(databaseCreationSpecifics, scriptName); @@ -71,7 +71,7 @@ private static DatabaseSpecifics updateDatabaseSpecificsForDBCreation(DatabaseSp protected Settings loadSettings(String pillarID, String pathToSettings) { SettingsProvider settingsLoader = - new SettingsProvider(new XMLFileSettingsLoader(pathToSettings), pillarID); + new SettingsProvider(new XMLFileSettingsLoader(pathToSettings), pillarID); return settingsLoader.getSettings(); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseFactory.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseFactory.java index 425417517..5211eee16 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseFactory.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseFactory.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -25,6 +25,7 @@ /** * DatabaseFactory which knows - based on the driver class - whether to use a Derby or Postgres backend. + * * @param class */ // FIXME: Is tasting on the name of the driver class the right way to detect the database type? @@ -32,32 +33,33 @@ public abstract class DatabaseFactory { public static final String derbyDriver = "org.apache.derby.jdbc.EmbeddedDriver"; - public static final String postgressDriver = "org.postgresql.Driver"; - + public static final String postgresDriver = "org.postgresql.Driver"; + /** * Obtain the appropriate DAO instance for the concrete backend. + * * @param ds the database specifics * @return the appropriate DAO instance for the concrete backend. * @throws UnsupportedDatabaseTypeException if the driver is not either derby or postgres * @see #derbyDriver - * @see #postgressDriver + * @see #postgresDriver */ - protected T getDAOInstance(DatabaseSpecifics ds) throws UnsupportedDatabaseTypeException{ + protected T getDAOInstance(DatabaseSpecifics ds) throws UnsupportedDatabaseTypeException { DatabaseManager dm = getDatabaseManager(ds); String dbDriver = ds.getDriverClass(); - if(dbDriver.equals(derbyDriver)) { + if (dbDriver.equals(derbyDriver)) { return getDerbyDAO(dm); - } else if(dbDriver.equals(postgressDriver)) { + } else if (dbDriver.equals(postgresDriver)) { return getPostgresDAO(dm); } else { throw new UnsupportedDatabaseTypeException("The database for driver: '" + dbDriver - + "' is not supported, use '" + derbyDriver + "' or '" + postgressDriver + "'"); + + "' is not supported, use '" + derbyDriver + "' or '" + postgresDriver + "'"); } } - + protected abstract T getDerbyDAO(DatabaseManager dm); - + protected abstract T getPostgresDAO(DatabaseManager dm); - + protected abstract DatabaseManager getDatabaseManager(DatabaseSpecifics ds); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMaintainer.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMaintainer.java index c92b6c8a7..019381bd1 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMaintainer.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMaintainer.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -42,13 +42,14 @@ public class DatabaseMaintainer { /** * Attempts to find a script with the indicated name in the classpath and run it. + * * @param databaseSpecifics the specifics of the database - * @param scriptName The name of the script in the classpath. - * @throws SQLException if a connection to the database could not be established or if it failed to close the connection + * @param scriptName The name of the script in the classpath. + * @throws SQLException if a connection to the database could not be established or if it failed to close the connection * @throws ClassNotFoundException if the database driver is not on the classpath - * @throws IOException if the script can not be read - * @throws FileNotFoundException if the script is not on the classpath - * @throws RuntimeException if the script can not be run + * @throws IOException if the script can not be read + * @throws FileNotFoundException if the script is not on the classpath + * @throws RuntimeException if the script can not be run */ protected static void runScript(DatabaseSpecifics databaseSpecifics, String scriptName) throws SQLException, ClassNotFoundException, FileNotFoundException, IOException { @@ -56,15 +57,16 @@ protected static void runScript(DatabaseSpecifics databaseSpecifics, String scri runScript(connection, scriptName); connection.close(); } - + /** * Attempts to find a script with the indicated name in the classpath and run it. - * @param connector the database connector + * + * @param connector the database connector * @param scriptName The name of the script in the classpath. - * @throws IOException if the script could not be read or found + * @throws IOException if the script could not be read or found * @throws IllegalStateException if the database connection could not be opened - * @throws SQLException if the database connection could not be closed - * @throws RuntimeException if the script failed + * @throws SQLException if the database connection could not be closed + * @throws RuntimeException if the script failed * @see #runScript(Connection, String) */ protected static void runScript(DBConnector connector, String scriptName) throws IOException, IllegalStateException, @@ -73,13 +75,13 @@ protected static void runScript(DBConnector connector, String scriptName) throws runScript(connection, scriptName); connection.close(); } - + /** - * * Run the script given. + * * @param connection the database connection * @param scriptName the name of the script - * @throws IOException if the script could not be read + * @throws IOException if the script could not be read * @throws RuntimeException if the script could not be run * @see SqlScriptRunner#runScript(Reader) */ @@ -90,12 +92,13 @@ private static void runScript(Connection connection, String scriptName) throws I /** * Creates a reader for the file found at indicated location. + * * @param filePath the path to the file on the classpath * @return a reader for the content - * @throws IOException if the file cannot be read + * @throws IOException if the file cannot be read * @throws FileNotFoundException if the file is not on the classpath */ - private static Reader getReaderForFile(String filePath) throws FileNotFoundException, java.io.IOException { + private static Reader getReaderForFile(String filePath) throws FileNotFoundException, java.io.IOException { InputStream is = DatabaseMaintainer.class.getClassLoader().getResourceAsStream(filePath); if (is == null) { @@ -107,10 +110,11 @@ private static Reader getReaderForFile(String filePath) throws FileNotFoundExce /** * Creates a connection based on the supplied databaseSpecifics. + * * @param databaseSpecifics the database specifics - * @throws SQLException if a connection to the database could not be established - * @throws ClassNotFoundException if the specified database driver class could not be found on the classpath * @return the connection to the database + * @throws SQLException if a connection to the database could not be established + * @throws ClassNotFoundException if the specified database driver class could not be found on the classpath */ protected static Connection getDBConnection(DatabaseSpecifics databaseSpecifics) throws SQLException, ClassNotFoundException { Class.forName(databaseSpecifics.getDriverClass()); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseManager.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseManager.java index 3f4575240..898778473 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseManager.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseManager.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -29,89 +29,92 @@ import java.sql.SQLException; /** - * General class for obtaining a database connection to a service's database. + * General class for obtaining a database connection to a service's database. * The manager is responsible for: * - Creating a new database, if none existed on the connection url (derby only). * - Connecting to the database. * - Migrating the database schema if needed (derby only). - * - * If the database is unavailable exceptions will be thrown detailing the reason. - * Databases that are not automatically migrated will result in an exception. + *

      + * If the database is unavailable exceptions will be thrown detailing the reason. + * Databases that are not automatically migrated will result in an exception. */ public abstract class DatabaseManager { - private Logger log = LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); private static final String derbyDriver = "org.apache.derby.jdbc.EmbeddedDriver"; - private static final String postgressDriver = "org.postgresql.Driver"; + private static final String postgresDriver = "org.postgresql.Driver"; protected DBConnector connector = null; - + /** - * Method to obtain the DBConnector for the concrete instance of the database. - * When a connection is returned, the database is ensured to be existing, connected + * Method to obtain the DBConnector for the concrete instance of the database. + * When a connection is returned, the database is ensured to be existing, connected * and in the expected version. + * * @return {@link DBConnector} DBConnector to the database. */ public DBConnector getConnector() { DatabaseSpecifics ds = getDatabaseSpecifics(); - if(ds.getDriverClass().equals(derbyDriver)) { - return getDerbyConnection(); - } else if(ds.getDriverClass().equals(postgressDriver)) { + if (ds.getDriverClass().equals(derbyDriver)) { + return getDerbyConnection(); + } else if (ds.getDriverClass().equals(postgresDriver)) { return getPostgresConnection(); } else { throw new IllegalStateException("The database driver: '" + ds.getDriverClass() + "' is not supported." - + " Supported drivers are: '" + derbyDriver + "' and '" + postgressDriver + "'."); + + " Supported drivers are: '" + derbyDriver + "' and '" + postgresDriver + "'."); } - - + + } - + /** - * Get a connection to a postgres database - * This method won't attempt to create a database if connection is unsuccessful, + * Get a connection to a postgres database + * This method won't attempt to create a database if connection is unsuccessful, * also i won't attempt to migrate the database. + * * @return {@link DBConnector} The connector to the database */ private DBConnector getPostgresConnection() { - if(connector == null) { + if (connector == null) { obtainConnection(); } - if(needsMigration()) { - throw new IllegalStateException("Automatic migration of postgres databases are not supported. "+ - "The database on: " + getDatabaseSpecifics().getDatabaseURL() + + if (needsMigration()) { + throw new IllegalStateException("Automatic migration of postgres databases are not supported. " + + "The database on: " + getDatabaseSpecifics().getDatabaseURL() + " needs manuel migration."); } - + return connector; } - + /** - * Get a connection to a derby database + * Get a connection to a derby database * Creates the database if the connection to it fails. Migrates the database schema if it is needed. - * @return {@link DBConnector} The connector to the database + * + * @return {@link DBConnector} The connector to the database */ private DBConnector getDerbyConnection() { - if(connector == null) { + if (connector == null) { try { obtainConnection(); } catch (IllegalStateException e) { - if(allowAutoCreate()) { + if (allowAutoCreate()) { log.warn("Failed to connect to database, attempting to create it"); createDatabase(); } else { - log.error("Failed to connect to database, autocreation is disabled"); + log.error("Failed to connect to database, auto-creation is disabled"); throw e; } } - if(connector == null) { + if (connector == null) { obtainConnection(); } log.info("Checking if the database needs to be migrated."); - if(needsMigration()) { - if(allowAutoMigrate()) { - log.warn("Database needs to be migrated, attempting to automigrate."); + if (needsMigration()) { + if (allowAutoMigrate()) { + log.warn("Database needs to be migrated, attempting to auto-migrate."); migrateDatabase(); } else { - log.error("Database needs migration, automigrations is disabled."); - throw new IllegalStateException("Database needs migration, automigrations is disabled."); + log.error("Database needs migration, auto-migrations is disabled."); + throw new IllegalStateException("Database needs migration, auto-migrations is disabled."); } } else { log.info("Database migration was not needed."); @@ -119,83 +122,89 @@ private DBConnector getDerbyConnection() { } return connector; } - + /** - * Obtain the database specifics for the database to manage. - * @return DatabaseSpecifics The database specifics for the concrete database + * Obtain the database specifics for the database to manage. + * + * @return DatabaseSpecifics The database specifics for the concrete database */ protected abstract DatabaseSpecifics getDatabaseSpecifics(); - + /** * Get the migrator for the concrete database. - * @return DatabaseMigrator The concrete database migrator + * + * @return DatabaseMigrator The concrete database migrator */ protected abstract DatabaseMigrator getMigrator(); - + /** - * Method to determine whether the database needs to be migrated. - * @return true if migration should be done, false otherwise + * Method to determine whether the database needs to be migrated. + * + * @return true if migration should be done, false otherwise */ protected abstract boolean needsMigration(); - + /** - * Get the path to the file containing the full database schema for initial creation of - * the concrete database. - * @return String The path to the file with the database in String form. + * Get the path to the file containing the full database schema for initial creation of + * the concrete database. + * + * @return String The path to the file with the database in String form. */ protected abstract String getDatabaseCreationScript(); - + /** - * Connect to a database using the database specifics from the implementing class. + * Connect to a database using the database specifics from the implementing class. + * * @throws IllegalStateException if connection cannot be obtained. */ protected void obtainConnection() throws IllegalStateException { log.debug("Obtaining db connection."); - connector = new DBConnector(getDatabaseSpecifics()); + connector = new DBConnector(getDatabaseSpecifics()); Connection connection = connector.getConnection(); try { connection.close(); } catch (SQLException e) { - log.warn("Connection opened for testing connectivaty failed to close", e); + log.warn("Connection opened for testing connectivity failed to close", e); } log.debug("Obtained db connection."); } - + /** * Perform the actual migration of the concrete database. */ private void migrateDatabase() { DatabaseMigrator migrator = getMigrator(); - if(migrator != null) { + if (migrator != null) { migrator.migrate(); } else { throw new IllegalStateException("The database was attempted migrated, but no migrator was available."); } } - + private boolean allowAutoMigrate() { DatabaseSpecifics ds = getDatabaseSpecifics(); - if(ds.isSetAllowAutoMigrate()) { + if (ds.isSetAllowAutoMigrate()) { return ds.isAllowAutoMigrate(); } else { return true; } } - + private boolean allowAutoCreate() { DatabaseSpecifics ds = getDatabaseSpecifics(); - if(ds.isSetAllowAutoCreate()) { + if (ds.isSetAllowAutoCreate()) { return ds.isAllowAutoCreate(); } else { return true; - } } - + } + } + /** - * Create the database on the given database specifics. + * Create the database on the given database specifics. */ private void createDatabase() { DatabaseCreator databaseCreator = new DatabaseCreator(); databaseCreator.createDatabase(getDatabaseSpecifics(), getDatabaseCreationScript()); } - + } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMigrator.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMigrator.java index 91f65a049..d1a68e13a 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMigrator.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseMigrator.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -31,85 +31,82 @@ /** * Abstract class for migrating the databases. * Handles the default operations. - * + *

      * It is asserted, that the database has the following table for the versions: - * + *

      * create table tableversions ( - * tablename varchar(100) not null, -- Name of table - * version int not null -- version of table + * tablename varchar(100) not null, -- Name of table + * version int not null -- version of table * ); */ public abstract class DatabaseMigrator extends DatabaseMaintainer { - /** The connection to the database.*/ protected final DBConnector connector; - - /** The name of the "table versions" table.*/ - protected static final String TABLEVERSIONS_TABLE = "tableversions"; - /** The 'tablename' coloumn in the table.*/ - protected static final String TV_TABLENAME = "tablename"; - /** The 'version' coloumn in the table.*/ + protected static final String TABLE_VERSIONS_TABLE = "tableversions"; + protected static final String TV_TABLE_NAME = "tablename"; protected static final String TV_VERSION = "version"; - + /** - * Constructor. * @param connector The connector for the database. */ protected DatabaseMigrator(DBConnector connector) { this.connector = connector; } - + /** * Extracts the version numbers for the tables in the database. + * * @return The mapping between the table names and their respective version number. */ protected Map getTableVersions() { Map resultMap = new HashMap<>(); - - // Extract the table name as first coloumn and version as second coloumn. - String sql = "SELECT " + TV_TABLENAME + " , " + TV_VERSION + " FROM " + TABLEVERSIONS_TABLE; - int tablenameColoumn = 1; - int versionColoumn = 2; - + + // Extract the table name as first column and version as second column. + String sql = "SELECT " + TV_TABLE_NAME + " , " + TV_VERSION + " FROM " + TABLE_VERSIONS_TABLE; + int tableNameColumn = 1; + int versionColumn = 2; + try (Connection conn = connector.getConnection(); - PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql, new Object[0])) { - try (ResultSet res = ps.executeQuery()){ + PreparedStatement ps = DatabaseUtils.createPreparedStatement(conn, sql)) { + try (ResultSet res = ps.executeQuery()) { while (res.next()) { - resultMap.put(res.getString(tablenameColoumn), res.getInt(versionColoumn)); + resultMap.put(res.getString(tableNameColumn), res.getInt(versionColumn)); } } } catch (SQLException e) { throw new IllegalStateException("Cannot extract the table versions.", e); } - + return resultMap; } - + /** * Performs the update of a single table. - * @param tablename The name of the table to update. + * + * @param tableName The name of the table to update. * @param newVersion The new version for the table. - * @param updateSql The SQL for updating the table. - * @param args The arguments for performing this update. + * @param updateSql The SQL for updating the table. + * @param args The arguments for performing this update. */ - protected void updateTable(String tablename, Integer newVersion, String updateSql, Object ... args) { - String migrateSql = "UPDATE " + TABLEVERSIONS_TABLE + " SET " + TV_VERSION + " = ? WHERE " + TV_TABLENAME + protected void updateTable(String tableName, Integer newVersion, String updateSql, Object... args) { + String migrateSql = "UPDATE " + TABLE_VERSIONS_TABLE + " SET " + TV_VERSION + " = ? WHERE " + TV_TABLE_NAME + " = ?"; - + DatabaseUtils.executeStatement(connector, updateSql, args); - DatabaseUtils.executeStatement(connector, migrateSql, newVersion, tablename); + DatabaseUtils.executeStatement(connector, migrateSql, newVersion, tableName); } - + /** * Method for running a specific migrate script on the embedded database. * Will throw an exception if the migration is tried to be performed on another type of database. - * @param migrateScriptName The name of the migrate script to run. + * + * @param migrateScriptName The name of the migrated script to run. */ protected void migrateDerbyDatabase(String migrateScriptName) { - if(connector.getDatabaseDriverClass().equals(DatabaseUtils.DERBY_EMBEDDED_DRIVER)) { + if (connector.getDatabaseDriverClass().equals(DatabaseUtils.DERBY_EMBEDDED_DRIVER)) { try { runScript(connector, migrateScriptName); } catch (Exception e) { - throw new IllegalStateException("Cannot migrate the database with the script '" + migrateScriptName + throw new IllegalStateException("Cannot migrate the database with the script '" + migrateScriptName + "'. It is very possible that the database has to be migrated by manually running " + "migrate-scripts.", e); } @@ -119,16 +116,17 @@ protected void migrateDerbyDatabase(String migrateScriptName) { + connector.getDatabaseDriverClass()); } } - + /** * Perform the migration for the given database. */ abstract public void migrate(); - + /** * Method to determine if migration is needed. - * @return true if migration is needed, false otherwise. + * + * @return true if migration is needed, false otherwise. */ public abstract boolean needsMigration(); - + } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseUtils.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseUtils.java index 7e99f7920..7e68b7161 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseUtils.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/DatabaseUtils.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Integrity Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -43,31 +43,37 @@ * Utility class for operating on databases. */ public class DatabaseUtils { - /** The log.*/ + /** + * The log. + */ private static final Logger log = LoggerFactory.getLogger(DatabaseUtils.class); - /** The name of the embedded derby driver.*/ + /** + * The name of the embedded derby driver. + */ public static final String DERBY_EMBEDDED_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver"; - - /** Private constructor to prevent instantiation of this utility class.*/ - private DatabaseUtils() { } - + + /** + * Private constructor to prevent instantiation of this utility class. + */ + private DatabaseUtils() {} + /** - * Retrieves an integer value from the database through the use of a SQL query, which requests + * Retrieves an integer value from the database through the use of a SQL query, which requests * the wanted integer value, and the arguments for the query to become a proper SQL statement. - * + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the integer value. - * @param args The arguments for the database statement. + * @param query The query for retrieving the integer value. + * @param args The arguments for the database statement. * @return The integer value from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static Integer selectIntValue(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { @@ -87,23 +93,23 @@ public static Integer selectIntValue(DBConnector dbConnector, String query, Obje throw failedExecutionOfStatement(e, query, args); } } - + /** - * Retrieves a long value from the database through the use of a SQL query, which requests + * Retrieves a long value from the database through the use of a SQL query, which requests * the wanted long value, and the arguments for the query to become a proper SQL statement. - * + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the long value. - * @param args The arguments for the database statement. + * @param query The query for retrieving the long value. + * @param args The arguments for the database statement. * @return The long value from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static Long selectLongValue(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { @@ -120,29 +126,29 @@ public static Long selectLongValue(DBConnector dbConnector, String query, Object throw new IllegalStateException("Too many results from " + ps); } return resultLong; - } + } } catch (SQLException e) { throw failedExecutionOfStatement(e, query, args); } } - + /** - * Retrieves the first long value from the database through the use of a SQL query and the arguments for the query - * to become a proper SQL statement, which requests the wanted set of long values, where only the first is + * Retrieves the first long value from the database through the use of a SQL query and the arguments for the query + * to become a proper SQL statement, which requests the wanted set of long values, where only the first is * returned. - * + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the long value. - * @param args The arguments for the database statement. + * @param query The query for retrieving the long value. + * @param args The arguments for the database statement. * @return The long value from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static Long selectFirstLongValue(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { @@ -161,24 +167,24 @@ public static Long selectFirstLongValue(DBConnector dbConnector, String query, O throw failedExecutionOfStatement(e, query, args); } } - + /** - * Retrieves the first string value from the database through the use of a SQL query and the arguments for the query - * to become a proper SQL statement, which requests the wanted set of string values, where only the first is + * Retrieves the first string value from the database through the use of a SQL query and the arguments for the query + * to become a proper SQL statement, which requests the wanted set of string values, where only the first is * returned. - * + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the long value. - * @param args The arguments for the database statement. + * @param query The query for retrieving the long value. + * @param args The arguments for the database statement. * @return The string value from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static String selectFirstStringValue(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { @@ -197,27 +203,28 @@ public static String selectFirstStringValue(DBConnector dbConnector, String quer throw failedExecutionOfStatement(e, query, args); } } + /** - * Retrieves a list of long values from the database through the use of a SQL query, which requests + * Retrieves a list of long values from the database through the use of a SQL query, which requests * the wanted long values, and the arguments for the query to become a proper SQL statement. - * + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the long value. - * @param args The arguments for the database statement. + * @param query The query for retrieving the long value. + * @param args The arguments for the database statement. * @return The list of long values from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static List selectLongList(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); - PreparedStatement ps = createPreparedStatement(conn, query, args)) { + PreparedStatement ps = createPreparedStatement(conn, query, args)) { List list = new ArrayList<>(); try (ResultSet res = ps.executeQuery()) { - while(res.next()) { + while (res.next()) { list.add(res.getLong(1)); } return list; @@ -228,51 +235,52 @@ public static List selectLongList(DBConnector dbConnector, String query, O } /** - * Retrieves an date value from the database through the use of a SQL query, which requests + * Retrieves an date value from the database through the use of a SQL query, which requests * the wanted date value, and the arguments for the query to become a proper SQL statement. - * + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the date. - * @param args The arguments for the database statement. + * @param query The query for retrieving the date. + * @param args The arguments for the database statement. * @return The date from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static Date selectDateValue(DBConnector dbConnector, String query, Object... args) { return retrieveDateValue(dbConnector, true, query, args); } - + /** - * Retrieves the first date value from the database through the use of a SQL query, which requests + * Retrieves the first date value from the database through the use of a SQL query, which requests * the wanted date value, and the arguments for the query to become a proper SQL statement. - * If the results set contains more than one value, the others are ignored. - * + * If the results set contains more than one value, the others are ignored. + * * @param dbConnector For connecting to the database. - * @param query The query for retrieving the date. - * @param args The arguments for the database statement. + * @param query The query for retrieving the date. + * @param args The arguments for the database statement. * @return The date from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static Date selectFirstDateValue(DBConnector dbConnector, String query, Object... args) { return retrieveDateValue(dbConnector, false, query, args); } - + /** * The actual extraction from the database. - * @param dbConnector For connecting to the database. + * + * @param dbConnector For connecting to the database. * @param mustHaveOnlyOneResult Whether it should fail, if more than one result is found. - * @param query The query for retrieving the date. - * @param args The arguments for the database statement. + * @param query The query for retrieving the date. + * @param args The arguments for the database statement. * @return The date from the given statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ private static Date retrieveDateValue(DBConnector dbConnector, boolean mustHaveOnlyOneResult, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { @@ -294,17 +302,17 @@ private static Date retrieveDateValue(DBConnector dbConnector, boolean mustHaveO throw failedExecutionOfStatement(e, query, args); } } - + /** - * Retrieves a String value from the database through the use of a SQL query, which requests + * Retrieves a String value from the database through the use of a SQL query, which requests * the wanted String value, and the arguments for the query to become a proper SQL statement. - * + * * @param dbConnector For connecting to the database. - * @param query The query to extract the String value. - * @param args The arguments for the statement. + * @param query The query to extract the String value. + * @param args The arguments for the statement. * @return The requested string value, or null if no such value could be found. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static String selectStringValue(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); @@ -314,7 +322,7 @@ public static String selectStringValue(DBConnector dbConnector, String query, Ob try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { - if(!res.next()) { + if (!res.next()) { log.trace("No string was found for the query '" + query + "'. A null has been returned."); return null; } @@ -324,17 +332,17 @@ public static String selectStringValue(DBConnector dbConnector, String query, Ob throw failedExecutionOfStatement(e, query, args); } } - + /** - * Retrieves a list of String value from the database through the use of a SQL query, which requests + * Retrieves a list of String value from the database through the use of a SQL query, which requests * the wanted list of String value, and the arguments for the query to become a proper SQL statement. - * + * * @param dbConnector For connecting to the database. - * @param query The SQL query for retrieving the strings. - * @param args The arguments for the statement. + * @param query The SQL query for retrieving the strings. + * @param args The arguments for the statement. * @return The requested list of strings. If no strings were found, then the list is empty. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static List selectStringList(DBConnector dbConnector, String query, Object... args) { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); @@ -344,8 +352,8 @@ public static List selectStringList(DBConnector dbConnector, String quer try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { try (ResultSet res = ps.executeQuery()) { - List list = new ArrayList<>(); - while(res.next()) { + List list = new ArrayList<>(); + while (res.next()) { list.add(res.getString(1)); } return list; @@ -358,36 +366,36 @@ public static List selectStringList(DBConnector dbConnector, String quer /** * Executing a given statement, which should not return any results. * This is intended to be used especially for UPDATE commands. - * + * * @param dbConnector For connecting to the database. - * @param query The SQL query to execute. - * @param args The arguments for the SQL statement. + * @param query The SQL query to execute. + * @param args The arguments for the SQL statement. * @throws IllegalStateException if the connection could not be established, - * if the prepared statement could not be created, or the execution failed + * if the prepared statement could not be created, or the execution failed */ public static void executeStatement(DBConnector dbConnector, String query, Object... args) throws IllegalStateException { ArgumentValidator.checkNotNull(dbConnector, "DBConnector dbConnector"); ArgumentValidator.checkNotNullOrEmpty(query, "String query"); ArgumentValidator.checkNotNull(args, "Object... args"); - + try (Connection conn = dbConnector.getConnection(); PreparedStatement ps = createPreparedStatement(conn, query, args)) { - ps.executeUpdate(); - } catch (SQLException e) { + ps.executeUpdate(); + } catch (SQLException e) { throw failedExecutionOfStatement(e, query, args); } } - + /** * Prepare a statement given a query string and some args. - * + *

      * NB: the provided connection is not closed. * * @param dbConnection The connection to the database. - * @param query a query string (must not be null or empty) - * @param args some args to insert into this query string (must not be null) + * @param query a query string (must not be null or empty) + * @param args some args to insert into this query string (must not be null) * @return a prepared statement - * @throws SQLException If unable to prepare a statement + * @throws SQLException If unable to prepare a statement * @throws IllegalStateException if any of the args is of an unknown type */ public static PreparedStatement createPreparedStatement(Connection dbConnection, String query, Object... args) @@ -407,10 +415,10 @@ public static PreparedStatement createPreparedStatement(Connection dbConnection, } else if (arg instanceof Date) { s.setTimestamp(i, new Timestamp(((Date) arg).getTime())); } else { - if(arg == null) { + if (arg == null) { throw new IllegalStateException("Cannot handle a null as argument for SQL query. We can only " - + "handle string, int, long, date or boolean args for query: " + query); - } else { + + "handle string, int, long, date or boolean args for query: " + query); + } else { throw new IllegalStateException("Cannot handle type '" + arg.getClass().getName() + "'. We can only " + "handle string, int, long, date or boolean args for query: " + query); } @@ -433,20 +441,21 @@ public static PreparedStatement createPreparedStatement(Connection dbConnection, * @throws IllegalStateException Always, since it is intended for this method to report the failure. */ private static IllegalStateException failedExecutionOfStatement(Throwable e, String query, Object... args) { - return new IllegalStateException("Could not execute the query '" + query + "' with the arguments '" + return new IllegalStateException("Could not execute the query '" + query + "' with the arguments '" + Arrays.asList(args) + "'", e); } - + /** * Method to provide safe dump of database specifics (so we won't leak passwords). + * * @param databaseSpecifics the specifics of the database, containing sensitive passwords * @return the cleaned database specifics as a string */ public static String getDatabaseSpecificsDump(DatabaseSpecifics databaseSpecifics) { return "DatabaseSpecifics [driverClass=" + databaseSpecifics.getDriverClass() - + ", databaseURL=" + databaseSpecifics.getDatabaseURL() + + ", databaseURL=" + databaseSpecifics.getDatabaseURL() + ", username=" + databaseSpecifics.getUsername() + ", allowAutoMigrate=" + databaseSpecifics.isAllowAutoMigrate() + ", allowAutoCreate=" + databaseSpecifics.isAllowAutoCreate() + "]"; - } + } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/SqlScriptRunner.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/SqlScriptRunner.java index 196d56fc8..607d8ec4b 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/SqlScriptRunner.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/SqlScriptRunner.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -35,7 +35,7 @@ /** * Runs a sql script as a sequence of JDBC statements. - * + *

      * Slightly modified version of the com.ibatis.common.jdbc.SqlScriptRunner class * from the iBATIS Apache project. Only removed dependency on Resource class * and a constructor @@ -43,19 +43,15 @@ public class SqlScriptRunner { private static final String DEFAULT_DELIMITER = ";"; private static final Logger log = LoggerFactory.getLogger(SqlScriptRunner.class); - - private Connection connection; - - private boolean stopOnError; - private boolean autoCommit; - + private final Connection connection; + private final boolean stopOnError; + private final boolean autoCommit; private String delimiter = DEFAULT_DELIMITER; private boolean fullLineDelimiter = false; /** - * - * @param connection The connection to use - * @param autoCommit Enable autocommit + * @param connection The connection to use + * @param autoCommit Enable autocommit * @param stopOnError Stop running the script, if a statement fails. */ public SqlScriptRunner(Connection connection, @@ -67,7 +63,7 @@ public SqlScriptRunner(Connection connection, } /** - * @param delimiter The statement delimiter, eg. ';' for mysql. + * @param delimiter The statement delimiter, eg. ';' for mysql. * @param fullLineDelimiter true if the delimiter used to distinguish between lines. */ public void setDelimiter(String delimiter, boolean fullLineDelimiter) { @@ -110,80 +106,75 @@ public void runScript(Reader reader) { * @throws IOException if there is an error reading from the Reader. */ private void runScript(Connection conn, Reader reader) throws IOException, SQLException { - StringBuffer command = null; + StringBuilder command = null; LineNumberReader lineReader = new LineNumberReader(reader); - String line = null; + String line; while ((line = lineReader.readLine()) != null) { if (command == null) { - command = new StringBuffer(); + command = new StringBuilder(); } String trimmedLine = line.trim(); - if (trimmedLine.startsWith("--") || - trimmedLine.startsWith("//")) { - // Ignore comment line - } else if (trimmedLine.length() == 0) { - // Ignore empty line. - } else if (trimmedLine.contains("connect")) { - // Ignore connect statement as this is handled in the supplied connection. - } else if (!fullLineDelimiter - && trimmedLine.endsWith(getDelimiter()) - || fullLineDelimiter - && trimmedLine.equals(getDelimiter())) { - - command.append(trimLineForComment(line).substring(0, line - .lastIndexOf(getDelimiter()))); - command.append(" "); - - Statement statement = conn.createStatement(); - - log.debug("Executing statement: " + command.toString()); - - boolean hasResults = false; - if (stopOnError) { - hasResults = statement.execute(command.toString()); - } else { - try { - statement.execute(command.toString()); - } catch (SQLException e) { - e.fillInStackTrace(); - log.error("Error executing: " + command, e); + if (proceedWithLine(trimmedLine)) { + if (!fullLineDelimiter + && trimmedLine.endsWith(getDelimiter()) + || fullLineDelimiter + && trimmedLine.equals(getDelimiter())) { + + command.append(trimLineForComment(line), 0, line + .lastIndexOf(getDelimiter())); + command.append(" "); + + Statement statement = conn.createStatement(); + + log.debug("Executing statement: " + command); + + boolean hasResults = false; + if (stopOnError) { + hasResults = statement.execute(command.toString()); + } else { + try { + statement.execute(command.toString()); + } catch (SQLException e) { + e.fillInStackTrace(); + log.error("Error executing: " + command, e); + } } - } - if (autoCommit && !conn.getAutoCommit()) { - conn.commit(); - } - - ResultSet rs = statement.getResultSet(); - StringBuilder resultSB = new StringBuilder(); - if (hasResults && rs != null) { - ResultSetMetaData md = rs.getMetaData(); - int cols = md.getColumnCount(); - for (int i = 0; i < cols; i++) { - String name = md.getColumnLabel(i); - resultSB.append(name + "\t"); + if (autoCommit && !conn.getAutoCommit()) { + conn.commit(); } - resultSB.append("\n"); - while (rs.next()) { + + ResultSet rs = statement.getResultSet(); + StringBuilder resultSB = new StringBuilder(); + if (hasResults && rs != null) { + ResultSetMetaData md = rs.getMetaData(); + int cols = md.getColumnCount(); for (int i = 0; i < cols; i++) { - String value = rs.getString(i); - resultSB.append(value + "\t"); + String name = md.getColumnLabel(i); + resultSB.append(name).append("\t"); } resultSB.append("\n"); + while (rs.next()) { + for (int i = 0; i < cols; i++) { + String value = rs.getString(i); + resultSB.append(value).append("\t"); + } + resultSB.append("\n"); + } + log.info("Result: " + resultSB); } - log.info("Result: " + resultSB.toString()); - } - command = null; - try { - statement.close(); - } catch (Exception e) { - // Ignore to workaround a bug in Jakarta DBCP + command = null; + try { + statement.close(); + } catch (Exception e) { + // Ignore to work around a bug in Jakarta DBCP + } + Thread.yield(); + } else { + command.append(trimLineForComment(line)); + command.append(" "); } - Thread.yield(); - } else { - command.append(trimLineForComment(line)); - command.append(" "); } } if (!autoCommit) { @@ -192,6 +183,15 @@ private void runScript(Connection conn, Reader reader) throws IOException, SQLEx } + private boolean proceedWithLine(String trimmedLine) { + if (trimmedLine.startsWith("--") || + trimmedLine.startsWith("//")) { + return false; + } else if (trimmedLine.length() == 0) { + return false; + } else return !trimmedLine.contains("connect"); + } + private String trimLineForComment(String line) { if (line.contains("--")) { return line.substring(0, line.indexOf("--")); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/database/UnsupportedDatabaseTypeException.java b/bitrepository-service/src/main/java/org/bitrepository/service/database/UnsupportedDatabaseTypeException.java index e7d8c1e3a..df277e832 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/database/UnsupportedDatabaseTypeException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/database/UnsupportedDatabaseTypeException.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -22,7 +22,7 @@ package org.bitrepository.service.database; /** - * Exception to indicate that a given database type is not supported. + * Exception to indicate that a given database type is not supported. */ @SuppressWarnings("serial") public class UnsupportedDatabaseTypeException extends RuntimeException { diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/exception/IdentifyContributorException.java b/bitrepository-service/src/main/java/org/bitrepository/service/exception/IdentifyContributorException.java index 8f2f4a09b..d48ac31a8 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/exception/IdentifyContributorException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/exception/IdentifyContributorException.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,24 +27,22 @@ import org.bitrepository.bitrepositoryelements.ResponseCode; /** - * Exception which wraps bad response information for the identifications. + * Exception which wraps bad response information for the identifications. */ @SuppressWarnings("serial") public class IdentifyContributorException extends RequestHandlerException { /** - * Constructor. * @param rCode The response code. * @param rText The text for the response info. */ public IdentifyContributorException(ResponseCode rCode, String rText) { super(rCode, rText); } - + /** - * Constructor. * @param rCode The response code. * @param rText The text for the response info. - * @param e The exception to wrap into the StackTrace. + * @param e The exception to wrap into the StackTrace. */ public IdentifyContributorException(ResponseCode rCode, String rText, Exception e) { super(rCode, rText, e); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/exception/IllegalOperationException.java b/bitrepository-service/src/main/java/org/bitrepository/service/exception/IllegalOperationException.java index 15f018d2e..4cbaf3441 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/exception/IllegalOperationException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/exception/IllegalOperationException.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -29,31 +29,29 @@ */ @SuppressWarnings("serial") public class IllegalOperationException extends RequestHandlerException { - private String fileID; - + private final String fileID; + /** - * Constructor. - * @param rCode The response code. - * @param rText The text for the response info. + * @param rCode The response code. + * @param rText The text for the response info. * @param fileID The id of the file regarding the illegal operation. Use null, if no file. */ public IllegalOperationException(ResponseCode rCode, String rText, String fileID) { super(rCode, rText); this.fileID = fileID; } - + /** - * Constructor. - * @param rCode The response code. - * @param rText The text for the response info. + * @param rCode The response code. + * @param rText The text for the response info. * @param fileID The id of the file regarding the illegal operation. Use null, if no file. - * @param e The exception to wrap into the StackTrace. + * @param e The exception to wrap into the StackTrace. */ public IllegalOperationException(ResponseCode rCode, String rText, String fileID, Exception e) { super(rCode, rText, e); this.fileID = fileID; } - + /** * @return fileID field. */ diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/exception/InvalidMessageException.java b/bitrepository-service/src/main/java/org/bitrepository/service/exception/InvalidMessageException.java index f1f0254b9..76480b4c2 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/exception/InvalidMessageException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/exception/InvalidMessageException.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Reference Pillar - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -28,31 +28,28 @@ import org.bitrepository.bitrepositoryelements.ResponseInfo; /** - * Exception which wraps bad response information for the validation of the operation requests. + * Exception which wraps bad response information for the validation of the operation requests. */ @SuppressWarnings("serial") public class InvalidMessageException extends RequestHandlerException { /** - * Constructor. * @param rCode The response code. * @param rText The text for the response info. */ public InvalidMessageException(ResponseCode rCode, String rText) { super(rCode, rText); } - + /** - * Constructor. * @param rCode The response code. * @param rText The text for the response info. - * @param e The exception to wrap into the StackTrace. + * @param e The exception to wrap into the StackTrace. */ public InvalidMessageException(ResponseCode rCode, String rText, Exception e) { super(rCode, rText, e); } - + /** - * Constructor. * @param rInfo The response info. */ public InvalidMessageException(ResponseInfo rInfo) { diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/exception/RequestHandlerException.java b/bitrepository-service/src/main/java/org/bitrepository/service/exception/RequestHandlerException.java index 2bbf4e8a6..73b9cb11a 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/exception/RequestHandlerException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/exception/RequestHandlerException.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -29,11 +29,12 @@ */ @SuppressWarnings("serial") public abstract class RequestHandlerException extends Exception { - /** The ResponseInfo wrapped by this exception. Tells the reason for the exception.*/ + /** + * The ResponseInfo wrapped by this exception. Tells the reason for the exception. + */ private final ResponseInfo responseInfo; - + /** - * Constructor. * @param rCode The response code. * @param rText The text for the response info. */ @@ -43,12 +44,11 @@ public RequestHandlerException(ResponseCode rCode, String rText) { this.responseInfo.setResponseCode(rCode); this.responseInfo.setResponseText(rText); } - + /** - * Constructor. * @param rCode The response code. * @param rText The text for the response info. - * @param e The exception to wrap into the StackTrace. + * @param e The exception to wrap into the StackTrace. */ public RequestHandlerException(ResponseCode rCode, String rText, Exception e) { super(rText, e); @@ -56,23 +56,22 @@ public RequestHandlerException(ResponseCode rCode, String rText, Exception e) { this.responseInfo.setResponseCode(rCode); this.responseInfo.setResponseText(rText); } - + /** - * Constructor. * @param rInfo The response info. */ public RequestHandlerException(ResponseInfo rInfo) { super(rInfo.getResponseText()); this.responseInfo = rInfo; } - + /** * @return The wrapped ResponseInfo. */ public ResponseInfo getResponseInfo() { return responseInfo; } - + @Override public String toString() { return super.toString() + ", " + responseInfo.toString(); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/exception/StepFailedException.java b/bitrepository-service/src/main/java/org/bitrepository/service/exception/StepFailedException.java index 3c876ce53..1c16997a3 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/exception/StepFailedException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/exception/StepFailedException.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -24,12 +24,13 @@ /** * StepFailedException allows communicating to the upstream fault barrier that a step failed. */ +@SuppressWarnings("serial") public class StepFailedException extends Exception { public StepFailedException(String message, Exception e) { super(message, e); } - + public StepFailedException(String message) { super(message); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/exception/WorkflowAbortedException.java b/bitrepository-service/src/main/java/org/bitrepository/service/exception/WorkflowAbortedException.java index e4f73a966..ca737cbdd 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/exception/WorkflowAbortedException.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/exception/WorkflowAbortedException.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * + * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . @@ -22,8 +22,9 @@ package org.bitrepository.service.exception; /** - * WorkflowAbortedException allows to communicate to an upstream fault barrier that the workflow aborted. + * WorkflowAbortedException allows communicating to an upstream fault barrier that the workflow aborted. */ +@SuppressWarnings("serial") public class WorkflowAbortedException extends Exception { public WorkflowAbortedException(String message) { diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobEventListener.java b/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobEventListener.java index 2274ed7fe..828abc906 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobEventListener.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobEventListener.java @@ -1,20 +1,20 @@ package org.bitrepository.service.scheduler;/* * #%L - * Bitrepository Integrity Service + * BitRepository Integrity Service * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobScheduler.java b/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobScheduler.java index 5d6698611..80f807e91 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobScheduler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/JobScheduler.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Integrity Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -36,7 +36,8 @@ public interface JobScheduler { /** * Adds a job for the scheduler to schedule. - * @param job The job to schedule. + * + * @param job The job to schedule. * @param interval The interval for how often the job should be triggered. */ void schedule(SchedulableJob job, Long interval); @@ -52,7 +53,8 @@ public interface JobScheduler { /** * Reschedules the job to start now, - * @param job the jobn to start + * + * @param job the job to start * @return A string indicating the result of the attempt to start the job. */ String startJob(SchedulableJob job); @@ -71,6 +73,7 @@ public interface JobScheduler { /** * Enables other objects to listen for job events. + * * @param listener The callback listener to receive the events. */ void addJobEventListener(JobEventListener listener); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/TimerbasedScheduler.java b/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/TimerBasedScheduler.java similarity index 80% rename from bitrepository-service/src/main/java/org/bitrepository/service/scheduler/TimerbasedScheduler.java rename to bitrepository-service/src/main/java/org/bitrepository/service/scheduler/TimerBasedScheduler.java index 010926ad7..3db8615b0 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/TimerbasedScheduler.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/scheduler/TimerBasedScheduler.java @@ -1,37 +1,29 @@ /* * #%L * Bitrepository Integrity Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% */ package org.bitrepository.service.scheduler; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Timer; - import org.bitrepository.common.utils.TimeUtils; import org.bitrepository.service.workflow.JobID; import org.bitrepository.service.workflow.JobTimerTask; @@ -40,39 +32,41 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Timer; + /** * Scheduler that uses Timer to run workflows. */ -public class TimerbasedScheduler implements JobScheduler { - private Logger log = LoggerFactory.getLogger(getClass()); - - /** The timer that schedules events. */ +public class TimerBasedScheduler implements JobScheduler { + private final Logger log = LoggerFactory.getLogger(getClass()); private final Timer timer; - /** The map between the running timertasks and their names. */ - private Map intervalTasks = new HashMap<>(); + private final Map intervalTasks = new HashMap<>(); public static final long SCHEDULE_INTERVAL = 60000; - - /** The name of the timer.*/ private static final String TIMER_NAME = "Service Scheduler"; - /** Whether the timer is a daemon.*/ private static final boolean TIMER_IS_DAEMON = true; - /** A timer delay of 0 seconds.*/ private static final Long NO_DELAY = 0L; - private List jobListeners = new LinkedList<>(); + private final List jobListeners = new LinkedList<>(); - /** Setup a timer task for running the workflows at requested interval. + /** + * Sets up a timer task for running the workflows at requested interval. */ - public TimerbasedScheduler() { + public TimerBasedScheduler() { timer = new Timer(TIMER_NAME, TIMER_IS_DAEMON); } @Override public void schedule(SchedulableJob workflow, Long interval) { - log.info("Scheduling job : " + workflow.getJobID() + " to run every " + log.info("Scheduling job : " + workflow.getJobID() + " to run every " + TimeUtils.millisecondsToHuman(interval)); - + JobTimerTask task = new JobTimerTask(interval, workflow, Collections.unmodifiableList(jobListeners)); - if(interval > 0) { + if (interval > 0) { scheduleJob(task); } @@ -82,8 +76,8 @@ public void schedule(SchedulableJob workflow, Long interval) { @Override public String startJob(SchedulableJob job) { log.debug("Starting job: " + job); - if(job.currentState() != WorkflowState.NOT_RUNNING) { - log.info("Cannot schedule job,'" + job.getJobID() + "', which is in state '" + if (job.currentState() != WorkflowState.NOT_RUNNING) { + log.info("Cannot schedule job,'" + job.getJobID() + "', which is in state '" + job.currentState() + "'"); return "Already running"; } @@ -121,23 +115,24 @@ public void addJobEventListener(JobEventListener listener) { @Override public JobTimerTask cancelJob(JobID jobID) { JobTimerTask task = intervalTasks.remove(jobID); - if(task == null) { + if (task == null) { return null; } task.cancel(); return task; } - + /** - * Schedules a task. - * If the interval for the task is > 0, then it should be scheduled to run at fixed interval, - * but it if has a non-positive interval, then it should only be scheduled for one run. + * Schedules a task. + * If the interval for the task is > 0, then it should be scheduled to run at fixed interval, + * but if it has a non-positive interval, then it should only be scheduled for one run. + * * @param task The task to schedule. */ private void scheduleJob(JobTimerTask task) { - if(task.getIntervalBetweenRuns() > 0) { - timer.scheduleAtFixedRate(task, NO_DELAY, SCHEDULE_INTERVAL); + if (task.getIntervalBetweenRuns() > 0) { + timer.scheduleAtFixedRate(task, NO_DELAY, SCHEDULE_INTERVAL); } else { timer.schedule(task, NO_DELAY); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/AbstractWorkFlowStep.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/AbstractWorkFlowStep.java index 49c5dc973..d0b8560bd 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/AbstractWorkFlowStep.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/AbstractWorkFlowStep.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobID.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobID.java index 0c9e01dba..66d7618a2 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobID.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobID.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,16 +27,16 @@ public class JobID { private final String collectionID; private final String workflowName; - + public JobID(String workflowName, String collectionID) { this.collectionID = collectionID; this.workflowName = workflowName; } - + public String getWorkflowName() { return workflowName; } - + public String getCollectionID() { return collectionID; } @@ -67,14 +67,11 @@ public boolean equals(Object obj) { } else if (!collectionID.equals(other.collectionID)) return false; if (workflowName == null) { - if (other.workflowName != null) - return false; - } else if (!workflowName.equals(other.workflowName)) - return false; - return true; + return other.workflowName == null; + } else return workflowName.equals(other.workflowName); } - - @Override + + @Override public String toString() { return workflowName + "-" + collectionID; } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobTimerTask.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobTimerTask.java index c4f403092..5536d5aac 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobTimerTask.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/JobTimerTask.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -34,21 +34,18 @@ * Used for scheduling workflows to run continuously at a given interval. */ public class JobTimerTask extends TimerTask { - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - /** The date for the next run of the workflow.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private Date nextRun; - /** The interval between triggers. */ private final long interval; private final SchedulableJob job; - private List jobListeners; + private final List jobListeners; /** * Initialise trigger. * * @param interval The interval between triggering events in milliseconds. * @param job The job. - * @param jobListeners eventlisteners for this job. + * @param jobListeners event listeners for this job. */ public JobTimerTask(long interval, SchedulableJob job, List jobListeners) { this.interval = interval; @@ -61,8 +58,8 @@ public JobTimerTask(long interval, SchedulableJob job, List jo * @return The date for the next time the encapsulated workflow should run. */ public Date getNextRun() { - if(interval > 0) { - return new Date(nextRun.getTime()); + if (interval > 0) { + return new Date(nextRun.getTime()); } else { return null; } @@ -93,10 +90,8 @@ public void runJob() { nextRun = new Date(System.currentTimeMillis() + interval); } notifyListenersAboutFinishedJob(job); - return; } else { log.info("Ignoring start request for " + job.getJobID() + " the job is already running"); - return; } } catch (Throwable e) { log.error("Fault barrier for '" + job.getJobID() + "' caught unexpected exception.", e); @@ -104,7 +99,7 @@ public void runJob() { } private void notifyListenersAboutFinishedJob(SchedulableJob job) { - for (JobEventListener listener:jobListeners) { + for (JobEventListener listener : jobListeners) { listener.jobFinished(job); } } @@ -115,15 +110,15 @@ private void notifyListenersAboutFinishedJob(SchedulableJob job) { public String getName() { return job.getJobID().toString(); } - + public JobID getWorkflowID() { return job.getJobID(); } @Override public void run() { - if( nextRun != null && (getNextRun() == null || - getNextRun().getTime() <= System.currentTimeMillis())) { + if (nextRun != null && (getNextRun() == null || + getNextRun().getTime() <= System.currentTimeMillis())) { runJob(); } } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/SchedulableJob.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/SchedulableJob.java index af8809583..87e82842f 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/SchedulableJob.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/SchedulableJob.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Integrity Client - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,42 +27,43 @@ /** * Interface for defining a SchedulableJob. - * A SchedulableJob performs a given task for the respective service. + * A SchedulableJob performs a given task for the respective service. */ public interface SchedulableJob { /** * Start the SchedulableJob. */ void start(); - + /** * @return The current state of the SchedulableJob. */ WorkflowState currentState(); - + /** * @param newState The new state for the workflow. */ void setCurrentState(WorkflowState newState); - + /** - * @return A human readable text telling the current state of the SchedulableJob. + * @return A human-readable text telling the current state of the SchedulableJob. */ String getHumanReadableState(); - + /** - * @return Provides a human readable description of the SchedulableJob. + * @return Provides a human-readable description of the SchedulableJob. */ String getDescription(); - + /** - * @return Provides an ID to identify the SchedulableJob on. + * @return Provides an ID to identify the SchedulableJob on. */ JobID getJobID(); /** * Initializes a SchedulableJob with a context and a collection to run the SchedulableJob on. - * @param context workflow context. + * + * @param context workflow context. * @param collectionID collection id. */ void initialise(WorkflowContext context, String collectionID); diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/Workflow.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/Workflow.java index 7d8315cf2..0ee520a70 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/Workflow.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/Workflow.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -27,20 +27,15 @@ /** * Abstract interface for running a SchedulableJob based on WorkflowSteps. + * * @see SchedulableJob {@link SchedulableJob} - * @see WorkflowStep {@link WorkflowStep} + * @see WorkflowStep {@link WorkflowStep} */ public abstract class Workflow implements SchedulableJob { - /** The jobID. */ protected JobID jobID; - /** The log.*/ - private Logger log = LoggerFactory.getLogger(getClass()); - - /** The current step running.*/ + private final Logger log = LoggerFactory.getLogger(getClass()); private WorkflowStep currentStep = null; - /** The current state of the workflow. */ private WorkflowState currentState = WorkflowState.NOT_RUNNING; - /** Statistics for the workflow.*/ private WorkflowStatistic statistics; @Override @@ -51,10 +46,11 @@ public synchronized void start() { /** * Initiates the given step and sets it to the current running step. + * * @param step The step to start. */ protected void performStep(WorkflowStep step) { - if(currentState != WorkflowState.ABORTED) { + if (currentState != WorkflowState.ABORTED) { this.currentState = WorkflowState.RUNNING; this.currentStep = step; log.info("Starting step: '" + step.getName() + "'"); @@ -63,7 +59,7 @@ protected void performStep(WorkflowStep step) { step.performStep(); } catch (WorkflowAbortedException e) { this.currentState = WorkflowState.ABORTED; - log.warn("Failure occured, aborting workflow", e); + log.warn("Failure occurred, aborting workflow", e); } catch (Exception e) { log.error("Failure in step: '" + step.getName() + "'.", e); throw new RuntimeException("Failed to run step " + step.getName(), e); @@ -73,7 +69,7 @@ protected void performStep(WorkflowStep step) { } } } - + /** * For telling that the workflow has finished its task. */ @@ -83,15 +79,16 @@ protected void finish() { this.currentStep = null; log.info(statistics.getFullStatistics()); } - + /** * Get the final state of the workflow. + * * @return ABORTED if current state is ABORTED, SUCCEEDED otherwise. */ private WorkflowState getFinishedWorkflowStatus() { return (currentState == WorkflowState.ABORTED ? WorkflowState.ABORTED : WorkflowState.SUCCEEDED); } - + @Override public WorkflowState currentState() { return currentState; @@ -104,7 +101,7 @@ public void setCurrentState(WorkflowState newState) { @Override public String getHumanReadableState() { - if(currentStep == null) { + if (currentStep == null) { return currentState.name(); } else { return currentStep.getName(); @@ -115,7 +112,7 @@ public String getHumanReadableState() { * @return The statistics for this workflow. */ public synchronized WorkflowStatistic getWorkflowStatistics() { - if(statistics == null) { + if (statistics == null) { statistics = new WorkflowStatistic(getClass().getSimpleName()); } return statistics; @@ -131,9 +128,7 @@ public boolean equals(Object o) { if (this == o) return true; Workflow that = (Workflow) o; - if (!jobID.equals(that.jobID)) return false; - - return true; + return jobID.equals(that.jobID); } @Override diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowContext.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowContext.java index f7668a502..f88914fe8 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowContext.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowContext.java @@ -1,20 +1,20 @@ package org.bitrepository.service.workflow;/* * #%L - * Bitrepository Integrity Service + * BitRepository Integrity Service * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowManager.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowManager.java index 00a361716..cd36c0188 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowManager.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowManager.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -39,7 +39,6 @@ /** * WorkflowManager manages one or more workflows including statistics and monitors state. - * */ public abstract class WorkflowManager { private final Logger log = LoggerFactory.getLogger(this.getClass()); @@ -84,7 +83,7 @@ public WorkflowStatistic getLastCompleteStatistics(JobID workflowID) { getWorkflow(workflowID); if (statistics.containsKey(workflowID)) { List stats = statistics.get(workflowID); - return stats.get(stats.size()-1); + return stats.get(stats.size() - 1); } else return null; } @@ -113,21 +112,21 @@ public long getRunInterval(JobID jobID) { } private void loadWorkFlows(WorkflowSettings configuration) { - for (WorkflowConfiguration workflowConf:configuration.getWorkflow()) { + for (WorkflowConfiguration workflowConf : configuration.getWorkflow()) { log.info("Scheduling from configuration: " + workflowConf); List unscheduledCollections = new LinkedList<>(SettingsUtils.getAllCollectionsIDs()); try { if (workflowConf.getSchedules() != null) { - for (Schedule schedule:workflowConf.getSchedules().getSchedule()) { + for (Schedule schedule : workflowConf.getSchedules().getSchedule()) { List collectionsToScheduleWorkflowFor; if (schedule.isSetCollections()) { collectionsToScheduleWorkflowFor = schedule.getCollections().getCollectionID(); } else { collectionsToScheduleWorkflowFor = SettingsUtils.getAllCollectionsIDs(); } - for (String collectionID:collectionsToScheduleWorkflowFor) { + for (String collectionID : collectionsToScheduleWorkflowFor) { Workflow workflow = - (Workflow)lookupClass(workflowConf.getWorkflowClass()).getDeclaredConstructor().newInstance(); + (Workflow) lookupClass(workflowConf.getWorkflowClass()).getDeclaredConstructor().newInstance(); workflow.initialise(context, collectionID); scheduler.schedule(workflow, schedule.getWorkflowInterval()); addWorkflow(collectionID, workflow); @@ -136,9 +135,9 @@ private void loadWorkFlows(WorkflowSettings configuration) { } } // Create a instance of all workflows not explicitly scheduled. - for (String collectionID:unscheduledCollections) { + for (String collectionID : unscheduledCollections) { Workflow workflow = - (Workflow)Class.forName(workflowConf.getWorkflowClass()).getDeclaredConstructor().newInstance(); + (Workflow) Class.forName(workflowConf.getWorkflowClass()).getDeclaredConstructor().newInstance(); workflow.initialise(context, collectionID); addWorkflow(collectionID, workflow); } @@ -167,8 +166,9 @@ private void addWorkflow(String collectionID, Workflow workflow) { } /** - * Allows subclasses to define a workflow package where workflow classes defined with a simplename in the settings + * Allows subclasses to define a workflow package where workflow classes defined with a simple name in the settings * will be prefixed with the namespace defined here. + * * @return default workflow package string. */ protected abstract String getDefaultWorkflowPackage(); @@ -186,7 +186,8 @@ public void jobFailed(SchedulableJob job) {} /** * Adds the workflow statistics to the statistics list for this workflow. Will also remove older statistics * if the number of statistics exceeds MAX_NUMBER_OF_STATISTICS_FOR_A_WORKFLOW. - * @param job The job which finished and to add statistics from + * + * @param job The job which finished and to add statistics from */ @Override public void jobFinished(SchedulableJob job) { @@ -196,7 +197,7 @@ public void jobFinished(SchedulableJob job) { } List workflowStatistics = statistics.get(job.getJobID()); - workflowStatistics.add((((Workflow)job).getWorkflowStatistics())); + workflowStatistics.add((((Workflow) job).getWorkflowStatistics())); if (workflowStatistics.size() > MAX_NUMBER_OF_STATISTICS_FOR_A_WORKFLOW) { workflowStatistics.remove(0); } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowState.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowState.java index 569e40fca..aa9631954 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowState.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowState.java @@ -1,23 +1,23 @@ /* * #%L * Bitrepository Service - * + * * $Id$ * $HeadURL$ * %% * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -31,31 +31,25 @@ */ @XmlRootElement public enum WorkflowState { - /** When the workflow is not running.*/ NOT_RUNNING("Not running"), - /** When the workflow is waiting to be run.*/ WAITING("Waiting"), - /** When the workflow is running.*/ RUNNING("Running"), - /** When an execution of the workflow has been aborted. */ ABORTED("Aborted"), - /** When the workflow have finished. */ SUCCEEDED("Succeeded"); - + /** - * Constructor. - * @param humanName Human readable form of the enum. + * @param humanName Human-readable form of the enum. */ WorkflowState(String humanName) { this.humanName = humanName; } - + /** - * Human readable text of the enum. + * Human-readable text of the enum. */ - private String humanName; - - @Override + private final String humanName; + + @Override public String toString() { return humanName; } diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStatistic.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStatistic.java index 724d7a869..ab2d86557 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStatistic.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStatistic.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -29,7 +29,7 @@ import java.util.List; /** - * Provides details about the statistics of an workflow. The statistics will not be fully populated until the + * Provides details about the statistics of a workflow. The statistics will not be fully populated until the * workflow has finished. */ public class WorkflowStatistic { @@ -43,6 +43,7 @@ public class WorkflowStatistic { /** * Creates a fresh WorkflowStatistic instance. + * * @param name The name of this instance to be used as title for the statistics. */ public WorkflowStatistic(String name) { @@ -57,8 +58,9 @@ public void start() { } /** - * Marks the start time of a sub step of the statistics statistics. - * @param name The name of the substep to be used as identifier in the statistics. + * Marks the start time of a sub step of the statistics. + * + * @param name The name of the sub-step to be used as identifier in the statistics. */ public void startSubStatistic(String name) { subStatistics.add(new WorkflowStatistic(name)); @@ -66,7 +68,8 @@ public void startSubStatistic(String name) { } /** - * Marks the end time of a sub step of the statistics statistics. + * Marks the end time of a sub step of the statistics. + * * @param state what state the sub step ended in. */ public void finishSubStatistic(WorkflowState state) { @@ -74,30 +77,30 @@ public void finishSubStatistic(WorkflowState state) { } /** - * @return A string representation of statistics, including all substatistics. + * @return A string representation of statistics, including all sub-statistics. */ public String getFullStatistics() { if (start == null) { return "Haven't finished a run yet"; } StringBuilder sb = new StringBuilder(); - sb.append(getName() + " duration: " + TimeUtils.millisecondsToHuman(getDuration())); - for (WorkflowStatistic stepStat: subStatistics) { - sb.append(LINEFEED +stepStat.getFullStatistics()); + sb.append(getName()).append(" duration: ").append(TimeUtils.millisecondsToHuman(getDuration())); + for (WorkflowStatistic stepStat : subStatistics) { + sb.append(LINEFEED).append(stepStat.getFullStatistics()); } return sb.toString(); } /** * Humanly readable string indicating how long the current step has run and the total time the workflow has flown. + * * @return a string of the form 'step duration'/'workflow duration'. If the workflow isn't running * a "Not running" string will be returned. */ public String getPartStatistics() { if (start == null) { return "Not started yet"; - } - else if (finish != null ) { + } else if (finish != null) { return "Idle"; } else { WorkflowStatistic currentSubStatistic = getCurrentSubStatistic(); @@ -110,16 +113,18 @@ else if (finish != null ) { /** * Helper to get the status of the latest step. + * * @return statistics for the current step if the workflow statistics have an active step. */ public WorkflowStatistic getCurrentSubStatistic() { if (subStatistics.isEmpty() || finish != null) { return null; - } else return subStatistics.get(subStatistics.size()-1); + } else return subStatistics.get(subStatistics.size() - 1); } /** * Get the start date of the statistics. + * * @return starting time as a Date. */ public Date getStart() { @@ -128,22 +133,25 @@ public Date getStart() { /** * Get the finish date of the statistics. + * * @return finish time as a Date. */ public Date getFinish() { return finish; } - + /** * Get the final state of the workflow. + * * @return the final state of the workflow as a WorkflowState. */ public WorkflowState getFinishState() { return finishState; } - + /** * Mark this part of the workflow as finished. + * * @param finishState The state at which the workflow (or step) finished at */ public void finish(WorkflowState finishState) { diff --git a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStep.java b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStep.java index a1ff036d2..81a14a078 100644 --- a/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStep.java +++ b/bitrepository-service/src/main/java/org/bitrepository/service/workflow/WorkflowStep.java @@ -5,16 +5,16 @@ * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 2.1 of the + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public + * + * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * . * #L% @@ -32,10 +32,11 @@ public interface WorkflowStep { * @return The name of this given step in the workflow. */ String getName(); - + /** * Perform the task wrapped in this step. - * @throws StepFailedException if the task failed + * + * @throws StepFailedException if the task failed * @throws WorkflowAbortedException if the workflow was aborted */ void performStep() throws StepFailedException, WorkflowAbortedException; diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java index cbb62f48d..0be217d7c 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseMigrationTest.java @@ -35,9 +35,9 @@ import java.io.File; -import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDITTRAIL_AUDIT; +import static org.bitrepository.service.audit.AuditDatabaseConstants.AUDIT_TRAIL_AUDIT; import static org.bitrepository.service.audit.AuditDatabaseConstants.DATABASE_VERSION_ENTRY; -import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_FILEID; +import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_FILE_ID; import static org.bitrepository.service.audit.AuditDatabaseConstants.FILE_TABLE; import static org.testng.Assert.assertEquals; @@ -81,11 +81,11 @@ public void testMigratingAuditContributorDatabase() { String extractVersionSql = "SELECT version FROM tableversions WHERE tablename = ?"; int fileTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, FILE_TABLE); assertEquals(fileTableVersionBefore, 1, "File table before migration"); - int auditTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDITTRAIL_AUDIT); + int auditTableVersionBefore = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDIT_TRAIL_AUDIT); assertEquals(auditTableVersionBefore, 1, "Table version before migration"); addStep("Ingest a entry to the database without the collection id", "works only in version 1."); - String sqlInsert = "INSERT INTO " + FILE_TABLE + " ( " + FILE_FILEID + " ) VALUES ( ? )"; + String sqlInsert = "INSERT INTO " + FILE_TABLE + " ( " + FILE_FILE_ID + " ) VALUES ( ? )"; DatabaseUtils.executeStatement(connector, sqlInsert, FILE_ID); addStep("Perform migration", "File table has version 2, audit table version 5 and database-version is 5"); @@ -93,7 +93,7 @@ public void testMigratingAuditContributorDatabase() { migrator.migrate(); int fileTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, FILE_TABLE); assertEquals(fileTableVersionAfter, 2, "Table version after migration"); - int auditTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDITTRAIL_AUDIT); + int auditTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, AUDIT_TRAIL_AUDIT); assertEquals(auditTableVersionAfter, 5, "Table version after migration"); int dbTableVersionAfter = DatabaseUtils.selectIntValue(connector, extractVersionSql, DATABASE_VERSION_ENTRY); assertEquals(dbTableVersionAfter, AuditTrailContributorDatabaseMigrator.CURRENT_VERSION, "Table version after migration"); diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java index d03decba9..f7e905d03 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/audit/AuditTrailContributorDatabaseTest.java @@ -21,11 +21,6 @@ */ package org.bitrepository.service.audit; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - import org.bitrepository.bitrepositoryelements.FileAction; import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.TestSettingsProvider; @@ -39,6 +34,11 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + /** Run audit trail contributor database test using Derby. Generates jaccept reports. */ public class AuditTrailContributorDatabaseTest extends ExtendedTestCase { @@ -74,7 +74,7 @@ public void testAuditTrailDatabaseExtraction() throws Exception { addDescription("Testing the basic functions of the audit trail database interface."); addStep("Setup varibles and the database connection.", "No errors."); DatabaseManager dm = new AuditDatabaseManager(databaseSpecifics); - AuditTrailContributerDAO daba = new DerbyAuditTrailContributorDAO(dm); + AuditTrailContributorDAO daba = new DerbyAuditTrailContributorDAO(dm); daba.initialize(settings.getComponentID()); addStep("Populate the database.", "Should be inserted into database."); @@ -131,7 +131,7 @@ public void testAuditTrailDatabaseExtractionOrder() throws Exception { addDescription("Test the order of extraction"); addStep("Setup variables and database connection", "No errors"); DatabaseManager dm = new AuditDatabaseManager(databaseSpecifics); - AuditTrailContributerDAO daba = new DerbyAuditTrailContributorDAO(dm); + AuditTrailContributorDAO daba = new DerbyAuditTrailContributorDAO(dm); daba.initialize(settings.getComponentID()); addStep("Populate the database.", "Should be inserted into database."); @@ -167,7 +167,7 @@ public void testAuditTrailDatabaseExtractionOrder() throws Exception { public void contributorDatabaseCorrectTimestampTest() throws ParseException { addDescription("Testing the correct ingest and extraction of audittrail dates"); DatabaseManager dm = new AuditDatabaseManager(databaseSpecifics); - AuditTrailContributerDAO daba = new DerbyAuditTrailContributorDAO(dm); + AuditTrailContributorDAO daba = new DerbyAuditTrailContributorDAO(dm); daba.initialize(settings.getComponentID()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); @@ -212,7 +212,7 @@ public void testAuditTrailDatabaseIngest() throws Exception { } DatabaseManager dm = new AuditDatabaseManager(databaseSpecifics); - AuditTrailContributerDAO daba = new DerbyAuditTrailContributorDAO(dm); + AuditTrailContributorDAO daba = new DerbyAuditTrailContributorDAO(dm); daba.initialize(settings.getComponentID()); addStep("Test with all data.", "No failures"); diff --git a/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java b/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java index 4535062cb..111596fe7 100644 --- a/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java +++ b/bitrepository-service/src/test/java/org/bitrepository/service/exception/IllegalOperationExceptionTest.java @@ -21,15 +21,15 @@ */ package org.bitrepository.service.exception; +import org.bitrepository.bitrepositoryelements.ResponseCode; +import org.jaccept.structure.ExtendedTestCase; +import org.testng.annotations.Test; + import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; -import org.bitrepository.bitrepositoryelements.ResponseCode; -import org.jaccept.structure.ExtendedTestCase; -import org.testng.annotations.Test; - /** * Test that IllegalOperationException behaves as expected. */ diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/BasicClient.java b/bitrepository-webclient/src/main/java/org/bitrepository/BasicClient.java index 1d455ad9c..673511aef 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/BasicClient.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/BasicClient.java @@ -21,15 +21,15 @@ */ package org.bitrepository; -import java.util.ArrayList; -import java.util.List; - import org.bitrepository.common.settings.Settings; import org.bitrepository.settings.repositorysettings.Collection; import org.bitrepository.settings.repositorysettings.RepositorySettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + public class BasicClient { private Settings settings; private final Logger log = LoggerFactory.getLogger(getClass()); diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/BasicClientFactory.java b/bitrepository-webclient/src/main/java/org/bitrepository/BasicClientFactory.java index 17fee7ab3..d460c81ec 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/BasicClientFactory.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/BasicClientFactory.java @@ -21,13 +21,6 @@ */ package org.bitrepository; -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Properties; - import org.bitrepository.common.settings.Settings; import org.bitrepository.common.settings.SettingsProvider; import org.bitrepository.common.settings.XMLFileSettingsLoader; @@ -36,6 +29,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Properties; + public class BasicClientFactory { private static final Logger log = LoggerFactory.getLogger(BasicClientFactory.class); private static BasicClient client; diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java b/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java index bb084fce3..bc37f3742 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/utils/LogbackConfigLoader.java @@ -21,15 +21,14 @@ */ package org.bitrepository.utils; -import java.io.File; -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; public class LogbackConfigLoader { private Logger log = LoggerFactory.getLogger(LogbackConfigLoader.class); diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/utils/XMLGregorianCalendarConverter.java b/bitrepository-webclient/src/main/java/org/bitrepository/utils/XMLGregorianCalendarConverter.java index 21417b051..3072dc728 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/utils/XMLGregorianCalendarConverter.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/utils/XMLGregorianCalendarConverter.java @@ -21,13 +21,13 @@ */ package org.bitrepository.utils; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.XMLGregorianCalendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; /** * Utility class for converting between XMLGregorianCalendar and java.util.Date diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java index dd5a1fb68..8a7a4d657 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/Reposervice.java @@ -21,26 +21,24 @@ */ package org.bitrepository.webservice; -import java.io.IOException; -import java.io.StringWriter; -import java.util.List; -import java.util.stream.Collectors; - +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonGenerator; import org.bitrepository.BasicClient; import org.bitrepository.BasicClientFactory; import org.bitrepository.common.utils.SettingsUtils; import org.bitrepository.settings.repositorysettings.Collection; import org.bitrepository.settings.repositorysettings.ProtocolSettings; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.core.JsonGenerator; - import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.io.StringWriter; +import java.util.List; +import java.util.stream.Collectors; /** * The class exposes the REST webservices provided by the Bitrepository-webclient using CXF. diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/ServiceUrl.java b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/ServiceUrl.java index 4e738dc79..ee2c18a75 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/ServiceUrl.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/ServiceUrl.java @@ -21,6 +21,13 @@ */ package org.bitrepository.webservice; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; @@ -28,14 +35,6 @@ import java.nio.charset.StandardCharsets; import java.util.Properties; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - @Path("/urlservice") public class ServiceUrl { private static final String CONFIGFILE = "services.properties"; diff --git a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/WebclientContextListener.java b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/WebclientContextListener.java index 96fbf654e..128674b7e 100644 --- a/bitrepository-webclient/src/main/java/org/bitrepository/webservice/WebclientContextListener.java +++ b/bitrepository-webclient/src/main/java/org/bitrepository/webservice/WebclientContextListener.java @@ -21,15 +21,15 @@ */ package org.bitrepository.webservice; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - import org.bitrepository.BasicClient; import org.bitrepository.BasicClientFactory; import org.bitrepository.utils.LogbackConfigLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + /** * The Listener has two intentions diff --git a/bitrepository-webclient/src/main/webapp/WEB-INF/web.xml b/bitrepository-webclient/src/main/webapp/WEB-INF/web.xml index 8b9ad243f..3954fafe6 100644 --- a/bitrepository-webclient/src/main/webapp/WEB-INF/web.xml +++ b/bitrepository-webclient/src/main/webapp/WEB-INF/web.xml @@ -1,7 +1,7 @@