Merged latest trunk updates to branch
authorPatric Plitzner <p.plitzner@bgbm.org>
Mon, 29 Oct 2012 14:29:01 +0000 (14:29 +0000)
committerPatric Plitzner <p.plitzner@bgbm.org>
Mon, 29 Oct 2012 14:29:01 +0000 (14:29 +0000)
39 files changed:
.gitattributes
cdmlib-ext/src/test/java/eu/etaxonomy/cdm/ext/geo/EditGeoServiceTest.java
cdmlib-io/pom.xml
cdmlib-io/src/main/java/eu/etaxonomy/cdm/io/common/CdmApplicationAwareDefaultImport.java
cdmlib-io/src/main/java/eu/etaxonomy/cdm/io/tcsxml/in/CdmTcsXmlImport.java
cdmlib-io/src/test/resources/eu/etaxonomy/cdm/applicationContext-test.xml
cdmlib-model/pom.xml
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/common/GrantedAuthorityImpl.java
cdmlib-model/src/main/java/eu/etaxonomy/cdm/model/common/User.java
cdmlib-persistence/pom.xml
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/CdmDeleteListener.java
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/CdmHibernateInterceptor.java
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/CdmAuthority.java
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/CdmPermissionEvaluator.java
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/IGrantedAuthorityConverter.java [new file with mode: 0644]
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/Role.java [new file with mode: 0644]
cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/voter/CdmPermissionVoter.java
cdmlib-persistence/src/main/resources/eu/etaxonomy/cdm/persistence_security.xml
cdmlib-persistence/src/test/java/eu/etaxonomy/cdm/persistence/dao/hibernate/taxon/TaxonNodeDaoHibernateImplTest.java
cdmlib-remote/src/main/java/eu/etaxonomy/cdm/remote/config/DataSourceConfigurer.java
cdmlib-services/pom.xml
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationController.java
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/FirstDataInserter.java [new file with mode: 0644]
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/MonitoredGenericApplicationContext.java
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/service/ServiceBase.java
cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/service/UserService.java
cdmlib-services/src/main/resources/eu/etaxonomy/cdm/services.xml
cdmlib-services/src/main/resources/eu/etaxonomy/cdm/services_security.xml
cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.java [new file with mode: 0644]
cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/ClassificationServiceImplTest.java
cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/DescriptionServiceImplTest.java
cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/SecurityTest.java
cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/service/TaxonServiceSearchTest.java
cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB-result.xml [new file with mode: 0644]
cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB.xml [new file with mode: 0644]
cdmlib-services/src/test/resources/eu/etaxonomy/cdm/applicationContext-securityTest.xml
cdmlib-services/src/test/resources/eu/etaxonomy/cdm/applicationContext-test.xml
cdmlib-services/src/test/resources/log4j.properties
pom.xml

index c092e68937185a0be49aed2e351a5ae0dd5b635e..ea094a122debaa576d14e708d55a0bb7e054b816 100644 (file)
@@ -1329,7 +1329,9 @@ cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permissi
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/CdmAuthority.java -text
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/CdmPermissionClass.java -text
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/CdmPermissionEvaluator.java -text
+cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/IGrantedAuthorityConverter.java -text
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/Operation.java -text
+cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/Role.java -text
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/voter/CdmPermissionVoter.java -text
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/voter/DescriptionBaseVoter.java -text
 cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/voter/DescriptionElementVoter.java -text
@@ -1835,6 +1837,7 @@ cdmlib-services/README.TXT -text
 cdmlib-services/pom.xml -text
 cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationController.java -text
 cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/CdmApplicationDefaultConfiguration.java -text
+cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/FirstDataInserter.java -text
 cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/ICdmApplicationConfiguration.java -text
 cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/MonitoredGenericApplicationContext.java -text
 cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/MonitoredListableBeanFactory.java -text
@@ -1988,6 +1991,7 @@ cdmlib-services/src/main/resources/wsdl/LSIDDataServiceFileBindings.wsdl -text
 cdmlib-services/src/main/resources/wsdl/LSIDDataServiceHTTPBindings.wsdl -text
 cdmlib-services/src/main/resources/wsdl/LSIDDataServiceSOAPBindings.wsdl -text
 cdmlib-services/src/main/resources/wsdl/LSIDPortTypes.wsdl -text
+cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.java -text
 cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/facade/DerivedUnitFacadeCacheStrategyTest.java -text
 cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/facade/DerivedUnitFacadeFieldObservationCacheStrategyTest.java -text
 cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/facade/DerivedUnitFacadeTest.java -text
@@ -2037,6 +2041,8 @@ cdmlib-services/src/test/java/eu/etaxonomy/cdm/validation/NeededForCorrectTermLo
 cdmlib-services/src/test/java/eu/etaxonomy/cdm/validation/ValidationTest.java -text
 cdmlib-services/src/test/resources/dbscripts/001-cdm.h2.sql -text
 cdmlib-services/src/test/resources/dbscripts/hibernate.properties -text
+cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB-result.xml -text
+cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB.xml -text
 cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/facade/DerivedUnitFacadeTest.testSetDerivedUnitImageGallery-result.xml -text
 cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/facade/DerivedUnitFacadeTest.testSetDerivedUnitImageGallery.xml -text
 cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/facade/DerivedUnitFacadeTest.testSetFieldObjectImageGallery-result.xml -text
index 6470fb6eb1a489081e279e6c40c00b0920b95fbf..3803c046f8fd571ef9fd31fe911ecc3e15a9af34 100644 (file)
@@ -33,14 +33,12 @@ import org.apache.log4j.Logger;
 import org.junit.After;\r
 import org.junit.AfterClass;\r
 import org.junit.Before;\r
-import org.junit.BeforeClass;\r
 import org.junit.Test;\r
 import org.unitils.spring.annotation.SpringBeanByType;\r
 \r
 import eu.etaxonomy.cdm.common.CdmUtils;\r
 import eu.etaxonomy.cdm.common.StreamUtils;\r
 import eu.etaxonomy.cdm.common.UriUtils;\r
-import eu.etaxonomy.cdm.model.common.DefaultTermInitializer;\r
 import eu.etaxonomy.cdm.model.common.Language;\r
 import eu.etaxonomy.cdm.model.common.TermVocabulary;\r
 import eu.etaxonomy.cdm.model.description.AbsenceTerm;\r
@@ -60,17 +58,17 @@ import eu.etaxonomy.cdm.test.integration.CdmIntegrationTest;
  * @version 1.0\r
  */\r
 public class EditGeoServiceTest extends CdmIntegrationTest {\r
-       @SuppressWarnings("unused")\r
-       private static final Logger logger = Logger.getLogger(EditGeoServiceTest.class);\r
+    @SuppressWarnings("unused")\r
+    private static final Logger logger = Logger.getLogger(EditGeoServiceTest.class);\r
 \r
-       private static final String EDIT_MAPSERVICE_URI_STING = "http://edit.br.fgov.be/edit_wp5/v1/areas.php";\r
-       private static URI editMapServiceUri;\r
+    private static final String EDIT_MAPSERVICE_URI_STING = "http://edit.br.fgov.be/edit_wp5/v1/areas.php";\r
+    private static URI editMapServiceUri;\r
 \r
-       //@SpringBeanByType\r
-       private IDefinedTermDao termDao;\r
+    //@SpringBeanByType\r
+    private IDefinedTermDao termDao;\r
 \r
-       @SpringBeanByType\r
-       private GeoServiceAreaAnnotatedMapping mapping;\r
+    @SpringBeanByType\r
+    private GeoServiceAreaAnnotatedMapping mapping;\r
 \r
 //\r
 //     /**\r
@@ -82,144 +80,144 @@ public class EditGeoServiceTest extends CdmIntegrationTest {
 //             initializer.initialize();\r
 //     }\r
 \r
-       /**\r
-        * @throws java.lang.Exception\r
-        */\r
-       @AfterClass\r
-       public static void tearDownAfterClass() throws Exception {\r
-       }\r
-\r
-       /**\r
-        * @throws java.lang.Exception\r
-        */\r
-       @Before\r
-       public void setUp() throws Exception {\r
-               EditGeoServiceUtilities.setTermDao(termDao);\r
-               System.setProperty("ONLY-A-TEST", "TRUE"); // allows EditGeoServiceUtilities to skip some line of code\r
-               editMapServiceUri = new URI(EDIT_MAPSERVICE_URI_STING);\r
-       }\r
-\r
-       /**\r
-        * @throws java.lang.Exception\r
-        */\r
-       @After\r
-       public void tearDown() throws Exception {\r
-       }\r
+    /**\r
+     * @throws java.lang.Exception\r
+     */\r
+    @AfterClass\r
+    public static void tearDownAfterClass() throws Exception {\r
+    }\r
+\r
+    /**\r
+     * @throws java.lang.Exception\r
+     */\r
+    @Before\r
+    public void setUp() throws Exception {\r
+        EditGeoServiceUtilities.setTermDao(termDao);\r
+        System.setProperty("ONLY-A-TEST", "TRUE"); // allows EditGeoServiceUtilities to skip some line of code\r
+        editMapServiceUri = new URI(EDIT_MAPSERVICE_URI_STING);\r
+    }\r
+\r
+    /**\r
+     * @throws java.lang.Exception\r
+     */\r
+    @After\r
+    public void tearDown() throws Exception {\r
+    }\r
 \r
 //******************************************** TESTS**************\r
-       @Test\r
-       public void testGetWebServiceUrlTdwg() throws MalformedURLException, IOException {\r
-               //String webServiceUrl = "http://www.test.de/webservice";\r
-               Set<Distribution> distributions = new HashSet<Distribution>();\r
-               distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("SPA"), PresenceTerm.PRESENT()));\r
-               distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("GER"), PresenceTerm.INTRODUCED()));\r
-               distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("14"), PresenceTerm.CULTIVATED()));\r
-               distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("BGM"), AbsenceTerm.ABSENT()));\r
-               distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("FRA"), AbsenceTerm.ABSENT()));\r
-               distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("IND-AP"), PresenceTerm.PRESENT()));\r
-\r
-               Map<PresenceAbsenceTermBase<?>, Color> presenceAbsenceColorMap = new HashMap<PresenceAbsenceTermBase<?>, Color>();\r
-               presenceAbsenceColorMap.put(PresenceTerm.PRESENT(), Color.BLUE);\r
-               presenceAbsenceColorMap.put(PresenceTerm.INTRODUCED(), Color.BLACK);\r
-               presenceAbsenceColorMap.put(PresenceTerm.CULTIVATED(), Color.YELLOW);\r
-               presenceAbsenceColorMap.put(AbsenceTerm.ABSENT(), Color.DARK_GRAY);\r
-               String backLayer ="";\r
-               presenceAbsenceColorMap = null;\r
-               String bbox="-20,0,120,70";\r
-               List<Language> languages = new ArrayList<Language>();\r
-\r
-               String result = EditGeoServiceUtilities.getDistributionServiceRequestParameterString(distributions, mapping, presenceAbsenceColorMap, 600, 300, bbox,backLayer, null, languages );\r
-               //TODO Set semantics is not determined\r
-               //String expected = "http://www.test.de/webservice?l=tdwg3&ad=tdwg3:a:GER|b:OKL|c:BGM|b:SPA|d:FRA&as=a:005500|b:00FF00|c:FFFFFF|d:001100&bbox=-20,40,40,40&ms=400x300";\r
-               System.out.println(result);\r
-               assertTrue(result.matches(".*l=earth.*"));\r
-               assertTrue(result.matches(".*ms=600,300.*"));\r
-               assertTrue(result.matches(".*ad=tdwg[1-4].*"));\r
-               assertTrue(result.matches(".*tdwg2:[a-d]:14[\\|&].*") );\r
-               assertTrue(result.matches(".*[a-d]:FRA,BGM[\\|&].*") || result.matches(".*[a-d]:BGM,FRA[\\|&].*") );\r
-               assertTrue(result.matches(".*[a-d]:GER[\\|&].*") );\r
-               assertTrue(result.matches(".*[a-d]:SPA[\\|&].*") );\r
-               assertTrue(result.matches(".*tdwg4:[a-d]:INDAP[\\|&].*") );\r
-               //assertTrue(result.matches("0000ff"));\r
-               //TODO continue\r
-\r
-               // request map image from webservice\r
-               subTestWithEditMapService(result);\r
-       }\r
-\r
-       @Test\r
-       public void testGetWebServiceUrlCyprus() throws ClientProtocolException, IOException, URISyntaxException {\r
-               makeCyprusAreas();\r
-               Set<Distribution> distributions = new HashSet<Distribution>();\r
-               distributions.add(Distribution.NewInstance(divisions.get("1"), PresenceTerm.PRESENT()));\r
-               distributions.add(Distribution.NewInstance(divisions.get("2"), PresenceTerm.INTRODUCED()));\r
-               distributions.add(Distribution.NewInstance(divisions.get("3"), PresenceTerm.CULTIVATED()));\r
-               distributions.add(Distribution.NewInstance(divisions.get("4"), AbsenceTerm.ABSENT()));\r
-               distributions.add(Distribution.NewInstance(divisions.get("5"), AbsenceTerm.ABSENT()));\r
-               distributions.add(Distribution.NewInstance(divisions.get("6"), PresenceTerm.PRESENT()));\r
-\r
-               Map<PresenceAbsenceTermBase<?>, Color> presenceAbsenceColorMap = new HashMap<PresenceAbsenceTermBase<?>, Color>();\r
-               presenceAbsenceColorMap.put(PresenceTerm.PRESENT(), Color.BLUE);\r
-               presenceAbsenceColorMap.put(PresenceTerm.INTRODUCED(), Color.BLACK);\r
-               presenceAbsenceColorMap.put(PresenceTerm.CULTIVATED(), Color.YELLOW);\r
-               presenceAbsenceColorMap.put(AbsenceTerm.ABSENT(), Color.DARK_GRAY);\r
-               String backLayer ="";\r
-               presenceAbsenceColorMap = null;\r
-               String bbox="-20,0,120,70";\r
-               List<Language> languages = new ArrayList<Language>();\r
-\r
-               String result = EditGeoServiceUtilities.getDistributionServiceRequestParameterString(distributions, mapping, presenceAbsenceColorMap, 600, 300, bbox,backLayer, null, languages );\r
-               //TODO Set semantics is not determined\r
-               //String expected = "http://www.test.de/webservice?l=tdwg3&ad=tdwg3:a:GER|b:OKL|c:BGM|b:SPA|d:FRA&as=a:005500|b:00FF00|c:FFFFFF|d:001100&bbox=-20,40,40,40&ms=400x300";\r
-               assertTrue(result.matches(".*l=earth.*"));\r
-               assertTrue(result.matches(".*ms=600,300.*"));\r
-               assertTrue(result.matches(".*ad=cyprusdivs%3Abdcode:.*"));\r
-               assertTrue(result.matches(".*[a-d]:5,4[\\|&].*") || result.matches(".*[a-d]:4,5[\\|&].*") );\r
-               assertTrue(result.matches(".*[a-d]:1,6[\\|&].*") || result.matches(".*[a-d]:6,1[\\|&].*") );\r
-               assertTrue(result.matches(".*[a-d]:2[\\|&].*") );\r
-               assertTrue(result.matches(".*[a-d]:3[\\|&].*") );\r
-\r
-               // request map image from webservice\r
-               subTestWithEditMapService(result);\r
-       }\r
-\r
-       private void subTestWithEditMapService(String result)throws MalformedURLException, IOException {\r
-               if(UriUtils.isServiceAvailable(editMapServiceUri)){\r
-                       URL requestUrl = new URL(editMapServiceUri.toString() + "?img=false&" + result);\r
-                       HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();\r
-                       connection.connect();\r
-                       assertTrue(connection.getResponseCode() == 200);\r
-                       InputStream contentStream = connection.getInputStream();\r
-                       String content = StreamUtils.readToString(contentStream);\r
-                       System.out.println(content);\r
-                       assertTrue(content.startsWith("[{"));\r
-                       assertTrue(content.endsWith("}]"));\r
-                       assertTrue(content.matches(".*\"bbox\":.*"));\r
-                       assertTrue(content.matches(".*\"legend\":.*"));\r
-                       assertTrue(content.matches(".*\"layers\":.*"));\r
-                       assertTrue(content.matches(".*\"sld\":.*"));\r
-                       assertTrue(content.matches(".*\"geoserver\":.*"));\r
-               }\r
-       }\r
-\r
-       public static final UUID uuidCyprusDivisionsVocabulary = UUID.fromString("2119f610-1f93-4d87-af28-40aeefaca100");\r
-       private Map<String, NamedArea> divisions = new HashMap<String, NamedArea>();\r
-\r
-       private boolean makeCyprusAreas() {\r
-               //divisions\r
-\r
-\r
-               NamedAreaType areaType = NamedAreaType.NATURAL_AREA();\r
-               NamedAreaLevel areaLevel = NamedAreaLevel.NewInstance("Cyprus Division", "Cyprus Division", null);\r
-\r
-               TermVocabulary areaVocabulary = TermVocabulary.NewInstance("Cyprus devisions", "Cyprus divisions", null, null);\r
-               areaVocabulary.setUuid(uuidCyprusDivisionsVocabulary);\r
-\r
-               for(int i = 1; i <= 8; i++){\r
-                       UUID divisionUuid = getNamedAreaUuid(String.valueOf(i));\r
-                       NamedArea division = this.getNamedArea(divisionUuid, "Division " + i, "Cyprus: Division " + i, String.valueOf(i), areaType, areaLevel, areaVocabulary);\r
-                       divisions.put(String.valueOf(i), division);\r
-               }\r
+    @Test\r
+    public void testGetWebServiceUrlTdwg() throws MalformedURLException, IOException {\r
+        //String webServiceUrl = "http://www.test.de/webservice";\r
+        Set<Distribution> distributions = new HashSet<Distribution>();\r
+        distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("SPA"), PresenceTerm.PRESENT()));\r
+        distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("GER"), PresenceTerm.INTRODUCED()));\r
+        distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("14"), PresenceTerm.CULTIVATED()));\r
+        distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("BGM"), AbsenceTerm.ABSENT()));\r
+        distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("FRA"), AbsenceTerm.ABSENT()));\r
+        distributions.add(Distribution.NewInstance(TdwgArea.getAreaByTdwgAbbreviation("IND-AP"), PresenceTerm.PRESENT()));\r
+\r
+        Map<PresenceAbsenceTermBase<?>, Color> presenceAbsenceColorMap = new HashMap<PresenceAbsenceTermBase<?>, Color>();\r
+        presenceAbsenceColorMap.put(PresenceTerm.PRESENT(), Color.BLUE);\r
+        presenceAbsenceColorMap.put(PresenceTerm.INTRODUCED(), Color.BLACK);\r
+        presenceAbsenceColorMap.put(PresenceTerm.CULTIVATED(), Color.YELLOW);\r
+        presenceAbsenceColorMap.put(AbsenceTerm.ABSENT(), Color.DARK_GRAY);\r
+        String backLayer ="";\r
+        presenceAbsenceColorMap = null;\r
+        String bbox="-20,0,120,70";\r
+        List<Language> languages = new ArrayList<Language>();\r
+\r
+        String result = EditGeoServiceUtilities.getDistributionServiceRequestParameterString(distributions, mapping, presenceAbsenceColorMap, 600, 300, bbox,backLayer, null, languages );\r
+        //TODO Set semantics is not determined\r
+        //String expected = "http://www.test.de/webservice?l=tdwg3&ad=tdwg3:a:GER|b:OKL|c:BGM|b:SPA|d:FRA&as=a:005500|b:00FF00|c:FFFFFF|d:001100&bbox=-20,40,40,40&ms=400x300";\r
+        System.out.println(result);\r
+        assertTrue(result.matches(".*l=earth.*"));\r
+        assertTrue(result.matches(".*ms=600,300.*"));\r
+        assertTrue(result.matches(".*ad=tdwg[1-4].*"));\r
+        assertTrue(result.matches(".*tdwg2:[a-d]:14[\\|&].*") );\r
+        assertTrue(result.matches(".*[a-d]:FRA,BGM[\\|&].*") || result.matches(".*[a-d]:BGM,FRA[\\|&].*") );\r
+        assertTrue(result.matches(".*[a-d]:GER[\\|&].*") );\r
+        assertTrue(result.matches(".*[a-d]:SPA[\\|&].*") );\r
+        assertTrue(result.matches(".*tdwg4:[a-d]:INDAP[\\|&].*") );\r
+        //assertTrue(result.matches("0000ff"));\r
+        //TODO continue\r
+\r
+        // request map image from webservice\r
+        subTestWithEditMapService(result);\r
+    }\r
+\r
+    @Test\r
+    public void testGetWebServiceUrlCyprus() throws ClientProtocolException, IOException, URISyntaxException {\r
+        makeCyprusAreas();\r
+        Set<Distribution> distributions = new HashSet<Distribution>();\r
+        distributions.add(Distribution.NewInstance(divisions.get("1"), PresenceTerm.PRESENT()));\r
+        distributions.add(Distribution.NewInstance(divisions.get("2"), PresenceTerm.INTRODUCED()));\r
+        distributions.add(Distribution.NewInstance(divisions.get("3"), PresenceTerm.CULTIVATED()));\r
+        distributions.add(Distribution.NewInstance(divisions.get("4"), AbsenceTerm.ABSENT()));\r
+        distributions.add(Distribution.NewInstance(divisions.get("5"), AbsenceTerm.ABSENT()));\r
+        distributions.add(Distribution.NewInstance(divisions.get("6"), PresenceTerm.PRESENT()));\r
+\r
+        Map<PresenceAbsenceTermBase<?>, Color> presenceAbsenceColorMap = new HashMap<PresenceAbsenceTermBase<?>, Color>();\r
+        presenceAbsenceColorMap.put(PresenceTerm.PRESENT(), Color.BLUE);\r
+        presenceAbsenceColorMap.put(PresenceTerm.INTRODUCED(), Color.BLACK);\r
+        presenceAbsenceColorMap.put(PresenceTerm.CULTIVATED(), Color.YELLOW);\r
+        presenceAbsenceColorMap.put(AbsenceTerm.ABSENT(), Color.DARK_GRAY);\r
+        String backLayer ="";\r
+        presenceAbsenceColorMap = null;\r
+        String bbox="-20,0,120,70";\r
+        List<Language> languages = new ArrayList<Language>();\r
+\r
+        String result = EditGeoServiceUtilities.getDistributionServiceRequestParameterString(distributions, mapping, presenceAbsenceColorMap, 600, 300, bbox,backLayer, null, languages );\r
+        //TODO Set semantics is not determined\r
+        //String expected = "http://www.test.de/webservice?l=tdwg3&ad=tdwg3:a:GER|b:OKL|c:BGM|b:SPA|d:FRA&as=a:005500|b:00FF00|c:FFFFFF|d:001100&bbox=-20,40,40,40&ms=400x300";\r
+        assertTrue(result.matches(".*l=earth.*"));\r
+        assertTrue(result.matches(".*ms=600,300.*"));\r
+        assertTrue(result.matches(".*ad=cyprusdivs%3Abdcode:.*"));\r
+        assertTrue(result.matches(".*[a-d]:5,4[\\|&].*") || result.matches(".*[a-d]:4,5[\\|&].*") );\r
+        assertTrue(result.matches(".*[a-d]:1,6[\\|&].*") || result.matches(".*[a-d]:6,1[\\|&].*") );\r
+        assertTrue(result.matches(".*[a-d]:2[\\|&].*") );\r
+        assertTrue(result.matches(".*[a-d]:3[\\|&].*") );\r
+\r
+        // request map image from webservice\r
+        subTestWithEditMapService(result);\r
+    }\r
+\r
+    private void subTestWithEditMapService(String result)throws MalformedURLException, IOException {\r
+        if(UriUtils.isServiceAvailable(editMapServiceUri)){\r
+            URL requestUrl = new URL(editMapServiceUri.toString() + "?img=false&" + result);\r
+            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();\r
+            connection.connect();\r
+            assertTrue(connection.getResponseCode() == 200);\r
+            InputStream contentStream = connection.getInputStream();\r
+            String content = StreamUtils.readToString(contentStream);\r
+            System.out.println(content);\r
+            assertTrue(content.startsWith("[{"));\r
+            assertTrue(content.endsWith("}]"));\r
+            assertTrue(content.matches(".*\"bbox\":.*"));\r
+            assertTrue(content.matches(".*\"legend\":.*"));\r
+            assertTrue(content.matches(".*\"layers\":.*"));\r
+            assertTrue(content.matches(".*\"sld\":.*"));\r
+            assertTrue(content.matches(".*\"geoserver\":.*"));\r
+        }\r
+    }\r
+\r
+    public static final UUID uuidCyprusDivisionsVocabulary = UUID.fromString("2119f610-1f93-4d87-af28-40aeefaca100");\r
+    private Map<String, NamedArea> divisions = new HashMap<String, NamedArea>();\r
+\r
+    private boolean makeCyprusAreas() {\r
+        //divisions\r
+\r
+\r
+        NamedAreaType areaType = NamedAreaType.NATURAL_AREA();\r
+        NamedAreaLevel areaLevel = NamedAreaLevel.NewInstance("Cyprus Division", "Cyprus Division", null);\r
+\r
+        TermVocabulary areaVocabulary = TermVocabulary.NewInstance("Cyprus devisions", "Cyprus divisions", null, null);\r
+        areaVocabulary.setUuid(uuidCyprusDivisionsVocabulary);\r
+\r
+        for(int i = 1; i <= 8; i++){\r
+            UUID divisionUuid = getNamedAreaUuid(String.valueOf(i));\r
+            NamedArea division = this.getNamedArea(divisionUuid, "Division " + i, "Cyprus: Division " + i, String.valueOf(i), areaType, areaLevel, areaVocabulary);\r
+            divisions.put(String.valueOf(i), division);\r
+        }\r
 \r
 //             indigenousStatus = (PresenceTerm)getTermService().find(CyprusTransformer.indigenousUuid);\r
 //             casualStatus = (PresenceTerm)getTermService().find(CyprusTransformer.casualUuid);\r
@@ -227,85 +225,85 @@ public class EditGeoServiceTest extends CdmIntegrationTest {
 //             invasiveStatus = (PresenceTerm)getTermService().find(CyprusTransformer.invasiveUuid);\r
 //             questionableStatus = (PresenceTerm)getTermService().find(CyprusTransformer.questionableUuid);\r
 \r
-               return true;\r
-\r
-\r
-       }\r
-\r
-       public static final UUID uuidDivision1 = UUID.fromString("ab17eee9-1abb-4ce9-a9a2-563f840cdbfc");\r
-       public static final UUID uuidDivision2 = UUID.fromString("c3606165-efb7-4224-a168-63e009eb4aa5");\r
-       public static final UUID uuidDivision3 = UUID.fromString("750d4e07-e34b-491f-a7b7-09723afdc960");\r
-       public static final UUID uuidDivision4 = UUID.fromString("8a858922-e8e5-4791-ad53-906e50633ec7");\r
-       public static final UUID uuidDivision5 = UUID.fromString("16057133-d541-4ebd-81d4-cb92265ec54c");\r
-       public static final UUID uuidDivision6 = UUID.fromString("fbf21230-4a42-4f4c-9af8-5da52123c264");\r
-       public static final UUID uuidDivision7 = UUID.fromString("d31dd96a-36ea-4428-871c-d8552a9565ca");\r
-       public static final UUID uuidDivision8 = UUID.fromString("236ea447-c3ab-486d-9e06-cc5907861acc");\r
-\r
-\r
-       public UUID getNamedAreaUuid(String key) {\r
-               if (CdmUtils.isEmpty(key)){return null;\r
-               }else if (key.equalsIgnoreCase("1")){return uuidDivision1;\r
-               }else if (key.equalsIgnoreCase("2")){return uuidDivision2;\r
-               }else if (key.equalsIgnoreCase("3")){return uuidDivision3;\r
-               }else if (key.equalsIgnoreCase("4")){return uuidDivision4;\r
-               }else if (key.equalsIgnoreCase("5")){return uuidDivision5;\r
-               }else if (key.equalsIgnoreCase("6")){return uuidDivision6;\r
-               }else if (key.equalsIgnoreCase("7")){return uuidDivision7;\r
-               }else if (key.equalsIgnoreCase("8")){return uuidDivision8;\r
-               }else{\r
-                       return null;\r
-               }\r
-       }\r
-\r
-       protected NamedArea getNamedArea(UUID uuid, String label, String text, String labelAbbrev, NamedAreaType areaType, NamedAreaLevel level, TermVocabulary voc){\r
-               NamedArea namedArea = NamedArea.NewInstance(text, label, labelAbbrev);\r
-               voc.addTerm(namedArea);\r
-               namedArea.setType(areaType);\r
-               namedArea.setLevel(level);\r
-               namedArea.setUuid(uuid);\r
-               return namedArea;\r
-       }\r
-\r
-       @Test\r
-       public void testGetWebServiceUrlBangka() throws ClientProtocolException, IOException, URISyntaxException {\r
-               NamedArea areaBangka = NamedArea.NewInstance("Bangka", "Bangka", null);\r
-               TermVocabulary<NamedArea> voc = TermVocabulary.NewInstance("test Voc", "test voc", null, null);\r
-               voc.addTerm(areaBangka);\r
-\r
-               GeoServiceArea geoServiceArea = new GeoServiceArea();\r
-               String geoServiceLayer="vmap0_as_bnd_political_boundary_a";\r
-               String layerFieldName ="nam";\r
-               String areaValue = "PULAU BANGKA#SUMATERA SELATAN";\r
-               geoServiceArea.add(geoServiceLayer, layerFieldName, areaValue);\r
-               geoServiceArea.add(geoServiceLayer, layerFieldName, "BALI");\r
-\r
-               mapping.set(areaBangka, geoServiceArea);\r
-               Set<Distribution> distributions = new HashSet<Distribution>();\r
-               distributions.add(Distribution.NewInstance(areaBangka, PresenceTerm.PRESENT()));\r
-\r
-               Map<PresenceAbsenceTermBase<?>, Color> presenceAbsenceColorMap = new HashMap<PresenceAbsenceTermBase<?>, Color>();\r
-               presenceAbsenceColorMap.put(PresenceTerm.PRESENT(), Color.BLUE);\r
-\r
-               String backLayer ="";\r
-               presenceAbsenceColorMap = null;\r
-               String bbox="90,-8,130,8";\r
-               List<Language> languages = new ArrayList<Language>();\r
-\r
-               String result = EditGeoServiceUtilities.getDistributionServiceRequestParameterString(distributions, mapping, presenceAbsenceColorMap, 600, 300, bbox,backLayer, null, languages );\r
-               //TODO Set semantics is not determined\r
-               //String expected = "http://www.test.de/webservice?l=tdwg3&ad=tdwg3:a:GER|b:OKL|c:BGM|b:SPA|d:FRA&as=a:005500|b:00FF00|c:FFFFFF|d:001100&bbox=-20,40,40,40&ms=400x300";\r
-\r
-               System.out.println(result);\r
-\r
-               assertTrue(result.matches(".*l=earth.*"));\r
-               assertTrue(result.matches(".*ms=600,300.*"));\r
-               assertTrue(result.matches(".*ad=vmap0_as_bnd_political_boundary_a%3Anam:.*"));\r
-               assertTrue(result.matches(".*(PULAU\\+BANGKA%23SUMATERA\\+SELATAN).*") );\r
-               assertTrue(result.matches(".*(BALI).*") );\r
-\r
-               // request map image from webservice\r
-               subTestWithEditMapService(result);\r
-       }\r
+        return true;\r
+\r
+\r
+    }\r
+\r
+    public static final UUID uuidDivision1 = UUID.fromString("ab17eee9-1abb-4ce9-a9a2-563f840cdbfc");\r
+    public static final UUID uuidDivision2 = UUID.fromString("c3606165-efb7-4224-a168-63e009eb4aa5");\r
+    public static final UUID uuidDivision3 = UUID.fromString("750d4e07-e34b-491f-a7b7-09723afdc960");\r
+    public static final UUID uuidDivision4 = UUID.fromString("8a858922-e8e5-4791-ad53-906e50633ec7");\r
+    public static final UUID uuidDivision5 = UUID.fromString("16057133-d541-4ebd-81d4-cb92265ec54c");\r
+    public static final UUID uuidDivision6 = UUID.fromString("fbf21230-4a42-4f4c-9af8-5da52123c264");\r
+    public static final UUID uuidDivision7 = UUID.fromString("d31dd96a-36ea-4428-871c-d8552a9565ca");\r
+    public static final UUID uuidDivision8 = UUID.fromString("236ea447-c3ab-486d-9e06-cc5907861acc");\r
+\r
+\r
+    public UUID getNamedAreaUuid(String key) {\r
+        if (CdmUtils.isEmpty(key)){return null;\r
+        }else if (key.equalsIgnoreCase("1")){return uuidDivision1;\r
+        }else if (key.equalsIgnoreCase("2")){return uuidDivision2;\r
+        }else if (key.equalsIgnoreCase("3")){return uuidDivision3;\r
+        }else if (key.equalsIgnoreCase("4")){return uuidDivision4;\r
+        }else if (key.equalsIgnoreCase("5")){return uuidDivision5;\r
+        }else if (key.equalsIgnoreCase("6")){return uuidDivision6;\r
+        }else if (key.equalsIgnoreCase("7")){return uuidDivision7;\r
+        }else if (key.equalsIgnoreCase("8")){return uuidDivision8;\r
+        }else{\r
+            return null;\r
+        }\r
+    }\r
+\r
+    protected NamedArea getNamedArea(UUID uuid, String label, String text, String labelAbbrev, NamedAreaType areaType, NamedAreaLevel level, TermVocabulary voc){\r
+        NamedArea namedArea = NamedArea.NewInstance(text, label, labelAbbrev);\r
+        voc.addTerm(namedArea);\r
+        namedArea.setType(areaType);\r
+        namedArea.setLevel(level);\r
+        namedArea.setUuid(uuid);\r
+        return namedArea;\r
+    }\r
+\r
+    @Test\r
+    public void testGetWebServiceUrlBangka() throws ClientProtocolException, IOException, URISyntaxException {\r
+        NamedArea areaBangka = NamedArea.NewInstance("Bangka", "Bangka", null);\r
+        TermVocabulary<NamedArea> voc = TermVocabulary.NewInstance("test Voc", "test voc", null, null);\r
+        voc.addTerm(areaBangka);\r
+\r
+        GeoServiceArea geoServiceArea = new GeoServiceArea();\r
+        String geoServiceLayer="vmap0_as_bnd_political_boundary_a";\r
+        String layerFieldName ="nam";\r
+        String areaValue = "PULAU BANGKA#SUMATERA SELATAN";\r
+        geoServiceArea.add(geoServiceLayer, layerFieldName, areaValue);\r
+        geoServiceArea.add(geoServiceLayer, layerFieldName, "BALI");\r
+\r
+        mapping.set(areaBangka, geoServiceArea);\r
+        Set<Distribution> distributions = new HashSet<Distribution>();\r
+        distributions.add(Distribution.NewInstance(areaBangka, PresenceTerm.PRESENT()));\r
+\r
+        Map<PresenceAbsenceTermBase<?>, Color> presenceAbsenceColorMap = new HashMap<PresenceAbsenceTermBase<?>, Color>();\r
+        presenceAbsenceColorMap.put(PresenceTerm.PRESENT(), Color.BLUE);\r
+\r
+        String backLayer ="";\r
+        presenceAbsenceColorMap = null;\r
+        String bbox="90,-8,130,8";\r
+        List<Language> languages = new ArrayList<Language>();\r
+\r
+        String result = EditGeoServiceUtilities.getDistributionServiceRequestParameterString(distributions, mapping, presenceAbsenceColorMap, 600, 300, bbox,backLayer, null, languages );\r
+        //TODO Set semantics is not determined\r
+        //String expected = "http://www.test.de/webservice?l=tdwg3&ad=tdwg3:a:GER|b:OKL|c:BGM|b:SPA|d:FRA&as=a:005500|b:00FF00|c:FFFFFF|d:001100&bbox=-20,40,40,40&ms=400x300";\r
+\r
+        System.out.println(result);\r
+\r
+        assertTrue(result.matches(".*l=earth.*"));\r
+        assertTrue(result.matches(".*ms=600,300.*"));\r
+        assertTrue(result.matches(".*ad=vmap0_as_bnd_political_boundary_a%3Anam:.*"));\r
+        assertTrue(result.matches(".*(PULAU\\+BANGKA%23SUMATERA\\+SELATAN).*") );\r
+        assertTrue(result.matches(".*(BALI).*") );\r
+\r
+        // request map image from webservice\r
+        subTestWithEditMapService(result);\r
+    }\r
 \r
 \r
 }
\ No newline at end of file
index 6d95964850796ae13917748e9aa6ee9ee17481a1..e91198b010196adcbdc234f457c8ffa7cb5caa04 100644 (file)
@@ -24,7 +24,6 @@
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-jar-plugin</artifactId>
-        <version>2.3.2</version>
         <executions>
           <execution>
             <goals>
index 75f6ad6779e13316e7af846c91c4790ed1496524..2e6b9f11bd8f1bca1100824f51771e641cbf4e1c 100644 (file)
@@ -1,8 +1,8 @@
 /**\r
 * Copyright (C) 2007 EDIT\r
-* European Distributed Institute of Taxonomy \r
+* European Distributed Institute of Taxonomy\r
 * http://www.e-taxonomy.eu\r
-* \r
+*\r
 * The contents of this file are subject to the Mozilla Public License Version 1.1\r
 * See LICENSE.TXT at the top of this package for the full license terms.\r
 */\r
@@ -42,160 +42,164 @@ import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmPermissionEvaluator;
 \r
 @Component("defaultImport")\r
 public class CdmApplicationAwareDefaultImport<T extends IImportConfigurator> implements ICdmImporter<T>, ApplicationContextAware {\r
-       private static final Logger logger = Logger.getLogger(CdmApplicationAwareDefaultImport.class);\r
-\r
-       protected ApplicationContext applicationContext;\r
-       \r
-       /* (non-Javadoc)\r
-        * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)\r
-        */\r
-       public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\r
-               this.applicationContext = applicationContext;\r
-       }\r
-\r
-\r
-       //Constants\r
-       final boolean OBLIGATORY = true; \r
-       final boolean FACULTATIVE = false; \r
-       final int modCount = 1000;\r
-\r
-       IService<CdmBase> service = null;\r
-       \r
-       //different type of stores that are used by the known imports\r
-       Map<String, MapWrapper<? extends CdmBase>> stores = new HashMap<String, MapWrapper<? extends CdmBase>>();\r
-\r
-       public CdmApplicationAwareDefaultImport(){\r
-               \r
-               \r
-               stores.put(ICdmIO.PERSON_STORE, new MapWrapper<Person>(service));\r
-               stores.put(ICdmIO.TEAM_STORE, new MapWrapper<TeamOrPersonBase<?>>(service));\r
-               stores.put(ICdmIO.REFERENCE_STORE, new MapWrapper<Reference>(service));\r
-               stores.put(ICdmIO.NOMREF_STORE, new MapWrapper<Reference>(service));\r
-               stores.put(ICdmIO.NOMREF_DETAIL_STORE, new MapWrapper<Reference>(service));\r
-               stores.put(ICdmIO.REF_DETAIL_STORE, new MapWrapper<Reference>(service));\r
-               stores.put(ICdmIO.TAXONNAME_STORE, new MapWrapper<TaxonNameBase<?,?>>(service));\r
-               stores.put(ICdmIO.TAXON_STORE, new MapWrapper<TaxonBase>(service));\r
-               stores.put(ICdmIO.SPECIMEN_STORE, new MapWrapper<Specimen>(service));\r
-       }\r
-       \r
-       public boolean invoke(IImportConfigurator config){\r
-               if (config.getCheck().equals(IImportConfigurator.CHECK.CHECK_ONLY)){\r
-                       return doCheck(config);\r
-               }else if (config.getCheck().equals(IImportConfigurator.CHECK.CHECK_AND_IMPORT)){\r
-                       doCheck(config);\r
-                       return doImport(config);\r
-               }else if (config.getCheck().equals(IImportConfigurator.CHECK.IMPORT_WITHOUT_CHECK)){\r
-                       return doImport(config);\r
-               }else{\r
-                       logger.error("Unknown CHECK type");\r
-                       return false;\r
-               }\r
-       }\r
-       \r
-       \r
-       @SuppressWarnings("unchecked")\r
-       protected <S extends IImportConfigurator> boolean doCheck(S  config){\r
-               boolean result = true;\r
-               \r
-               //check\r
-               if (config == null){\r
-                       logger.warn("CdmImportConfiguration is null");\r
-                       return false;\r
-               }\r
-               System.out.println("Start checking Source ("+ config.getSourceNameString() + ") ...");\r
-               if (! config.isValid()){\r
-                       logger.warn("CdmImportConfiguration is not valid");\r
-                       return false;\r
-               }\r
-               \r
-               ImportStateBase state = config.getNewState();\r
-               state.initialize(config);\r
-               \r
-               //do check for each class\r
-               for (Class<ICdmIO> ioClass: config.getIoClassList()){\r
-                       try {\r
-                               String ioBeanName = getComponentBeanName(ioClass);\r
-                               ICdmIO cdmIo = (ICdmIO)applicationContext.getBean(ioBeanName, ICdmIO.class);\r
-                               if (cdmIo != null){\r
-                                       registerObservers(config, cdmIo);\r
-                                       state.setCurrentIO(cdmIo);\r
-                                       result &= cdmIo.check(state);\r
-                                       unRegisterObservers(config, cdmIo);\r
-                               }else{\r
-                                       logger.error("cdmIO was null");\r
-                                       result = false;\r
-                               }\r
-                       } catch (Exception e) {\r
-                                       logger.error(e);\r
-                                       e.printStackTrace();\r
-                                       result = false;\r
-                       }\r
-               }\r
-               \r
-               //return\r
-               System.out.println("End checking Source ("+ config.getSourceNameString() + ") for import to Cdm");\r
-               return result;\r
-\r
-       }\r
-       \r
-       private void registerObservers(IImportConfigurator config, ICdmIO io){\r
-               for (IIoObserver observer : config.getObservers()){\r
-                       io.addObserver(observer);\r
-               }\r
-       }\r
-       \r
-       private void unRegisterObservers(IImportConfigurator config, ICdmIO io){\r
-               for (IIoObserver observer : config.getObservers()){\r
-                       io.removeObserver(observer);\r
-               }\r
-       }\r
-       \r
-       \r
-       /**\r
-        * Executes the whole \r
-        */\r
-       protected <S extends IImportConfigurator>  boolean doImport(S config){\r
-               boolean result = true;\r
-               //validate\r
-               if (config == null){\r
-                       logger.warn("Configuration is null");\r
-                       return false;\r
-               }else if (! config.isValid()){\r
-                       logger.warn("Configuration is not valid");\r
-                       return false;\r
-               }\r
-                               \r
-               config.getSourceReference();\r
-               logger.info("Start import from Source '"+ config.getSourceNameString() + "' to destination '" + config.getDestinationNameString() + "'");\r
-               \r
-               ImportStateBase state = config.getNewState();\r
-               state.initialize(config);\r
-               \r
-               CdmPermissionEvaluator permissionEval = applicationContext.getBean("cdmPermissionEvaluator", CdmPermissionEvaluator.class);\r
-\r
-               state.setSuccess(true);\r
-               //do invoke for each class\r
-               for (Class<ICdmIO> ioClass: config.getIoClassList()){\r
-                       try {\r
-                               String ioBeanName = getComponentBeanName(ioClass);\r
-                               ICdmIO cdmIo = (ICdmIO)applicationContext.getBean(ioBeanName, ICdmIO.class);\r
-                               if (cdmIo != null){\r
-                                       registerObservers(config, cdmIo);\r
-                                       state.setCurrentIO(cdmIo);\r
-                                       result &= cdmIo.invoke(state);\r
-                                       unRegisterObservers(config, cdmIo);\r
-                               }else{\r
-                                       logger.error("cdmIO was null");\r
-                                       result = false;\r
-                               }\r
-                       } catch (Exception e) {\r
-                                       logger.error(e);\r
-                                       e.printStackTrace();\r
-                                       result = false;\r
-                       }\r
-               }\r
-               \r
-               //do invoke for each class\r
+    private static final Logger logger = Logger.getLogger(CdmApplicationAwareDefaultImport.class);\r
+\r
+    protected ApplicationContext applicationContext;\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)\r
+     */\r
+    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\r
+        this.applicationContext = applicationContext;\r
+    }\r
+\r
+\r
+    //Constants\r
+    final boolean OBLIGATORY = true;\r
+    final boolean FACULTATIVE = false;\r
+    final int modCount = 1000;\r
+\r
+    IService<CdmBase> service = null;\r
+\r
+    //different type of stores that are used by the known imports\r
+    Map<String, MapWrapper<? extends CdmBase>> stores = new HashMap<String, MapWrapper<? extends CdmBase>>();\r
+\r
+    public CdmApplicationAwareDefaultImport(){\r
+\r
+\r
+        stores.put(ICdmIO.PERSON_STORE, new MapWrapper<Person>(service));\r
+        stores.put(ICdmIO.TEAM_STORE, new MapWrapper<TeamOrPersonBase<?>>(service));\r
+        stores.put(ICdmIO.REFERENCE_STORE, new MapWrapper<Reference>(service));\r
+        stores.put(ICdmIO.NOMREF_STORE, new MapWrapper<Reference>(service));\r
+        stores.put(ICdmIO.NOMREF_DETAIL_STORE, new MapWrapper<Reference>(service));\r
+        stores.put(ICdmIO.REF_DETAIL_STORE, new MapWrapper<Reference>(service));\r
+        stores.put(ICdmIO.TAXONNAME_STORE, new MapWrapper<TaxonNameBase<?,?>>(service));\r
+        stores.put(ICdmIO.TAXON_STORE, new MapWrapper<TaxonBase>(service));\r
+        stores.put(ICdmIO.SPECIMEN_STORE, new MapWrapper<Specimen>(service));\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see eu.etaxonomy.cdm.io.common.ICdmImporter#invoke(eu.etaxonomy.cdm.io.common.IImportConfigurator)\r
+     */\r
+    @Override\r
+    public boolean invoke(IImportConfigurator config){\r
+        if (config.getCheck().equals(IImportConfigurator.CHECK.CHECK_ONLY)){\r
+            return doCheck(config);\r
+        }else if (config.getCheck().equals(IImportConfigurator.CHECK.CHECK_AND_IMPORT)){\r
+            doCheck(config);\r
+            return doImport(config);\r
+        }else if (config.getCheck().equals(IImportConfigurator.CHECK.IMPORT_WITHOUT_CHECK)){\r
+            return doImport(config);\r
+        }else{\r
+            logger.error("Unknown CHECK type");\r
+            return false;\r
+        }\r
+    }\r
+\r
+\r
+    @SuppressWarnings("unchecked")\r
+    protected <S extends IImportConfigurator> boolean doCheck(S  config){\r
+        boolean result = true;\r
+\r
+        //check\r
+        if (config == null){\r
+            logger.warn("CdmImportConfiguration is null");\r
+            return false;\r
+        }\r
+        System.out.println("Start checking Source ("+ config.getSourceNameString() + ") ...");\r
+        if (! config.isValid()){\r
+            logger.warn("CdmImportConfiguration is not valid");\r
+            return false;\r
+        }\r
+\r
+        ImportStateBase state = config.getNewState();\r
+        state.initialize(config);\r
+\r
+        //do check for each class\r
+        for (Class<ICdmIO> ioClass: config.getIoClassList()){\r
+            try {\r
+                String ioBeanName = getComponentBeanName(ioClass);\r
+                ICdmIO cdmIo = (ICdmIO)applicationContext.getBean(ioBeanName, ICdmIO.class);\r
+                if (cdmIo != null){\r
+                    registerObservers(config, cdmIo);\r
+                    state.setCurrentIO(cdmIo);\r
+                    result &= cdmIo.check(state);\r
+                    unRegisterObservers(config, cdmIo);\r
+                }else{\r
+                    logger.error("cdmIO was null");\r
+                    result = false;\r
+                }\r
+            } catch (Exception e) {\r
+                    logger.error(e);\r
+                    e.printStackTrace();\r
+                    result = false;\r
+            }\r
+        }\r
+\r
+        //return\r
+        System.out.println("End checking Source ("+ config.getSourceNameString() + ") for import to Cdm");\r
+        return result;\r
+\r
+    }\r
+\r
+    private void registerObservers(IImportConfigurator config, ICdmIO io){\r
+        for (IIoObserver observer : config.getObservers()){\r
+            io.addObserver(observer);\r
+        }\r
+    }\r
+\r
+    private void unRegisterObservers(IImportConfigurator config, ICdmIO io){\r
+        for (IIoObserver observer : config.getObservers()){\r
+            io.removeObserver(observer);\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * Executes the whole\r
+     */\r
+    protected <S extends IImportConfigurator>  boolean doImport(S config){\r
+        boolean result = true;\r
+        //validate\r
+        if (config == null){\r
+            logger.warn("Configuration is null");\r
+            return false;\r
+        }else if (! config.isValid()){\r
+            logger.warn("Configuration is not valid");\r
+            return false;\r
+        }\r
+\r
+        config.getSourceReference();\r
+        logger.info("Start import from Source '"+ config.getSourceNameString() + "' to destination '" + config.getDestinationNameString() + "'");\r
+\r
+        ImportStateBase state = config.getNewState();\r
+        state.initialize(config);\r
+\r
+        CdmPermissionEvaluator permissionEval = applicationContext.getBean("cdmPermissionEvaluator", CdmPermissionEvaluator.class);\r
+\r
+        state.setSuccess(true);\r
+        //do invoke for each class\r
+        for (Class<ICdmIO> ioClass: config.getIoClassList()){\r
+            try {\r
+                String ioBeanName = getComponentBeanName(ioClass);\r
+                ICdmIO cdmIo = (ICdmIO)applicationContext.getBean(ioBeanName, ICdmIO.class);\r
+                if (cdmIo != null){\r
+                    registerObservers(config, cdmIo);\r
+                    state.setCurrentIO(cdmIo);\r
+                    result &= cdmIo.invoke(state);\r
+                    unRegisterObservers(config, cdmIo);\r
+                }else{\r
+                    logger.error("cdmIO was null");\r
+                    result = false;\r
+                }\r
+            } catch (Exception e) {\r
+                    logger.error(e);\r
+                    e.printStackTrace();\r
+                    result = false;\r
+            }\r
+        }\r
+\r
+        //do invoke for each class\r
 //             for (String ioBean: config.getIoBeans()){\r
 //                     try {\r
 //                             ICdmIO<S> cdmIo = (ICdmIO<S>)applicationContext.getBean(ioBean, ICdmIO.class);\r
@@ -210,45 +214,45 @@ public class CdmApplicationAwareDefaultImport<T extends IImportConfigurator> imp
 //                                     e.printStackTrace();\r
 //                                     result = false;\r
 //                     }\r
-//                     \r
+//\r
 //             }\r
-               \r
-               logger.info("End import from source '" + config.getSourceNameString() \r
-                               + "' to destination '" + config.getDestinationNameString() + "'"+\r
-                               (result? "(successful)":"(with errors)")) ;\r
-               return result;\r
-       }\r
-\r
-       /**\r
-        * Returns the name of a component bean. If the name is defined in the Component annotation this name is returned.\r
-        * Otherwise the class name is returned with starting lower case.\r
-        * @param ioClass\r
-        * @return\r
-        * @throws IllegalArgumentException if the class does not have a "Component" annotation\r
-        */\r
-       public static String getComponentBeanName(Class<ICdmIO> ioClass) throws IllegalArgumentException {\r
-               Component component = ioClass.getAnnotation(Component.class);\r
-               if (component == null){\r
-                       throw new IllegalArgumentException("Class " + ioClass.getName() + " is missing a @Component annotation." );\r
-               }\r
-               String ioBean = component.value();\r
-               if ("".equals(ioBean)){\r
-                       ioBean = ioClass.getSimpleName();\r
-                       ioBean = ioBean.substring(0, 1).toLowerCase() + ioBean.substring(1); //make camelcase\r
-               }\r
-               return ioBean;\r
-       }\r
-\r
-       public void authenticate(IImportConfigurator config) {\r
-               UsernamePasswordAuthenticationToken token = config.getAuthenticationToken();\r
-               if (token != null){\r
-                       SecurityContext context = SecurityContextHolder.getContext();\r
-                       \r
-                       AuthenticationManager authenticationManager = applicationContext.getBean("authenticationManager", AuthenticationManager.class);;\r
-                       Authentication authentication = authenticationManager.authenticate(token);\r
-                       context.setAuthentication(authentication);\r
-               }\r
-               \r
-       }\r
+\r
+        logger.info("End import from source '" + config.getSourceNameString()\r
+                + "' to destination '" + config.getDestinationNameString() + "'"+\r
+                (result? "(successful)":"(with errors)")) ;\r
+        return result;\r
+    }\r
+\r
+    /**\r
+     * Returns the name of a component bean. If the name is defined in the Component annotation this name is returned.\r
+     * Otherwise the class name is returned with starting lower case.\r
+     * @param ioClass\r
+     * @return\r
+     * @throws IllegalArgumentException if the class does not have a "Component" annotation\r
+     */\r
+    public static String getComponentBeanName(Class<ICdmIO> ioClass) throws IllegalArgumentException {\r
+        Component component = ioClass.getAnnotation(Component.class);\r
+        if (component == null){\r
+            throw new IllegalArgumentException("Class " + ioClass.getName() + " is missing a @Component annotation." );\r
+        }\r
+        String ioBean = component.value();\r
+        if ("".equals(ioBean)){\r
+            ioBean = ioClass.getSimpleName();\r
+            ioBean = ioBean.substring(0, 1).toLowerCase() + ioBean.substring(1); //make camelcase\r
+        }\r
+        return ioBean;\r
+    }\r
+\r
+    public void authenticate(IImportConfigurator config) {\r
+         UsernamePasswordAuthenticationToken token = config.getAuthenticationToken();\r
+        if (token != null){\r
+            SecurityContext context = SecurityContextHolder.getContext();\r
+\r
+            AuthenticationManager authenticationManager = applicationContext.getBean("authenticationManager", AuthenticationManager.class);;\r
+            Authentication authentication = authenticationManager.authenticate(token);\r
+            context.setAuthentication(authentication);\r
+        }\r
+\r
+    }\r
 \r
 }\r
index 90df73979222bc1cb55cf38413404bf10300a5b3..d104366c4637f3786bbaa53ec4b81dc6f572af91 100644 (file)
@@ -1,8 +1,8 @@
 /**\r
 * Copyright (C) 2007 EDIT\r
-* European Distributed Institute of Taxonomy \r
+* European Distributed Institute of Taxonomy\r
 * http://www.e-taxonomy.eu\r
-* \r
+*\r
 * The contents of this file are subject to the Mozilla Public License Version 1.1\r
 * See LICENSE.TXT at the top of this package for the full license terms.\r
 */\r
@@ -15,27 +15,28 @@ import org.springframework.stereotype.Component;
 import eu.etaxonomy.cdm.io.common.CdmApplicationAwareDefaultImport;\r
 \r
 /**\r
- * This class was created just as a test class to implement the according integration test. \r
- * But it can also be used on its own for importing tcs-xml data \r
- * \r
+ * This class was created just as a test class to implement the according integration test.\r
+ * But it can also be used on its own for importing tcs-xml data\r
+ *\r
  * @author a.mueller\r
  * @created 28.01.2009\r
  * @version 1.0\r
  */\r
 @Component\r
 public class CdmTcsXmlImport extends CdmApplicationAwareDefaultImport<TcsXmlImportConfigurator> {\r
-       @SuppressWarnings("unused")\r
-       private static final Logger logger = Logger.getLogger(CdmTcsXmlImport.class);\r
+    @SuppressWarnings("unused")\r
+    private static final Logger logger = Logger.getLogger(CdmTcsXmlImport.class);\r
+\r
+    /* (non-Javadoc)\r
+     * @see eu.etaxonomy.cdm.io.common.ICdmImport#invoke(eu.etaxonomy.cdm.io.common.IImportConfigurator)\r
+     */\r
+    @Override\r
+    public boolean invoke(TcsXmlImportConfigurator tcsiConfig) {\r
+        return super.invoke(tcsiConfig);\r
+    }\r
 \r
-       /* (non-Javadoc)\r
-        * @see eu.etaxonomy.cdm.io.common.ICdmImport#invoke(eu.etaxonomy.cdm.io.common.IImportConfigurator)\r
-        */\r
-       public boolean invoke(TcsXmlImportConfigurator tcsiConfig) {\r
-               return super.invoke(tcsiConfig);\r
-       }\r
 \r
 \r
-       \r
 \r
 \r
 }\r
index 1b257ae39a50f991667332bb8397df8c55cac01e..2c1eaff6d20c3df95f72f0c68e49b6c8ec76c338 100644 (file)
@@ -9,7 +9,7 @@
 \r
     <import resource="classpath:/eu/etaxonomy/cdm/defaultApplicationContext.xml"/>\r
 \r
-       <context:component-scan base-package="eu/etaxonomy/cdm/ext"/>\r
+    <context:component-scan base-package="eu/etaxonomy/cdm/ext"/>\r
 \r
    <!--\r
         use TestingTermInitializer\r
@@ -39,7 +39,7 @@
             </props>\r
         </property>\r
     </bean>\r
-    \r
+\r
     <bean id="tableGeneratorGlobalOverride"\r
         class="eu.etaxonomy.cdm.persistence.hibernate.TableGeneratorGlobalOverride">\r
         <property name="properties">\r
@@ -50,7 +50,7 @@
             </props>\r
         </property>\r
     </bean>\r
-    \r
+\r
 \r
     <bean id="taxonSpellingDirectory" class="org.springmodules.lucene.index.support.FSDirectoryFactoryBean">\r
       <property name="location" value="file:./target/test-classes/eu.etaxonomy.cdm.model.taxon.TaxonBase_spelling"/>\r
index 24c5cea84421ea0aa45bf41e755a6632f3c21cb8..4a50319df34e495e5e7be49139bec9e39cef6298 100644 (file)
       <groupId>eu.etaxonomy</groupId>
       <artifactId>cdmlib-commons</artifactId>
     </dependency>
+    <dependency>
+      <groupId>javax.xml.bind</groupId>
+      <artifactId>jaxb-api</artifactId>
+    </dependency>
     <dependency>
       <groupId>xml-resolver</groupId>
       <artifactId>xml-resolver</artifactId>
       <groupId>javax.activation</groupId>
       <artifactId>activation</artifactId>
     </dependency>
-    <!--dependency>
+    <dependency>
       <groupId>javax.xml.bind</groupId>
       <artifactId>jsr173_api</artifactId>
-    </dependency-->
+    </dependency>
     <dependency>
       <groupId>com.sun.xml.bind</groupId>
       <artifactId>jaxb-impl</artifactId>
       <groupId>org.apache.poi</groupId>
       <artifactId>poi</artifactId>
     </dependency>
+  <dependency>
+      <groupId>commons-lang</groupId>
+      <artifactId>commons-lang</artifactId>
+    </dependency>
     <dependency>
       <groupId>joda-time</groupId>
       <artifactId>joda-time</artifactId>
       <artifactId>jaxb-api</artifactId>
       <version>2.1</version>
     </dependency>
+    <dependency>
+    <groupId>jdom</groupId>
+    <artifactId>jdom</artifactId>
+  </dependency>
     <dependency>
       <groupId>javax.validation</groupId>
       <artifactId>validation-api</artifactId>
index 841854bd740d78f8dca8c390a27bf536fe911522..784e04be16d9fb89284108fe6cfbc6c971888d4b 100644 (file)
@@ -25,6 +25,7 @@ import org.springframework.security.core.GrantedAuthority;
 @XmlRootElement(name = "Group")\r
 @Entity\r
 public class GrantedAuthorityImpl extends CdmBase implements GrantedAuthority {\r
+\r
     private static final long serialVersionUID = 2651969425860655040L;\r
     private static final Logger logger = Logger\r
             .getLogger(GrantedAuthority.class);\r
@@ -41,6 +42,10 @@ public class GrantedAuthorityImpl extends CdmBase implements GrantedAuthority {
         return new GrantedAuthorityImpl();\r
     }\r
 \r
+    /* (non-Javadoc)\r
+     * @see org.springframework.security.core.GrantedAuthority#getAuthority()\r
+     */\r
+    @Override\r
     public String getAuthority() {\r
         return authority;\r
     }\r
@@ -49,6 +54,10 @@ public class GrantedAuthorityImpl extends CdmBase implements GrantedAuthority {
         this.authority = authority;\r
     }\r
 \r
+    /**\r
+     * @param o\r
+     * @return\r
+     */\r
     public int compareTo(Object o) {\r
         if (o instanceof GrantedAuthority) {\r
             return this.authority.compareTo(((GrantedAuthority) o)\r
@@ -90,19 +99,4 @@ public class GrantedAuthorityImpl extends CdmBase implements GrantedAuthority {
             return null;\r
         }\r
     }\r
-\r
-    /**\r
-     * The role prefix 'ROLE_' is defined in\r
-     * the spring security <code>RoleVoter</code>\r
-     *\r
-     * @author a.kohlbecker\r
-     * @date Oct 5, 2012\r
-     *\r
-     */\r
-    public enum Role {\r
-\r
-        ROLE_ADMIN,\r
-        ROLE_USER_MANAGER\r
-\r
-    }\r
 }\r
index 37a59e142f7a2d13203f49dde3a091002db3c26e..bbd2ce89ed0754ffd8a63c50ad6c2917fc0d8257 100644 (file)
@@ -1,8 +1,8 @@
 /**\r
 * Copyright (C) 2007 EDIT\r
-* European Distributed Institute of Taxonomy \r
+* European Distributed Institute of Taxonomy\r
 * http://www.e-taxonomy.eu\r
-* \r
+*\r
 * The contents of this file are subject to the Mozilla Public License Version 1.1\r
 * See LICENSE.TXT at the top of this package for the full license terms.\r
 */\r
@@ -57,7 +57,7 @@ import eu.etaxonomy.cdm.model.agent.Person;
     "accountNonExpired",\r
     "credentialsNonExpired",\r
     "accountNonLocked",\r
-    "person"    \r
+    "person"\r
 })\r
 @XmlRootElement(name = "User")\r
 @Entity\r
@@ -65,219 +65,224 @@ import eu.etaxonomy.cdm.model.agent.Person;
 @Audited\r
 @Table(name = "UserAccount")\r
 public class User extends CdmBase implements UserDetails {\r
-       private static final long serialVersionUID = 6582191171369439163L;\r
-       private static final Logger logger = Logger.getLogger(User.class);\r
-       \r
-       protected User(){\r
-               super();\r
-       }\r
-       \r
-       public static User NewInstance(String username, String pwd){\r
-               User user = new User();\r
-               user.setUsername(username);\r
-               user.setPassword(pwd);\r
-               \r
-               user.setAccountNonExpired(true);\r
-               user.setAccountNonLocked(true);\r
-               user.setCredentialsNonExpired(true);\r
-               user.setEnabled(true);\r
-               \r
-               return user;\r
-       }\r
-       \r
-       public static User NewInstance(String personTitle, String username, String pwd){\r
-               User user = new User();\r
-               user.setUsername(username);\r
-               user.setPassword(pwd);\r
-               \r
-               user.setAccountNonExpired(true);\r
-               user.setAccountNonLocked(true);\r
-               user.setCredentialsNonExpired(true);\r
-               user.setEnabled(true);\r
-               Person userPerson = Person.NewTitledInstance(personTitle);\r
-               user.setPerson(userPerson);\r
-               \r
-               return user;\r
-       }\r
-       \r
-       @XmlElement(name = "Username")\r
-       @NaturalId\r
-       @Field(index = Index.UN_TOKENIZED)\r
-       protected String username;\r
-       \r
-       /**\r
-        * a salted, MD5 encoded hash of the plaintext password\r
-        */\r
-       @XmlElement(name = "Password")\r
-       @NotAudited\r
-       protected String password;\r
-       \r
-       @XmlElement(name = "EmailAddress")\r
-       protected String emailAddress;\r
-       \r
-       @XmlElementWrapper(name = "GrantedAuthorities")\r
-       @XmlElement(name = "GrantedAuthority", type = GrantedAuthorityImpl.class)\r
-       @XmlIDREF\r
-       @XmlSchemaType(name = "IDREF")\r
-       @ManyToMany(fetch = FetchType.LAZY, targetEntity = GrantedAuthorityImpl.class)\r
-       @Cascade(CascadeType.SAVE_UPDATE)\r
-       @NotAudited\r
-       protected Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();  //authorities of this user only\r
-       \r
-       @XmlElementWrapper(name = "Groups")\r
-       @XmlElement(name = "Group")\r
-       @XmlIDREF\r
-       @XmlSchemaType(name = "IDREF")\r
-       @ManyToMany(fetch = FetchType.LAZY)\r
-       @IndexedEmbedded(depth = 1)\r
-       @NotAudited\r
-       protected Set<Group> groups = new HashSet<Group>();\r
-       \r
-       @XmlElement(name = "Enabled")\r
-       protected boolean enabled;\r
-       \r
-       @XmlElement(name = "AccountNonExpired")\r
-       protected boolean accountNonExpired;\r
-\r
-       @XmlElement(name = "CredentialsNonExpired")\r
-       protected boolean credentialsNonExpired;\r
-       \r
-       @XmlElement(name = "AccountNonLocked")\r
-       protected boolean accountNonLocked;     \r
-       \r
-       @XmlElement(name = "Person")\r
-       @XmlIDREF\r
-       @XmlSchemaType(name = "IDREF")\r
-       @OneToOne(fetch = FetchType.LAZY)\r
-       @Cascade({CascadeType.SAVE_UPDATE})\r
-       @IndexedEmbedded(depth = 1)\r
-       protected Person person;\r
-       \r
-       @XmlTransient\r
-       @Transient\r
-       private Set<GrantedAuthority> authorities;  //authorities of this user and of all groups the user belongs to\r
-       \r
-       private void initAuthorities() {\r
-               authorities = new HashSet<GrantedAuthority>();\r
-               authorities.addAll(grantedAuthorities);\r
-               for(Group group : groups) {\r
-                       authorities.addAll(group.getGrantedAuthorities());\r
-               }\r
-       }\r
-       \r
-       @Transient\r
-       public Collection<GrantedAuthority> getAuthorities() {\r
-               if(authorities == null || authorities.size() == 0) {\r
-                       initAuthorities();\r
-               }\r
-               return authorities;\r
-       }\r
-\r
-       public String getPassword() {\r
-               return password;\r
-       }\r
-\r
-       public String getUsername() {\r
-               return username;\r
-       }\r
-\r
-       public boolean isAccountNonExpired() {\r
-               return accountNonExpired;\r
-       }\r
-\r
-       public boolean isAccountNonLocked() {\r
-               return accountNonLocked;\r
-       }\r
-\r
-       public boolean isCredentialsNonExpired() {\r
-               return credentialsNonExpired;\r
-       }\r
-\r
-       public boolean isEnabled() {\r
-               return enabled;\r
-       }\r
-\r
-       public String getEmailAddress() {\r
-               return emailAddress;\r
-       }\r
-\r
-       public void setEmailAddress(String emailAddress) {\r
-               this.emailAddress = emailAddress;\r
-       }\r
-\r
-       public Set<GrantedAuthority> getGrantedAuthorities() {\r
-               return grantedAuthorities;\r
-       }\r
-\r
-       public void setGrantedAuthorities(Set<GrantedAuthority> grantedAuthorities) {\r
-               this.grantedAuthorities = grantedAuthorities;\r
-               initAuthorities();\r
-       }\r
-\r
-       public void setUsername(String username) {\r
-               this.username = username;\r
-       }\r
-\r
-       public void setPassword(String password) {\r
-               this.password = password;\r
-       }\r
-\r
-       public void setEnabled(boolean enabled) {\r
-               this.enabled = enabled;\r
-       }\r
-\r
-       public void setAccountNonExpired(boolean accountNonExpired) {\r
-               this.accountNonExpired = accountNonExpired;\r
-       }\r
-\r
-       public void setCredentialsNonExpired(boolean credentialsNonExpired) {\r
-               this.credentialsNonExpired = credentialsNonExpired;\r
-       }\r
-\r
-       public void setAccountNonLocked(boolean accountNonLocked) {\r
-               this.accountNonLocked = accountNonLocked;\r
-       }\r
-       \r
-       protected void setGroups(Set<Group> groups) {\r
-               this.groups = groups;\r
-               initAuthorities();\r
-       }\r
-       \r
-       public Set<Group> getGroups() {\r
-               return groups;\r
-       }\r
-       \r
-       \r
-       public Person getPerson() {\r
-               return person;\r
-       }\r
-       \r
-       public void setPerson(Person person) {\r
-               this.person = person;\r
-       }\r
-       \r
+    private static final long serialVersionUID = 6582191171369439163L;\r
+    private static final Logger logger = Logger.getLogger(User.class);\r
+\r
+    protected User(){\r
+        super();\r
+    }\r
+\r
+    public static User NewInstance(String username, String pwd){\r
+        User user = new User();\r
+        user.setUsername(username);\r
+        user.setPassword(pwd);\r
+\r
+        user.setAccountNonExpired(true);\r
+        user.setAccountNonLocked(true);\r
+        user.setCredentialsNonExpired(true);\r
+        user.setEnabled(true);\r
+\r
+        return user;\r
+    }\r
+\r
+    public static User NewInstance(String personTitle, String username, String pwd){\r
+        User user = new User();\r
+        user.setUsername(username);\r
+        user.setPassword(pwd);\r
+\r
+        user.setAccountNonExpired(true);\r
+        user.setAccountNonLocked(true);\r
+        user.setCredentialsNonExpired(true);\r
+        user.setEnabled(true);\r
+        Person userPerson = Person.NewTitledInstance(personTitle);\r
+        user.setPerson(userPerson);\r
+\r
+        return user;\r
+    }\r
+\r
+    @XmlElement(name = "Username")\r
+    @NaturalId\r
+    @Field(index = Index.UN_TOKENIZED)\r
+    protected String username;\r
+\r
+    /**\r
+     * a salted, MD5 encoded hash of the plaintext password\r
+     */\r
+    @XmlElement(name = "Password")\r
+    @NotAudited\r
+    protected String password;\r
+\r
+    @XmlElement(name = "EmailAddress")\r
+    protected String emailAddress;\r
+\r
+    @XmlElementWrapper(name = "GrantedAuthorities")\r
+    @XmlElement(name = "GrantedAuthority", type = GrantedAuthorityImpl.class)\r
+    @XmlIDREF\r
+    @XmlSchemaType(name = "IDREF")\r
+    @ManyToMany(fetch = FetchType.LAZY, targetEntity = GrantedAuthorityImpl.class)\r
+    @Cascade(CascadeType.SAVE_UPDATE)\r
+    @NotAudited\r
+    protected Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();  //authorities of this user only\r
+\r
+    @XmlElementWrapper(name = "Groups")\r
+    @XmlElement(name = "Group")\r
+    @XmlIDREF\r
+    @XmlSchemaType(name = "IDREF")\r
+    @ManyToMany(fetch = FetchType.LAZY)\r
+    @IndexedEmbedded(depth = 1)\r
+    @NotAudited\r
+    protected Set<Group> groups = new HashSet<Group>();\r
+\r
+    @XmlElement(name = "Enabled")\r
+    protected boolean enabled;\r
+\r
+    @XmlElement(name = "AccountNonExpired")\r
+    protected boolean accountNonExpired;\r
+\r
+    @XmlElement(name = "CredentialsNonExpired")\r
+    protected boolean credentialsNonExpired;\r
+\r
+    @XmlElement(name = "AccountNonLocked")\r
+    protected boolean accountNonLocked;\r
+\r
+    @XmlElement(name = "Person")\r
+    @XmlIDREF\r
+    @XmlSchemaType(name = "IDREF")\r
+    @OneToOne(fetch = FetchType.LAZY)\r
+    @Cascade({CascadeType.SAVE_UPDATE})\r
+    @IndexedEmbedded(depth = 1)\r
+    protected Person person;\r
+\r
+    @XmlTransient\r
+    @Transient\r
+    private Set<GrantedAuthority> authorities;  //authorities of this user and of all groups the user belongs to\r
+\r
+    private void initAuthorities() {\r
+        authorities = new HashSet<GrantedAuthority>();\r
+        authorities.addAll(grantedAuthorities);\r
+        for(Group group : groups) {\r
+            authorities.addAll(group.getGrantedAuthorities());\r
+        }\r
+    }\r
+\r
+    /**\r
+     * {@inheritDoc}\r
+     *\r
+     * @return returns a {@code Set<GrantedAuthority>} as Collection\r
+     */\r
+    @Transient\r
+    public Collection<GrantedAuthority> getAuthorities() {\r
+        if(authorities == null || authorities.size() == 0) {\r
+            initAuthorities();\r
+        }\r
+        return authorities;\r
+    }\r
+\r
+    public String getPassword() {\r
+        return password;\r
+    }\r
+\r
+    public String getUsername() {\r
+        return username;\r
+    }\r
+\r
+    public boolean isAccountNonExpired() {\r
+        return accountNonExpired;\r
+    }\r
+\r
+    public boolean isAccountNonLocked() {\r
+        return accountNonLocked;\r
+    }\r
+\r
+    public boolean isCredentialsNonExpired() {\r
+        return credentialsNonExpired;\r
+    }\r
+\r
+    public boolean isEnabled() {\r
+        return enabled;\r
+    }\r
+\r
+    public String getEmailAddress() {\r
+        return emailAddress;\r
+    }\r
+\r
+    public void setEmailAddress(String emailAddress) {\r
+        this.emailAddress = emailAddress;\r
+    }\r
+\r
+    public Set<GrantedAuthority> getGrantedAuthorities() {\r
+        return grantedAuthorities;\r
+    }\r
+\r
+    public void setGrantedAuthorities(Set<GrantedAuthority> grantedAuthorities) {\r
+        this.grantedAuthorities = grantedAuthorities;\r
+        initAuthorities();\r
+    }\r
+\r
+    public void setUsername(String username) {\r
+        this.username = username;\r
+    }\r
+\r
+    public void setPassword(String password) {\r
+        this.password = password;\r
+    }\r
+\r
+    public void setEnabled(boolean enabled) {\r
+        this.enabled = enabled;\r
+    }\r
+\r
+    public void setAccountNonExpired(boolean accountNonExpired) {\r
+        this.accountNonExpired = accountNonExpired;\r
+    }\r
+\r
+    public void setCredentialsNonExpired(boolean credentialsNonExpired) {\r
+        this.credentialsNonExpired = credentialsNonExpired;\r
+    }\r
+\r
+    public void setAccountNonLocked(boolean accountNonLocked) {\r
+        this.accountNonLocked = accountNonLocked;\r
+    }\r
+\r
+    protected void setGroups(Set<Group> groups) {\r
+        this.groups = groups;\r
+        initAuthorities();\r
+    }\r
+\r
+    public Set<Group> getGroups() {\r
+        return groups;\r
+    }\r
+\r
+\r
+    public Person getPerson() {\r
+        return person;\r
+    }\r
+\r
+    public void setPerson(Person person) {\r
+        this.person = person;\r
+    }\r
+\r
 //*********************** CLONE ********************************************************/\r
-       \r
-       /** \r
-        * Clones <i>this</i> User. This is a shortcut that enables to create\r
-        * a new instance that differs only slightly from <i>this</i> User.\r
-        * The corresponding person is cloned. \r
-        * \r
-        * @see eu.etaxonomy.cdm.model.common.CdmBase#clone()\r
-        * @see java.lang.Object#clone()\r
-        */\r
-       @Override\r
-       public Object clone() {\r
-               try{\r
-                       User result = (User)super.clone();\r
-                       result.setPerson((Person)this.person.clone());\r
-                       return result;\r
-               } catch (CloneNotSupportedException e){\r
-                       logger.warn("Object does not implement cloneable");\r
-                       e.printStackTrace();\r
-                       return null;\r
-               }\r
-               \r
-               \r
-       }\r
+\r
+    /**\r
+     * Clones <i>this</i> User. This is a shortcut that enables to create\r
+     * a new instance that differs only slightly from <i>this</i> User.\r
+     * The corresponding person is cloned.\r
+     *\r
+     * @see eu.etaxonomy.cdm.model.common.CdmBase#clone()\r
+     * @see java.lang.Object#clone()\r
+     */\r
+    @Override\r
+    public Object clone() {\r
+        try{\r
+            User result = (User)super.clone();\r
+            result.setPerson((Person)this.person.clone());\r
+            return result;\r
+        } catch (CloneNotSupportedException e){\r
+            logger.warn("Object does not implement cloneable");\r
+            e.printStackTrace();\r
+            return null;\r
+        }\r
+\r
+\r
+    }\r
 }\r
index 122432a0e4631c1763e3cec5e3b15fc8d2706fa9..cedadd33aff9da4a945234addb0efea17e96b741 100644 (file)
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-jar-plugin</artifactId>
-        <version>2.3.2</version>
         <executions>
           <execution>
             <goals>
index 29001a09dcb72991fab5b42ddf99f5a255d1caed..695a26b1c2077686edef85609fc5f345791b665c 100644 (file)
@@ -1,8 +1,8 @@
 /**\r
 * Copyright (C) 2007 EDIT\r
-* European Distributed Institute of Taxonomy \r
+* European Distributed Institute of Taxonomy\r
 * http://www.e-taxonomy.eu\r
-* \r
+*\r
 * The contents of this file are subject to the Mozilla Public License Version 1.1\r
 * See LICENSE.TXT at the top of this package for the full license terms.\r
 */\r
@@ -28,52 +28,52 @@ import eu.etaxonomy.cdm.model.common.RelationshipBase;
  * @version 1.0\r
  */\r
 public class CdmDeleteListener implements DeleteEventListener {\r
-       private static final long serialVersionUID = -5511287200489449838L;\r
-       protected static final Logger logger = Logger.getLogger(CdmDeleteListener.class);\r
+    private static final long serialVersionUID = -5511287200489449838L;\r
+    protected static final Logger logger = Logger.getLogger(CdmDeleteListener.class);\r
 \r
-       /* (non-Javadoc)\r
-        * @see org.hibernate.event.DeleteEventListener#onDelete(org.hibernate.event.DeleteEvent)\r
-        */\r
-       public void onDelete(DeleteEvent event) throws HibernateException {\r
-               Object entity = event.getObject();\r
-               if(entity != null && RelationshipBase.class.isAssignableFrom(entity.getClass())) {\r
-                       logger.info("Deleting " + entity);\r
-                       deleteRelationship(event, entity);\r
-               }\r
-       }\r
+    /* (non-Javadoc)\r
+     * @see org.hibernate.event.DeleteEventListener#onDelete(org.hibernate.event.DeleteEvent)\r
+     */\r
+    public void onDelete(DeleteEvent event) throws HibernateException {\r
+        Object entity = event.getObject();\r
+        if(entity != null && RelationshipBase.class.isAssignableFrom(entity.getClass())) {\r
+            logger.info("Deleting " + entity);\r
+            deleteRelationship(event, entity);\r
+        }\r
+    }\r
 \r
-       /* (non-Javadoc)\r
-        * @see org.hibernate.event.DeleteEventListener#onDelete(org.hibernate.event.DeleteEvent, java.util.Set)\r
-        */\r
-       public void onDelete(DeleteEvent event, Set transientEntities)throws HibernateException {\r
-               Object entity = event.getObject();\r
-               if(entity != null && RelationshipBase.class.isAssignableFrom(entity.getClass())) {\r
-                       logger.info("Deleting " + entity);\r
-                       deleteRelationship(event, entity);\r
-               }\r
-       }\r
+    /* (non-Javadoc)\r
+     * @see org.hibernate.event.DeleteEventListener#onDelete(org.hibernate.event.DeleteEvent, java.util.Set)\r
+     */\r
+    public void onDelete(DeleteEvent event, Set transientEntities)throws HibernateException {\r
+        Object entity = event.getObject();\r
+        if(entity != null && RelationshipBase.class.isAssignableFrom(entity.getClass())) {\r
+            logger.info("Deleting " + entity);\r
+            deleteRelationship(event, entity);\r
+        }\r
+    }\r
 \r
-       /**\r
-        * @param event\r
-        * @param entity\r
-        */\r
-       private void deleteRelationship(DeleteEvent event, Object entity) {\r
-               RelationshipBase relationshipEntity = (RelationshipBase)entity;\r
-               if (relationshipEntity.isRemoved()){\r
-                       Set<IRelated> deletedObjects = relationshipEntity.getDeletedObjects();\r
-                       for (IRelated rel : deletedObjects){\r
-                               if (rel != null){\r
-                                       logger.info("Updating related entity " + rel);\r
-                                       Object o = CdmBase.deproxy(rel, CdmBase.class);\r
-                                       EntityEntry entry = event.getSession().getPersistenceContext().getEntry(o);\r
-                                       if (entry == null){\r
-                                               System.out.println();\r
-                                       }\r
-                                       if (!entry.getStatus().equals(Status.DELETED)){\r
-                                               event.getSession().update(rel);\r
-                                       }\r
-                               }\r
-                       }\r
-               }\r
-       }\r
+    /**\r
+     * @param event\r
+     * @param entity\r
+     */\r
+    private void deleteRelationship(DeleteEvent event, Object entity) {\r
+        RelationshipBase relationshipEntity = (RelationshipBase)entity;\r
+        if (relationshipEntity.isRemoved()){\r
+            Set<IRelated> deletedObjects = relationshipEntity.getDeletedObjects();\r
+            for (IRelated rel : deletedObjects){\r
+                if (rel != null){\r
+                    logger.info("Updating related entity " + rel);\r
+                    Object o = CdmBase.deproxy(rel, CdmBase.class);\r
+                    EntityEntry entry = event.getSession().getPersistenceContext().getEntry(o);\r
+                    if (entry == null){\r
+//                                             System.out.println();\r
+                    }\r
+                    if (!entry.getStatus().equals(Status.DELETED)){\r
+                        event.getSession().update(rel);\r
+                    }\r
+                }\r
+            }\r
+        }\r
+    }\r
 }\r
index 7c03997b948a6f1395ec0b81dc64026426fe7229..eaf56c608d4b21df83a4e0e535fd0668b50a3da3 100644 (file)
@@ -11,7 +11,7 @@ package eu.etaxonomy.cdm.persistence.hibernate;
 \r
 import java.io.Serializable;\r
 import java.util.UUID;\r
-       \r
+\r
 import org.apache.log4j.Logger;\r
 import org.hibernate.EmptyInterceptor;\r
 import org.hibernate.Transaction;\r
@@ -29,24 +29,24 @@ import eu.etaxonomy.cdm.model.common.DefinedTermBase;
 public class CdmHibernateInterceptor extends EmptyInterceptor {\r
         private static final long serialVersionUID = 2536017420460052854L;\r
         private static final Logger logger = Logger.getLogger(CdmHibernateInterceptor.class);\r
-       \r
+\r
         //FIXME problem is circular dependency (see VocabularyStoreImpl.staticInitialized\r
 //      @Autowired\r
 //      VocabularyStoreImpl vocabularyStore;\r
-        \r
+\r
         private int updates;\r
         private int creates;\r
         private int loads;\r
 \r
-       public void onDelete(Object entity,\r
-              Serializable id,\r
-              Object[] state,\r
-              String[] propertyNames,\r
-              Type[] types) {\r
-               // do nothing\r
-       }\r
-              \r
-       public boolean onFlushDirty(Object entity,\r
+    public void onDelete(Object entity,\r
+           Serializable id,\r
+           Object[] state,\r
+           String[] propertyNames,\r
+           Type[] types) {\r
+        // do nothing\r
+    }\r
+\r
+    public boolean onFlushDirty(Object entity,\r
             Serializable id,\r
             Object[] currentState,\r
             Object[] previousState,\r
@@ -57,22 +57,22 @@ public class CdmHibernateInterceptor extends EmptyInterceptor {
         if ( entity instanceof CdmBase ) {\r
                 updates++;\r
                 //result &= checkTransientDefinedTerms(currentState);\r
-               }\r
-           return result;\r
-       }\r
-              \r
-       public boolean onLoad(Object entity,\r
-                       Serializable id,\r
-                       Object[] state,\r
-                       String[] propertyNames,\r
-                       Type[] types) {\r
+        }\r
+        return result;\r
+    }\r
+\r
+    public boolean onLoad(Object entity,\r
+                    Serializable id,\r
+                    Object[] state,\r
+                    String[] propertyNames,\r
+                    Type[] types) {\r
         if ( entity instanceof CdmBase ) {\r
-            logger.warn("id = " +id);    \r
-               loads++;\r
+            logger.warn("id = " +id);\r
+            loads++;\r
         }\r
         return false;\r
-       }\r
-              \r
+    }\r
+\r
     public boolean onSave(Object entity,\r
                     Serializable id,\r
                     Object[] state,\r
@@ -86,8 +86,8 @@ public class CdmHibernateInterceptor extends EmptyInterceptor {
         }\r
         return result;\r
     }\r
-              \r
-              \r
+\r
+\r
     private boolean checkTransientDefinedTerms(Object[] state){\r
         boolean result = false;\r
 //                     if (VocabularyStoreImpl.isInitialized()){\r
@@ -113,15 +113,15 @@ public class CdmHibernateInterceptor extends EmptyInterceptor {
 //                                                             throw new IllegalStateException("UUID is not equal.");\r
 //                                                     }\r
 //                                             }\r
-//                                            \r
+//\r
 //                                     }\r
 //                             }\r
 //                     }else{ //not initialized\r
-//                             \r
+//\r
 //                     }\r
             return result;\r
     }\r
-              \r
+\r
     public void afterTransactionCompletion(Transaction tx) {\r
             if ( tx.wasCommitted() ) {\r
                     logger.debug("Creations: " + creates + ", Updates: " + updates + ", Loads: " + loads);\r
@@ -130,7 +130,6 @@ public class CdmHibernateInterceptor extends EmptyInterceptor {
             creates=0;\r
             loads=0;\r
     }\r
-       \r
+\r
 }\r
-       \r
-              
\ No newline at end of file
+\r
index a454f83c96cd9e15cba4d3f69203123963181770..5943a2e9c1252c16da3d9acdae10cc8f750b6ee9 100644 (file)
@@ -1,4 +1,11 @@
-\r
+/**\r
+* Copyright (C) 2012 EDIT\r
+* European Distributed Institute of Taxonomy\r
+* http://www.e-taxonomy.eu\r
+*\r
+* The contents of this file are subject to the Mozilla Public License Version 1.1\r
+* See LICENSE.TXT at the top of this package for the full license terms.\r
+*/\r
 package eu.etaxonomy.cdm.persistence.hibernate.permission;\r
 \r
 import java.util.EnumSet;\r
@@ -8,8 +15,10 @@ import java.util.regex.Pattern;
 \r
 import org.apache.log4j.Logger;\r
 import org.springframework.security.access.ConfigAttribute;\r
+import org.springframework.security.core.GrantedAuthority;\r
 \r
 import eu.etaxonomy.cdm.model.common.CdmBase;\r
+import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;\r
 \r
 import sun.security.provider.PolicyParser.ParsingException;\r
 \r
@@ -48,7 +57,7 @@ import sun.security.provider.PolicyParser.ParsingException;
  *\r
  * @author k.luther\r
  */\r
-public class CdmAuthority implements ConfigAttribute {\r
+public class CdmAuthority implements GrantedAuthority, ConfigAttribute, IGrantedAuthorityConverter {\r
 \r
     private static final long serialVersionUID = 1L;\r
 \r
@@ -57,7 +66,7 @@ public class CdmAuthority implements ConfigAttribute {
     CdmPermissionClass permissionClass;\r
     String property;\r
     EnumSet<CRUD> operation;\r
-     UUID targetUuid;\r
+    UUID targetUuid;\r
 \r
     public CdmAuthority(CdmBase targetDomainObject, EnumSet<CRUD> operation, UUID uuid){\r
         this.permissionClass = CdmPermissionClass.getValueOf(targetDomainObject);\r
@@ -81,17 +90,7 @@ public class CdmAuthority implements ConfigAttribute {
         this.targetUuid = uuid;\r
     }\r
 \r
-    /**\r
-     * Constructs a new CdmAuthority by parsing the contents of an\r
-     * authority string. For details on the syntax please refer to the class\r
-     * documentation above.\r
-     *\r
-     * TODO usually one would not use a constructor but a valueOf(String) or fromSting() method for this\r
-     *\r
-     * @param authority\r
-     * @throws ParsingException\r
-     */\r
-    public CdmAuthority (String authority) throws ParsingException{\r
+    private CdmAuthority (String authority) throws ParsingException{\r
 \r
         String[] tokens = parse(authority);\r
         // className must never be null\r
@@ -179,6 +178,25 @@ public class CdmAuthority implements ConfigAttribute {
         return tokens;\r
     }\r
 \r
+    /**\r
+     * {@inheritDoc}\r
+     *\r
+     * same as {@link #toString()} and  {@link #getAttribute()}\r
+     */\r
+    @Override\r
+    public String getAuthority() {\r
+        return toString();\r
+    }\r
+\r
+    /**\r
+     * {@inheritDoc}\r
+     *\r
+     * same as {@link #toString()} and  {@link #getAuthority()}\r
+     */\r
+    @Override\r
+    public String getAttribute() {\r
+        return toString();\r
+    }\r
 \r
     @Override\r
     public String toString() {\r
@@ -194,9 +212,29 @@ public class CdmAuthority implements ConfigAttribute {
         return sb.toString() ;\r
     }\r
 \r
+    /**\r
+     * Constructs a new CdmAuthority by parsing the authority string.\r
+     * For details on the syntax please refer to the class\r
+     * documentation above.\r
+     *\r
+     *\r
+     * @param authority\r
+     * @throws ParsingException\r
+     */\r
+    public static CdmAuthority fromGrantedAuthority(GrantedAuthority authority) throws ParsingException {\r
+        return new CdmAuthority(authority.getAuthority());\r
+    }\r
+\r
+    /* (non-Javadoc)\r
+     * @see eu.etaxonomy.cdm.persistence.hibernate.permission.IGrantedAuthorityConverter#asNewGrantedAuthority()\r
+     */\r
     @Override\r
-    public String getAttribute() {\r
-        return toString();\r
+    public GrantedAuthorityImpl asNewGrantedAuthority() throws ParsingException {\r
+        GrantedAuthorityImpl grantedAuthority = GrantedAuthorityImpl.NewInstance();\r
+        grantedAuthority.setAuthority(getAuthority());\r
+        return grantedAuthority;\r
     }\r
 \r
+\r
+\r
 }
\ No newline at end of file
index ffc97ddba09e1d941963c67592102d067f602f3e..0a3e0e2f8dd38dd0093a489bbca5b6347168377f 100644 (file)
@@ -24,7 +24,6 @@ import org.springframework.security.core.GrantedAuthority;
 import org.springframework.stereotype.Component;\r
 \r
 import eu.etaxonomy.cdm.model.common.CdmBase;\r
-import static eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl.Role;\r
 \r
 /**\r
  * @author k.luther\r
@@ -69,6 +68,10 @@ public class CdmPermissionEvaluator implements PermissionEvaluator {
         CdmAuthority evalPermission;\r
         EnumSet<CRUD> requiredOperation;\r
 \r
+        if(authentication == null) {\r
+            return false;\r
+        }\r
+\r
         if(logger.isDebugEnabled()){\r
             StringBuilder grantedAuthoritiesTxt = new StringBuilder();\r
             for(GrantedAuthority ga : authentication.getAuthorities()){\r
@@ -98,13 +101,7 @@ public class CdmPermissionEvaluator implements PermissionEvaluator {
             return true; // it might be wrong to return true\r
         }\r
 \r
-        try{\r
-            //evalPermission = new CdmAuthority(targetDomainObject.getClass().getSimpleName().toUpperCase(), cdmPermission, ((CdmBase)targetDomainObject).getUuid());\r
-            evalPermission = new CdmAuthority((CdmBase)targetDomainObject, requiredOperation, ((CdmBase)targetDomainObject).getUuid());\r
-        }catch(NullPointerException e){\r
-            //evalPermission = new CdmAuthority(targetDomainObject.getClass().getSimpleName().toUpperCase(), cdmPermission, null);\r
-            evalPermission = new CdmAuthority((CdmBase)targetDomainObject, requiredOperation, null);\r
-        }\r
+        evalPermission = authorityRequiredFor((CdmBase)targetDomainObject, requiredOperation);\r
 \r
 \r
         if (evalPermission.permissionClass != null) {\r
@@ -117,6 +114,25 @@ public class CdmPermissionEvaluator implements PermissionEvaluator {
 \r
     }\r
 \r
+    /**\r
+     * @param targetEntity\r
+     * @param requiredOperation\r
+     * @return\r
+     */\r
+    private CdmAuthority authorityRequiredFor(CdmBase targetEntity, EnumSet<CRUD> requiredOperation) {\r
+        CdmAuthority evalPermission;\r
+        try{\r
+            //evalPermission = new CdmAuthority(targetDomainObject.getClass().getSimpleName().toUpperCase(), cdmPermission, (targetDomainObject).getUuid());\r
+            evalPermission = new CdmAuthority(targetEntity, requiredOperation, (targetEntity).getUuid());\r
+        }catch(NullPointerException e){\r
+            // TODO document where the NPE is coming from\r
+\r
+            //evalPermission = new CdmAuthority(targetDomainObject.getClass().getSimpleName().toUpperCase(), cdmPermission, null);\r
+            evalPermission = new CdmAuthority(targetEntity, requiredOperation, null);\r
+        }\r
+        return evalPermission;\r
+    }\r
+\r
 \r
     /**\r
      * @param authorities\r
@@ -128,7 +144,7 @@ public class CdmPermissionEvaluator implements PermissionEvaluator {
 \r
         //if user has administrator rights return true;\r
          for (GrantedAuthority authority: authentication.getAuthorities()){\r
-             if (authority.getAuthority().equals(Role.ROLE_ADMIN.name())){\r
+             if (authority.getAuthority().equals(Role.ROLE_ADMIN.getAuthority())){\r
                  logger.debug("ROLE_ADMIN found => true");\r
                  return true;\r
              }\r
diff --git a/cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/IGrantedAuthorityConverter.java b/cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/IGrantedAuthorityConverter.java
new file mode 100644 (file)
index 0000000..eb39329
--- /dev/null
@@ -0,0 +1,27 @@
+/**
+* Copyright (C) 2012 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.persistence.hibernate.permission;
+
+import sun.security.provider.PolicyParser.ParsingException;
+import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
+
+/**
+ * @author a.kohlbecker
+ * @date Oct 15, 2012
+ *
+ */
+public interface IGrantedAuthorityConverter {
+
+    /**
+     * @return
+     * @throws ParsingException
+     */
+    public abstract GrantedAuthorityImpl asNewGrantedAuthority() throws ParsingException;
+
+}
\ No newline at end of file
diff --git a/cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/Role.java b/cdmlib-persistence/src/main/java/eu/etaxonomy/cdm/persistence/hibernate/permission/Role.java
new file mode 100644 (file)
index 0000000..3403730
--- /dev/null
@@ -0,0 +1,95 @@
+package eu.etaxonomy.cdm.persistence.hibernate.permission;
+
+import java.util.UUID;
+
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.util.Assert;
+
+import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
+import eu.etaxonomy.cdm.persistence.dao.common.IGrantedAuthorityDao;
+
+/**
+ * The role prefix 'ROLE_' is defined in the spring security
+ * <code>RoleVoter</code>
+ *
+ * @author a.kohlbecker
+ * @date Oct 5, 2012
+ *
+ *
+ */
+public class Role implements GrantedAuthority, IGrantedAuthorityConverter {
+
+    private static final long serialVersionUID = -2244354513663448504L;
+
+    /**
+     * The role prefix 'ROLE_' is defined in the spring security
+     * <code>RoleVoter</code>
+     */
+    private static final String ROLE_PREFIX = "ROLE_";
+
+    public final static Role ROLE_ADMIN = new Role(UUID.fromString("56eac992-67ba-40be-896c-4e992ca2afc0"), "ROLE_ADMIN");
+    public final static Role ROLE_USER_MANAGER = new Role(UUID.fromString("9eabd2c6-0590-4a1e-95f5-99cc58b63aa7"), "ROLE_USER_MANAGER");
+
+    private UUID uuid;
+
+    public UUID getUuid() {
+        return uuid;
+    }
+
+    private String authority;
+
+    public Role(UUID uuid, String authority) {
+        this.uuid = uuid;
+        this.authority = authority;
+    }
+
+    /**
+     * <b>WARNING:</b> This method must only be used when there is nothing in
+     * hibernate to be flushed to the database. Otherwise you risk of getting
+     * into an endless loop. Alternatively you can use
+     * {@link #asNewGrantedAuthority()}
+     *
+     *
+     * @return either an instance which already is persited to the database or a
+     *         fresh not persisted instance of {@link GrantedAuthorityImpl} for
+     *         the Role.
+     */
+    public GrantedAuthorityImpl asGrantedAuthority(IGrantedAuthorityDao grantedAuthorityDao) {
+        GrantedAuthorityImpl grantedAuthority = grantedAuthorityDao.findByUuid(uuid);
+        if (grantedAuthority == null) {
+            grantedAuthority = asNewGrantedAuthority();
+        } else {
+            Assert.isTrue(authority.equals(grantedAuthority.getAuthority()), "the persisted Authority with uuid " + uuid + " is not '" + authority + "'" );
+        }
+        return grantedAuthority;
+    }
+
+    /**
+     * @return a fresh <b>not persisted instance</b> of {@link GrantedAuthorityImpl}
+     *         for the Role.
+     */
+    @Override
+    public GrantedAuthorityImpl asNewGrantedAuthority() {
+        GrantedAuthorityImpl grantedAuthority;
+        grantedAuthority = GrantedAuthorityImpl.NewInstance();
+        grantedAuthority.setUuid(uuid);
+        grantedAuthority.setAuthority(authority);
+        return grantedAuthority;
+    }
+
+    public static Role fromGrantedAuthority(GrantedAuthorityImpl grantedAuthority){
+        Assert.isTrue(grantedAuthority.getAuthority().matches("^" + ROLE_PREFIX +"\\w*$"), "invalid role prefix of authority " + grantedAuthority.getAuthority() + "[" + grantedAuthority.getUuid() + "]");
+        return new Role(grantedAuthority.getUuid(), grantedAuthority.getAuthority());
+    }
+
+    @Override
+    public String getAuthority() {
+        return authority;
+    }
+
+    @Override
+    public String toString(){
+        return getAuthority();
+    }
+
+}
\ No newline at end of file
index 589514972df64b61b8570544cbc9271e91ac54e9..3c6a274b70e72e0b68f46afa916a1e06a8189a54 100644 (file)
@@ -101,9 +101,9 @@ public abstract class CdmPermissionVoter implements AccessDecisionVoter {
 
             for (GrantedAuthority authority: authentication.getAuthorities()){
 
-                CdmAuthority ap;
+                CdmAuthority auth;
                 try {
-                    ap = new CdmAuthority(authority.getAuthority());
+                    auth = CdmAuthority.fromGrantedAuthority(authority);
                 } catch (ParsingException e) {
                     logger.debug("skipping " + authority.getAuthority() + " due to ParsingException");
                     continue;
@@ -117,18 +117,18 @@ public abstract class CdmPermissionVoter implements AccessDecisionVoter {
 
                 ValidationResult vr = new ValidationResult();
 
-                boolean isALL = ap.getPermissionClass().equals(CdmPermissionClass.ALL);
+                boolean isALL = auth.getPermissionClass().equals(CdmPermissionClass.ALL);
 
-                vr.isClassMatch = isALL || ap.getPermissionClass().equals(evalPermission.getPermissionClass());
-                vr.isPermissionMatch = ap.getOperation().containsAll(evalPermission.getOperation());
-                vr.isUuidMatch = ap.hasTargetUuid() && ap.getTargetUUID().equals(((CdmBase)object).getUuid());
+                vr.isClassMatch = isALL || auth.getPermissionClass().equals(evalPermission.getPermissionClass());
+                vr.isPermissionMatch = auth.getOperation().containsAll(evalPermission.getOperation());
+                vr.isUuidMatch = auth.hasTargetUuid() && auth.getTargetUUID().equals(((CdmBase)object).getUuid());
 
                 //
                 // only vote if no property is defined.
                 // Authorities with properties must be voted by type specific voters.
                 //
-                if(!ap.hasProperty()){
-                    if ( !ap.hasTargetUuid() && vr.isClassMatch && vr.isPermissionMatch){
+                if(!auth.hasProperty()){
+                    if ( !auth.hasTargetUuid() && vr.isClassMatch && vr.isPermissionMatch){
                         logger.debug("no tragetUuid, class & permission match => ACCESS_GRANTED");
                         return ACCESS_GRANTED;
                     }
@@ -151,7 +151,7 @@ public abstract class CdmPermissionVoter implements AccessDecisionVoter {
                 // ask subclasses for further voting decisions
                 // subclasses will cast votes for specific Cdm Types
                 //
-                Integer furtherVotingResult = furtherVotingDescisions(ap, object, attributes, vr);
+                Integer furtherVotingResult = furtherVotingDescisions(auth, object, attributes, vr);
                 if(furtherVotingResult != null && furtherVotingResult != ACCESS_ABSTAIN){
                     logger.debug("furtherVotingResult => " + furtherVotingResult);
                     return furtherVotingResult;
index f6a2980407eb134c7f20f0d794fd1afaa68e8017..607b9be57db1b425b2c9bf8fdd5030e255272588 100644 (file)
       <property name="sessionFactory" ref="sessionFactory" />\r
     </bean>\r
 \r
+    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" depends-on="tableGeneratorGlobalOverride">\r
+        <property name="namingStrategy">\r
+          <bean class="org.hibernate.cfg.DefaultComponentSafeNamingStrategy" />\r
+        </property>\r
+\r
+        <property name="entityInterceptor" ref="securityHibernateInterceptor" />\r
+\r
+        <property name="configLocation" value="classpath:eu/etaxonomy/cdm/hibernate.cfg.xml"/>\r
+        <property  name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>\r
+        <!--\r
+              If dataSource is set, this will override corresponding settings in Hibernate properties.\r
+              If this is set, the Hibernate settings should not define a connection provider to\r
+              avoid meaningless double configuration.\r
+\r
+              see also org.springframework.orm.hibernate3.AbstractSessionFactoryBean.setDataSource(DataSource dataSource)\r
+           -->\r
+        <property name="dataSource" ref="dataSource"/>\r
+        <property name="hibernateProperties" ref="hibernateProperties"/>\r
+    </bean>\r
+\r
+    <!--\r
+       Configuration for the BeanInitialization\r
+     -->\r
+    <bean id="titleCacheAutoInitializer" class="eu.etaxonomy.cdm.persistence.dao.TitleCacheAutoInitializer"></bean>\r
+      <bean id="annotationTypeAutoInitializer" class="eu.etaxonomy.cdm.persistence.dao.AnnotationTypeAutoInitializer"></bean>\r
+    <bean id="defaultBeanInitializer" class="eu.etaxonomy.cdm.persistence.dao.hibernate.HibernateBeanInitializer">\r
+       <property name="beanAutoInitializers">\r
+           <map>\r
+               <entry key="eu.etaxonomy.cdm.model.common.IdentifiableEntity"  value-ref="titleCacheAutoInitializer" />\r
+                 <entry key="eu.etaxonomy.cdm.model.common.Annotation"  value-ref="annotationTypeAutoInitializer" />\r
+           </map>\r
+       </property>\r
+    </bean>\r
+\r
+    <!--\r
+      ============================== SECURITY ==============================\r
+    -->\r
     <bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">\r
         <property name="decisionVoters">\r
             <list>\r
         <property name="permissionEvaluator" ref="cdmPermissionEvaluator" />\r
     </bean>\r
 \r
-    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" depends-on="tableGeneratorGlobalOverride">\r
-        <property name="namingStrategy">\r
-          <bean class="org.hibernate.cfg.DefaultComponentSafeNamingStrategy" />\r
-        </property>\r
-\r
-        <property name="entityInterceptor" ref="securityHibernateInterceptor" />\r
-\r
-        <property name="configLocation" value="classpath:eu/etaxonomy/cdm/hibernate.cfg.xml"/>\r
-        <property  name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration"/>\r
-        <!--\r
-              If dataSource is set, this will override corresponding settings in Hibernate properties.\r
-              If this is set, the Hibernate settings should not define a connection provider to\r
-              avoid meaningless double configuration.\r
-\r
-              see also org.springframework.orm.hibernate3.AbstractSessionFactoryBean.setDataSource(DataSource dataSource)\r
-           -->\r
-        <property name="dataSource" ref="dataSource"/>\r
-        <property name="hibernateProperties" ref="hibernateProperties"/>\r
-    </bean>\r
-\r
-  <!--\r
-     Configuration for the BeanInitialization\r
-   -->\r
-  <bean id="titleCacheAutoInitializer" class="eu.etaxonomy.cdm.persistence.dao.TitleCacheAutoInitializer"></bean>\r
-    <bean id="annotationTypeAutoInitializer" class="eu.etaxonomy.cdm.persistence.dao.AnnotationTypeAutoInitializer"></bean>\r
-  <bean id="defaultBeanInitializer" class="eu.etaxonomy.cdm.persistence.dao.hibernate.HibernateBeanInitializer">\r
-     <property name="beanAutoInitializers">\r
-         <map>\r
-             <entry key="eu.etaxonomy.cdm.model.common.IdentifiableEntity"  value-ref="titleCacheAutoInitializer" />\r
-               <entry key="eu.etaxonomy.cdm.model.common.Annotation"  value-ref="annotationTypeAutoInitializer" />\r
-         </map>\r
-     </property>\r
-  </bean>\r
-\r
-\r
 </beans>\r
index a0c61d90737ca9db617cb5f68a4ac48944d98e97..09418b5dc338bbf198af8a6f873cfbed7f32b25f 100644 (file)
@@ -5,7 +5,7 @@
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * See LICENSE.TXT at the top of this package for the full license terms.
-*/ 
+*/
 
 package eu.etaxonomy.cdm.persistence.dao.hibernate.taxon;
 
@@ -33,88 +33,87 @@ import eu.etaxonomy.cdm.persistence.dao.taxon.ITaxonNodeDao;
 import eu.etaxonomy.cdm.persistence.dao.taxon.IClassificationDao;
 import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
 
-public class TaxonNodeDaoHibernateImplTest extends
-               CdmTransactionalIntegrationTest {
-
-       @SpringBeanByType       
-       private ITaxonNodeDao taxonNodeDao;
-       
-       @SpringBeanByType
-       private IClassificationDao classificationDao;
-       
-       @SpringBeanByType
-       private ITaxonDao taxonDao;
-       
-       private UUID uuid1;
-       private UUID uuid2;
-       private UUID uuid3;
-       
-       @Before
-       public void setUp(){
-               uuid1 = UUID.fromString("20c8f083-5870-4cbd-bf56-c5b2b98ab6a7");
-               uuid2 = UUID.fromString("770239f6-4fa8-496b-8738-fe8f7b2ad519");
-               AuditEventContextHolder.clearContext(); 
-       }
-       
-       @After
-       public void tearDown(){
-               AuditEventContextHolder.clearContext(); 
-       }
-       
-       
-       @Test
-       @DataSet
-       public void testInit() {
-               assertNotNull("Instance of ITaxonDao expected",taxonNodeDao);
-               assertNotNull("Instance of IReferenceDao expected",classificationDao);
-       }       
-       
-       @Test
-       @DataSet
-       public void testFindByUuid() {
-               TaxonNode taxonNode = (TaxonNode) taxonNodeDao.findByUuid(uuid1);
-               Classification.class.getDeclaredConstructors();
-               assertNotNull("findByUuid should return a taxon node", taxonNode);
-       }
-       
-       @Test
-       @DataSet
-       public void testClassification() {
-               Classification classification =  classificationDao.findByUuid(UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9"));
-               
-               assertNotNull("findByUuid should return a taxon tree", classification);
-               assertNotNull("classification should have a name",classification.getName());
-               assertEquals("classification should have a name which is 'Name'",classification.getName().getText(),"Name");
-               TaxonNode taxNode = (TaxonNode) taxonNodeDao.findByUuid(uuid1);
-               TaxonNode taxNode2 = (TaxonNode) taxonNodeDao.findByUuid(uuid2);
-               Set<TaxonNode> rootNodes = new HashSet<TaxonNode>();
-               
-               rootNodes.add(taxNode);
-               
-       
-               for (TaxonNode rootNode : rootNodes){
-                       classification.addChildNode(rootNode, rootNode.getReference(), rootNode.getMicroReference(), rootNode.getSynonymToBeUsed());
-               }
-
-               taxNode.addChildNode(taxNode2, null, null,null);
-               
-               Taxon taxon2 = taxNode2.getTaxon();
-               Taxon taxon = taxNode.getTaxon();
-               UUID uuidTaxon = taxon.getUuid();
-               UUID uuidTaxon2 = taxon2.getUuid();
-       
-               List<TaxonBase> taxa = taxonDao.getAllTaxonBases(10, 0);
-               assertEquals("there should be only two taxa", 5, taxa.size());
-               
-               taxonNodeDao.delete(taxNode2);
-                               
-               taxa = taxonDao.getAllTaxonBases(10, 0);
-               assertEquals("there should be only one taxon left", 4, taxa.size());
-               
-               classificationDao.delete(classification);
-               classification = classificationDao.findByUuid(UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9"));
-               assertEquals("The tree should be null", null, classification);
-               
-               
-       }
+public class TaxonNodeDaoHibernateImplTest extends CdmTransactionalIntegrationTest {
+
+    @SpringBeanByType
+    private ITaxonNodeDao taxonNodeDao;
+
+    @SpringBeanByType
+    private IClassificationDao classificationDao;
+
+    @SpringBeanByType
+    private ITaxonDao taxonDao;
+
+    private UUID uuid1;
+    private UUID uuid2;
+    private UUID uuid3;
+
+    @Before
+    public void setUp(){
+        uuid1 = UUID.fromString("20c8f083-5870-4cbd-bf56-c5b2b98ab6a7");
+        uuid2 = UUID.fromString("770239f6-4fa8-496b-8738-fe8f7b2ad519");
+        AuditEventContextHolder.clearContext();
+    }
+
+    @After
+    public void tearDown(){
+        AuditEventContextHolder.clearContext();
+    }
+
+
+    @Test
+    @DataSet
+    public void testInit() {
+        assertNotNull("Instance of ITaxonDao expected",taxonNodeDao);
+        assertNotNull("Instance of IReferenceDao expected",classificationDao);
+    }
+
+    @Test
+    @DataSet
+    public void testFindByUuid() {
+        TaxonNode taxonNode = (TaxonNode) taxonNodeDao.findByUuid(uuid1);
+        Classification.class.getDeclaredConstructors();
+        assertNotNull("findByUuid should return a taxon node", taxonNode);
+    }
+
+    @Test
+    @DataSet
+    public void testClassification() {
+        Classification classification =  classificationDao.findByUuid(UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9"));
+
+        assertNotNull("findByUuid should return a taxon tree", classification);
+        assertNotNull("classification should have a name",classification.getName());
+        assertEquals("classification should have a name which is 'Name'",classification.getName().getText(),"Name");
+        TaxonNode taxNode = (TaxonNode) taxonNodeDao.findByUuid(uuid1);
+        TaxonNode taxNode2 = (TaxonNode) taxonNodeDao.findByUuid(uuid2);
+        Set<TaxonNode> rootNodes = new HashSet<TaxonNode>();
+
+        rootNodes.add(taxNode);
+
+
+        for (TaxonNode rootNode : rootNodes){
+            classification.addChildNode(rootNode, rootNode.getReference(), rootNode.getMicroReference(), rootNode.getSynonymToBeUsed());
+        }
+
+        taxNode.addChildNode(taxNode2, null, null,null);
+
+        Taxon taxon2 = taxNode2.getTaxon();
+        Taxon taxon = taxNode.getTaxon();
+        UUID uuidTaxon = taxon.getUuid();
+        UUID uuidTaxon2 = taxon2.getUuid();
+
+        List<TaxonBase> taxa = taxonDao.getAllTaxonBases(10, 0);
+        assertEquals("there should be only two taxa", 5, taxa.size());
+
+        taxonNodeDao.delete(taxNode2);
+
+        taxa = taxonDao.getAllTaxonBases(10, 0);
+        assertEquals("there should be only one taxon left", 4, taxa.size());
+
+        classificationDao.delete(classification);
+        classification = classificationDao.findByUuid(UUID.fromString("aeee7448-5298-4991-b724-8d5b75a0a7a9"));
+        assertEquals("The tree should be null", null, classification);
+
+
+    }
 }
index f8efa9e9aa914c13aa9f086c629a9503b4613c11..3c822f2ebac89665656e1ae2a57b311b602626ec 100644 (file)
@@ -141,26 +141,31 @@ public class DataSourceConfigurer extends AbstractWebApplicationConfigurer {
         try {\r
 \r
             Connection connection = dataSource.getConnection();\r
-\r
-            ResultSet resultSet = connection.createStatement().executeQuery(MetaDataPropertyName.DB_SCHEMA_VERSION.getSqlQuery());\r
-            String version = null;\r
-            if(resultSet.next()){\r
-                version = resultSet.getString(1);\r
+            ResultSet tables = connection.getMetaData().getTables(connection.getCatalog(), null, "CdmMetaData", null);\r
+            if(tables.first()){\r
+                ResultSet resultSet = connection.createStatement().executeQuery(MetaDataPropertyName.DB_SCHEMA_VERSION.getSqlQuery());\r
+                String version = null;\r
+                if(resultSet.next()){\r
+                    version = resultSet.getString(1);\r
+                } else {\r
+                    throw new RuntimeException("Unable to retrieve version info from data source " + dataSource.toString());\r
+                }\r
+\r
+                connection.close();\r
+\r
+                if(!CdmMetaData.isDbSchemaVersionCompatible(version)){\r
+                    /*\r
+                     * any exception thrown here would be nested into a spring\r
+                     * BeanException which can not be caught in the servlet\r
+                     * container, so we post the information into the\r
+                     * ServletContext\r
+                     */\r
+                    String errorMessage = "Incompatible version [" + (beanName != null ? beanName : jndiName) + "] expected version: " + CdmMetaData.getDbSchemaVersion() + ",  data base version  " + version;\r
+                    addErrorMessageToServletContextAttributes(errorMessage);\r
+                }\r
             } else {\r
-                throw new RuntimeException("Unable to retrieve version info from data source " + dataSource.toString());\r
-            }\r
-\r
-            connection.close();\r
-\r
-            if(!CdmMetaData.isDbSchemaVersionCompatible(version)){\r
-                /*\r
-                 * any exception thrown here would be nested into a spring\r
-                 * BeanException which can not be caught in the servlet\r
-                 * container, so we post the information into the\r
-                 * ServletContext\r
-                 */\r
-                String errorMessage = "Incompatible version [" + (beanName != null ? beanName : jndiName) + "] expected version: " + CdmMetaData.getDbSchemaVersion() + ",  data base version  " + version;\r
-                addErrorMessageToServletContextAttributes(errorMessage);\r
+//             throw new RuntimeException("database " + dataSource.toString() + " is empty or not a cdm database");\r
+                logger.error("database " + dataSource.toString() + " is empty or not a cdm database");\r
             }\r
 \r
 \r
index 95dcf14baf6a74abe01bcc1f16215288fec8e6bf..8140c1ab06aa49fbf3d70cad62935acc86a51f03 100644 (file)
@@ -25,7 +25,6 @@
       <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
-        <version>2.3.6</version>
         <extensions>true</extensions>
         <configuration>
           <instructions>
index 3513740233c3298b59c81e378b2d898a4a58ffaf..24a00db272053be6e7cfc944722da91db9f9dea2 100644 (file)
@@ -72,9 +72,9 @@ import eu.etaxonomy.cdm.model.common.CdmMetaData;
 import eu.etaxonomy.cdm.model.common.DefinedTermBase;\r
 import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;\r
 import eu.etaxonomy.cdm.model.common.User;\r
-import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl.Role;\r
 import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;\r
 import eu.etaxonomy.cdm.persistence.hibernate.permission.Operation;\r
+import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;\r
 \r
 \r
 /**\r
@@ -247,44 +247,12 @@ public class CdmApplicationController implements ICdmApplicationConfiguration{
         setApplicationContext(applicationContext);\r
         progressMonitor.worked(1);\r
 \r
-        //initialize user and metaData for new databases\r
-        int userCount = getUserService().count(User.class);\r
-        if (userCount == 0 ){\r
-            progressMonitor.subTask("Creating Admin User");\r
-            createAdminUser();\r
-        }\r
-        progressMonitor.worked(1);\r
-\r
-        //CDM Meta Data\r
-        int metaDataCount = getCommonService().getCdmMetaData().size();\r
-        if (metaDataCount == 0){\r
-            progressMonitor.subTask("Creating Meta Data");\r
-            createMetadata();\r
-        }\r
-        progressMonitor.worked(1);\r
-\r
         progressMonitor.done();\r
         return true;\r
     }\r
 \r
-    protected void createAdminUser(){\r
-        User firstUser = User.NewInstance("admin", "00000");\r
-        GrantedAuthorityImpl role_admin = GrantedAuthorityImpl.NewInstance();\r
-        role_admin.setAuthority(Role.ROLE_ADMIN.name());\r
-        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();\r
-        authorities.add(role_admin);\r
-        firstUser.setGrantedAuthorities(authorities);\r
-        getUserService().save(firstUser);\r
-\r
 \r
-        logger.info("Admin user created.");\r
-    }\r
 \r
-    protected void createMetadata(){\r
-        List<CdmMetaData> metaData = CdmMetaData.defaultMetaData();\r
-        getCommonService().saveAllMetaData(metaData);\r
-        logger.info("Metadata created.");\r
-    }\r
 \r
 \r
     /**\r
diff --git a/cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/FirstDataInserter.java b/cdmlib-services/src/main/java/eu/etaxonomy/cdm/api/application/FirstDataInserter.java
new file mode 100644 (file)
index 0000000..1b27dcf
--- /dev/null
@@ -0,0 +1,309 @@
+// $Id$
+/**
+* Copyright (C) 2012 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.api.application;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.annotation.security.RunAs;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.context.event.ContextStartedEvent;
+import org.springframework.security.access.intercept.RunAsManager;
+import org.springframework.security.access.intercept.RunAsManagerImpl;
+import org.springframework.security.access.intercept.RunAsUserToken;
+import org.springframework.security.authentication.AnonymousAuthenticationProvider;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.authentication.dao.SaltSource;
+import org.springframework.security.authentication.encoding.PasswordEncoder;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.TransactionStatus;
+import org.springframework.transaction.support.DefaultTransactionDefinition;
+
+import eu.etaxonomy.cdm.api.service.ICommonService;
+import eu.etaxonomy.cdm.api.service.IGrantedAuthorityService;
+import eu.etaxonomy.cdm.api.service.IUserService;
+import eu.etaxonomy.cdm.common.monitor.IProgressMonitor;
+import eu.etaxonomy.cdm.common.monitor.NullProgressMonitor;
+import eu.etaxonomy.cdm.model.common.CdmMetaData;
+import eu.etaxonomy.cdm.model.common.GrantedAuthorityImpl;
+import eu.etaxonomy.cdm.model.common.User;
+import eu.etaxonomy.cdm.persistence.hibernate.permission.Role;
+import eu.etaxonomy.cdm.persistence.query.OrderHint;
+
+/**
+ * The <code>FirstDataInserter</code> is responsible for equipping a new and empty database with
+ * the initial set of data need by the cdmlib. It operates not only on empty databases,
+ * its methods are executed everytime the ApplicationContext has been started up, that is listens
+ * for {@link ContextStartedEvent}s.
+ * <p>
+ * responsibilities:
+ * <ul>
+ * <li>User 'admin' and role 'ROLE_ADMIN'</li>
+ * <li>cdm metadata</li>
+ * <ul>
+ * <p>
+ * The <code>runAsAuthenticationProvider</code> must be set in a security application context, eg:
+ * {@code
+    <bean id="firstDataInserter" class="eu.etaxonomy.cdm.api.application.FirstDataInserter">
+        <property name="runAsAuthenticationProvider" ref="runAsAuthenticationProvider"/>
+    </bean>
+    }
+ *
+ *
+ *
+ * @author a.kohlbecker
+ * @date Oct 12, 2012
+ *
+ */
+//@RunAs("ROLE_ADMIN") // seems to be broken in spring see: https://jira.springsource.org/browse/SEC-1671
+public class FirstDataInserter implements ApplicationListener<ContextRefreshedEvent> {
+
+    public static final Logger logger = Logger.getLogger(FirstDataInserter.class);
+
+    private static final long serialVersionUID = -4738245032655597608L;
+
+    /**
+     * must match the key in eu/etaxonomy/cdm/services_security.xml
+     */
+    private static final String RUN_AS_KEY = "TtlCx3pgKC4l";
+
+    @Autowired
+    private ICommonService commonService;
+
+    @Autowired
+    private IUserService userService;
+
+    @Autowired
+    private IGrantedAuthorityService grantedAuthorityService;
+
+    // not to be autowired, since the FirstdataInserter must be usable without security
+    private AuthenticationProvider runAsAuthenticationProvider = null;
+
+    protected PlatformTransactionManager transactionManager;
+
+    protected DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition();
+
+    private IProgressMonitor progressMonitor = null;
+
+    private boolean firstDataInserted = false;
+
+    private Authentication authentication;
+
+    private ApplicationContext applicationContext;
+
+    @Autowired
+    public void setTransactionManager(PlatformTransactionManager transactionManager) {
+        this.transactionManager = transactionManager;
+    }
+
+    public FirstDataInserter() {
+        txDefinition.setName("FirstDataInserter.insertFirstData()");
+        txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
+    }
+
+    @Override
+    public void onApplicationEvent(ContextRefreshedEvent event) {
+        if(event.getApplicationContext() instanceof MonitoredGenericApplicationContext){
+            progressMonitor = ((MonitoredGenericApplicationContext)event.getApplicationContext()).getCurrentMonitor();
+            /* TODO set up work amount, currently the amount of work ticks is hard coded
+             *      in {@link CdmApplicationControllersetNewDataSource}, but we need some means to register
+             *      additional ticks.
+             *      see http://dev.e-taxonomy.eu/trac/ticket/3140 (generic way to obtain work ticks of application startup for monitoring)
+             *
+             */
+        } else {
+            progressMonitor = new NullProgressMonitor();
+        }
+        applicationContext = event.getApplicationContext();
+
+        insertFirstData();
+    }
+
+
+    private void insertFirstData() {
+
+        // this ApplicationListener may be called multiple times in nested
+        // application contexts like in web applications
+        if(!firstDataInserted){
+
+            runAsAuthentication();
+
+            TransactionStatus txStatus = transactionManager.getTransaction(txDefinition);
+
+            logger.info("inserting first data");
+            checkAdminUser();
+            checkMetadata();
+            firstDataInserted = true;
+
+            transactionManager.commit(txStatus);
+
+            restoreAuthentication();
+
+        } else {
+            logger.debug("insertFirstData() already executed before, skipping this time");
+        }
+    }
+
+    /**
+     * needed to work around the broken @RunAs("ROLE_ADMIN") which
+     * seems to be broken in spring see: https://jira.springsource.org/browse/SEC-1671
+     */
+    private void restoreAuthentication() {
+        if(runAsAuthenticationProvider == null){
+            logger.debug("no RunAsAuthenticationProvider set, thus nothing to restore");
+        }
+        SecurityContext securityContext = SecurityContextHolder.getContext();
+        securityContext.setAuthentication(authentication);
+        logger.debug("last authentication restored: " + (authentication != null ? authentication : "NULL"));
+    }
+
+    /**
+     *
+     * needed to work around the broken @RunAs("ROLE_ADMIN") which seems to be
+     * broken in spring see: https://jira.springsource.org/browse/SEC-1671
+     */
+    private void runAsAuthentication() {
+        if(runAsAuthenticationProvider == null){
+            logger.debug("no RunAsAuthenticationProvider set, skipping run-as authentication");
+            return;
+        }
+
+        SecurityContext securityContext = SecurityContextHolder.getContext();
+        authentication = securityContext.getAuthentication();
+
+        RunAsUserToken adminToken = new RunAsUserToken(
+                RUN_AS_KEY,
+                "system-admin",
+                null,
+                new Role[]{Role.ROLE_ADMIN},
+                (authentication != null ? authentication.getClass() : AnonymousAuthenticationToken.class));
+
+        Authentication runAsAuthentication = runAsAuthenticationProvider.authenticate(adminToken);
+        SecurityContextHolder.getContext().setAuthentication(runAsAuthentication);
+
+        logger.debug("switched to run-as authentication: " + runAsAuthentication);
+    }
+
+
+    private void checkMetadata() {
+        int metaDataCount = commonService.getCdmMetaData().size();
+        if (metaDataCount == 0){
+            progressMonitor.subTask("Creating Meta Data");
+            createMetadata();
+        }
+    }
+
+    private void checkAdminUser() {
+        User admin = findFirstUser();
+
+        if (admin == null){
+            progressMonitor.subTask("Creating Admin User");
+            admin = createAdminUser();
+        } else {
+            logger.info("Assuming first user '" + admin + "' is admin.");
+        }
+
+        checkAdminRole(admin);
+        progressMonitor.worked(1);
+    }
+
+    /**
+     * @return
+     */
+    private User findFirstUser() {
+        User firstUser = null;
+        List<User> users = userService.list(null, 1, null, Arrays.asList(new OrderHint[]{new OrderHint("id", OrderHint.SortOrder.ASCENDING)}), null);
+        if(users.size() > 0){
+            firstUser = users.get(0);
+        }
+        return firstUser;
+    }
+
+    private User createAdminUser(){
+
+        User admin = User.NewInstance("admin", "00000");
+        userService.save(admin);
+        logger.info("user 'admin' created.");
+        return admin;
+    }
+
+    private void checkAdminRole(User admin) {
+        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
+
+
+        authorities = (Set<GrantedAuthority>) admin.getAuthorities();
+
+        boolean hasRoleAdmin = false;
+        for(GrantedAuthority grau : authorities){
+            if(grau.getAuthority().contentEquals(Role.ROLE_ADMIN.getAuthority())){
+                hasRoleAdmin = true;
+                break;
+            }
+        }
+
+        if(!hasRoleAdmin){
+            authorities.add(getRoleAdmin());
+            admin.setGrantedAuthorities(authorities);
+            progressMonitor.subTask("Creating Admins Role");
+            userService.saveOrUpdate(admin);
+            logger.info("Role " + Role.ROLE_ADMIN.getAuthority() + " for user 'admin' created and added");
+        }
+    }
+
+    /**
+     * @return
+     */
+    private GrantedAuthorityImpl getRoleAdmin() {
+        GrantedAuthorityImpl role_admin = grantedAuthorityService.find(Role.ROLE_ADMIN.getUuid());
+        if(role_admin == null){
+            role_admin = Role.ROLE_ADMIN.asNewGrantedAuthority();
+        }
+        return role_admin;
+    }
+
+    private void createMetadata(){
+        List<CdmMetaData> metaData = CdmMetaData.defaultMetaData();
+        commonService.saveAllMetaData(metaData);
+        logger.info("Metadata created.");
+    }
+
+    /**
+     * @return the runAsAuthenticationProvider
+     */
+    public AuthenticationProvider getRunAsAuthenticationProvider() {
+        return runAsAuthenticationProvider;
+    }
+
+    /**
+     * @param runAsAuthenticationProvider the runAsAuthenticationProvider to set
+     */
+    public void setRunAsAuthenticationProvider(AuthenticationProvider runAsAuthenticationProvider) {
+        this.runAsAuthenticationProvider = runAsAuthenticationProvider;
+    }
+
+
+}
\ No newline at end of file
index 15d379a03e5450e45381691bf7ccbfa17d8d10bd..fccbb424ef7cd93dfbae6d8d88707f2cf9048e5d 100644 (file)
@@ -1,9 +1,9 @@
 // $Id$\r
 /**\r
 * Copyright (C) 2009 EDIT\r
-* European Distributed Institute of Taxonomy \r
+* European Distributed Institute of Taxonomy\r
 * http://www.e-taxonomy.eu\r
-* \r
+*\r
 * The contents of this file are subject to the Mozilla Public License Version 1.1\r
 * See LICENSE.TXT at the top of this package for the full license terms.\r
 */\r
@@ -28,105 +28,112 @@ import eu.etaxonomy.cdm.common.monitor.SubProgressMonitor;
  *\r
  */\r
 public class MonitoredGenericApplicationContext extends GenericApplicationContext{\r
-       @SuppressWarnings("unused")\r
-       private static final Logger logger = Logger.getLogger(CdmApplicationController.class);\r
-       \r
-       final int countInvokeBeanFactoryPostProcessors = 10;\r
-       final int countFinishBeanFactoryInitialization = 90;\r
-       private final int countTasks = countInvokeBeanFactoryPostProcessors + countFinishBeanFactoryInitialization;\r
-       private IProgressMonitor currentMonitor;\r
-\r
-       \r
-       \r
-       /**\r
-        * Constructor.\r
-        * @param progressMonitor\r
-        */\r
-       public MonitoredGenericApplicationContext() {\r
-//             MonitoredListableBeanFactory beanFactory = \r
-               super(new MonitoredListableBeanFactory());\r
-               //taken from empty constructor of GenericApplicationContext\r
-               ((MonitoredListableBeanFactory)getBeanFactory()).setSerializationId(getId());\r
-               ((MonitoredListableBeanFactory)getBeanFactory()).setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer());\r
-               ((MonitoredListableBeanFactory)getBeanFactory()).setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());\r
-       }\r
-\r
-\r
-       public int countTasks(){\r
-               return countTasks;\r
-       }\r
-\r
-       protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory){\r
-               String task = "Invoke bean factory post processors";\r
-               checkMonitorCancelled(currentMonitor);\r
-               currentMonitor.subTask(task);\r
-               super.invokeBeanFactoryPostProcessors(beanFactory);\r
-               currentMonitor.worked(countInvokeBeanFactoryPostProcessors);\r
-               checkMonitorCancelled(currentMonitor);\r
-       }\r
-\r
-       protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){\r
-               checkMonitorCancelled(currentMonitor);\r
-               String task = "Finish bean factory initialization";\r
-               currentMonitor.subTask(task);\r
-               IProgressMonitor subMonitor     = new SubProgressMonitor(currentMonitor, countFinishBeanFactoryInitialization);\r
-               getMyBeanFactory().setCurrentMonitor(subMonitor);\r
-               super.finishBeanFactoryInitialization(beanFactory);\r
-               checkMonitorCancelled(currentMonitor);\r
-               \r
-       }\r
-\r
-       /**\r
-        * @param progressMonitor the progressMonitor to set\r
-        */\r
-       public void setCurrentMonitor(IProgressMonitor monitor) {\r
-               this.currentMonitor = monitor;\r
-       }\r
-\r
-\r
-       /* (non-Javadoc)\r
-        * @see org.springframework.context.support.AbstractApplicationContext#refresh()\r
-        */\r
-       public void refresh(IProgressMonitor monitor) throws BeansException, IllegalStateException {\r
-               checkMonitorCancelled(monitor);\r
-               String message = "Refresh application context. This might take a while ...";\r
-               currentMonitor = monitor;\r
-               beginTask(message, countTasks);\r
-               super.refresh();\r
-               taskDone();\r
-               checkMonitorCancelled(monitor);\r
-       }\r
-\r
-\r
-       /**\r
-        * \r
-        */\r
-       private void taskDone() {\r
-               if (currentMonitor != null){\r
-                       currentMonitor.done();\r
-               }\r
-       }\r
-\r
-\r
-       /**\r
-        * @param monitor\r
-        * @param message\r
-        */\r
-       private void beginTask(String message, int countTasks) {\r
-               if (currentMonitor != null){\r
-                       currentMonitor.beginTask(message, countTasks);\r
-               }\r
-       }\r
-       \r
-       \r
-       private MonitoredListableBeanFactory getMyBeanFactory(){\r
-               return (MonitoredListableBeanFactory)getBeanFactory();\r
-       }\r
-       \r
-       \r
-       private void checkMonitorCancelled(IProgressMonitor monitor) {\r
-               if (monitor != null && monitor.isCanceled()){\r
-                       throw new CancellationException();\r
-               }       \r
-       }\r
+    @SuppressWarnings("unused")\r
+    private static final Logger logger = Logger.getLogger(CdmApplicationController.class);\r
+\r
+    final int countInvokeBeanFactoryPostProcessors = 10;\r
+    final int countFinishBeanFactoryInitialization = 90;\r
+    private final int countTasks = countInvokeBeanFactoryPostProcessors + countFinishBeanFactoryInitialization;\r
+    private IProgressMonitor currentMonitor;\r
+\r
+\r
+\r
+    /**\r
+     * Constructor.\r
+     * @param progressMonitor\r
+     */\r
+    public MonitoredGenericApplicationContext() {\r
+//             MonitoredListableBeanFactory beanFactory =\r
+        super(new MonitoredListableBeanFactory());\r
+        //taken from empty constructor of GenericApplicationContext\r
+        ((MonitoredListableBeanFactory)getBeanFactory()).setSerializationId(getId());\r
+        ((MonitoredListableBeanFactory)getBeanFactory()).setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer());\r
+        ((MonitoredListableBeanFactory)getBeanFactory()).setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());\r
+    }\r
+\r
+\r
+    public int countTasks(){\r
+        return countTasks;\r
+    }\r
+\r
+    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory){\r
+        String task = "Invoke bean factory post processors";\r
+        checkMonitorCancelled(currentMonitor);\r
+        currentMonitor.subTask(task);\r
+        super.invokeBeanFactoryPostProcessors(beanFactory);\r
+        currentMonitor.worked(countInvokeBeanFactoryPostProcessors);\r
+        checkMonitorCancelled(currentMonitor);\r
+    }\r
+\r
+    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){\r
+        checkMonitorCancelled(currentMonitor);\r
+        String task = "Finish bean factory initialization";\r
+        currentMonitor.subTask(task);\r
+        IProgressMonitor subMonitor    = new SubProgressMonitor(currentMonitor, countFinishBeanFactoryInitialization);\r
+        getMyBeanFactory().setCurrentMonitor(subMonitor);\r
+        super.finishBeanFactoryInitialization(beanFactory);\r
+        checkMonitorCancelled(currentMonitor);\r
+\r
+    }\r
+\r
+    /**\r
+     * @param progressMonitor the progressMonitor to set\r
+     */\r
+    public void setCurrentMonitor(IProgressMonitor monitor) {\r
+        this.currentMonitor = monitor;\r
+    }\r
+\r
+    /**\r
+     *\r
+     */\r
+    public IProgressMonitor getCurrentMonitor() {\r
+        return currentMonitor;\r
+    }\r
+\r
+\r
+    /* (non-Javadoc)\r
+     * @see org.springframework.context.support.AbstractApplicationContext#refresh()\r
+     */\r
+    public void refresh(IProgressMonitor monitor) throws BeansException, IllegalStateException {\r
+        checkMonitorCancelled(monitor);\r
+        String message = "Refresh application context. This might take a while ...";\r
+        currentMonitor = monitor;\r
+        beginTask(message, countTasks);\r
+        super.refresh();\r
+        taskDone();\r
+        checkMonitorCancelled(monitor);\r
+    }\r
+\r
+\r
+    /**\r
+     *\r
+     */\r
+    private void taskDone() {\r
+        if (currentMonitor != null){\r
+            currentMonitor.done();\r
+        }\r
+    }\r
+\r
+\r
+    /**\r
+     * @param monitor\r
+     * @param message\r
+     */\r
+    private void beginTask(String message, int countTasks) {\r
+        if (currentMonitor != null){\r
+            currentMonitor.beginTask(message, countTasks);\r
+        }\r
+    }\r
+\r
+\r
+    private MonitoredListableBeanFactory getMyBeanFactory(){\r
+        return (MonitoredListableBeanFactory)getBeanFactory();\r
+    }\r
+\r
+\r
+    private void checkMonitorCancelled(IProgressMonitor monitor) {\r
+        if (monitor != null && monitor.isCanceled()){\r
+            throw new CancellationException();\r
+        }\r
+    }\r
 }\r
index 190797d630a1b264bcadf85b23b10d199286516f..20fe34f61c29d1bdd7fd39e6dabaff1186c12135 100644 (file)
@@ -12,30 +12,22 @@ package eu.etaxonomy.cdm.api.service;
 \r
 import java.util.ArrayList;\r
 import java.util.Collection;\r
-import java.util.EnumSet;\r
 import java.util.List;\r
 import java.util.Map;\r
 import java.util.Set;\r
 import java.util.UUID;\r
 \r
-import javax.management.relation.RoleUnresolvedList;\r
-\r
 import org.apache.log4j.Logger;\r
 import org.hibernate.LockMode;\r
 import org.hibernate.Session;\r
 import org.springframework.context.ApplicationContext;\r
 import org.springframework.context.ApplicationContextAware;\r
-import org.springframework.security.core.Authentication;\r
 import org.springframework.transaction.annotation.Transactional;\r
 \r
 import eu.etaxonomy.cdm.api.service.pager.Pager;\r
 import eu.etaxonomy.cdm.api.service.pager.impl.DefaultPagerImpl;\r
 import eu.etaxonomy.cdm.model.common.CdmBase;\r
-\r
 import eu.etaxonomy.cdm.persistence.dao.common.ICdmEntityDao;\r
-import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;\r
-import eu.etaxonomy.cdm.persistence.hibernate.permission.Operation;\r
-import eu.etaxonomy.cdm.persistence.hibernate.permission.CdmPermissionEvaluator;\r
 import eu.etaxonomy.cdm.persistence.query.Grouping;\r
 import eu.etaxonomy.cdm.persistence.query.OrderHint;\r
 \r
index 30d79801d72a3956e8ecf816eff69cfad0a7614d..7b13d8cbf9dc3d689e0dcb4074f8adc7f51aa0a6 100644 (file)
@@ -374,7 +374,7 @@ public class UserService extends ServiceBase<User,IUserDao> implements IUserServ
     }\r
 \r
     @Transactional(readOnly=false)\r
-    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER_MANAGER')")\r
+    @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_RUN_AS_ADMIN') or hasRole('ROLE_USER_MANAGER')")\r
     public UUID save(User user) {\r
         if(user.getId() == 0 || dao.load(user.getUuid()) == null){\r
             createUser(user);\r
index 85509065b199da5787cdffa2258eabbcc64d7728..6b4f6af5d57281f6dd367602c4661ebb911aef53 100644 (file)
@@ -11,7 +11,9 @@
 \r
     <!--\r
         ======================================================================\r
-          default service configuration (same as in services.xml)\r
+          default service configuration (same as in services_security.xml)\r
+          this config file should soon be removed since the cdmlib should\r
+          never be without security\r
         ======================================================================\r
      -->\r
     <context:component-scan base-package="eu/etaxonomy/cdm/persistence">\r
@@ -25,4 +27,7 @@
     <!-- also find the implementation of ITaxonNodeComparator (otherwise it is not found by a component scan)  -->\r
     <bean name="taxonNodeByNameComparator" class="eu.etaxonomy.cdm.model.taxon.TaxonNodeByNameComparator">\r
     </bean>\r
+\r
+    <!-- equips a new and empty database with the initial set of meta data and admin user   -->\r
+    <bean id="firstDataInserter" class="eu.etaxonomy.cdm.api.application.FirstDataInserter" />\r
 </beans>\r
index e674700c9d2165a10235f04f6ca2580d012c673f..ab9cb112da70b745933adb30480cef1c81758c1d 100644 (file)
@@ -34,7 +34,7 @@
           security specific configuration\r
         ======================================================================\r
      -->\r
-    <security:global-method-security pre-post-annotations="enabled">\r
+    <security:global-method-security pre-post-annotations="enabled" run-as-manager-ref="runAsManager" >\r
         <security:expression-handler ref="expressionHandler" />\r
     </security:global-method-security>\r
 \r
         <property name="userPropertyToUse" value="getUsername"/>\r
     </bean>\r
 \r
+    <!--\r
+        Run-As Authentication Replacement for system operations\r
+        as e.g. performed by the eu.etaxonomy.cdm.api.application.FirstDataInserter\r
+\r
+        the key must match FirstDataInserter.RUN_AS_KEY\r
+     -->\r
+    <bean id="runAsManager"\r
+        class="org.springframework.security.access.intercept.RunAsManagerImpl">\r
+      <property name="key" value="TtlCx3pgKC4l"/>\r
+    </bean>\r
+\r
+    <bean id="runAsAuthenticationProvider"\r
+        class="org.springframework.security.access.intercept.RunAsImplAuthenticationProvider">\r
+      <property name="key" value="TtlCx3pgKC4l"/>\r
+    </bean>\r
+\r
+    <!-- equips a new and empty database with the initial set of meta data and admin user   -->\r
+    <bean id="firstDataInserter" class="eu.etaxonomy.cdm.api.application.FirstDataInserter">\r
+        <property name="runAsAuthenticationProvider" ref="runAsAuthenticationProvider"/>\r
+    </bean>\r
+\r
 </beans>\r
diff --git a/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.java b/cdmlib-services/src/test/java/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.java
new file mode 100644 (file)
index 0000000..18cbd82
--- /dev/null
@@ -0,0 +1,39 @@
+// $Id$
+/**
+* Copyright (C) 2012 EDIT
+* European Distributed Institute of Taxonomy
+* http://www.e-taxonomy.eu
+*
+* The contents of this file are subject to the Mozilla Public License Version 1.1
+* See LICENSE.TXT at the top of this package for the full license terms.
+*/
+package eu.etaxonomy.cdm.api.application;
+
+import org.junit.Test;
+import org.unitils.dbunit.annotation.DataSet;
+import org.unitils.dbunit.annotation.ExpectedDataSet;
+
+import eu.etaxonomy.cdm.test.integration.CdmTransactionalIntegrationTest;
+
+/**
+ * test for the {@link FirstDataInserter}
+ *
+ * @author a.kohlbecker
+ * @date Oct 12, 2012
+ *
+ */
+@DataSet
+public class FirstDataInserterTest extends CdmTransactionalIntegrationTest {
+
+    private final String[] tableNames = new String[]{"USERACCOUNT", "USERACCOUNT_GRANTEDAUTHORITYIMPL", "GRANTEDAUTHORITYIMPL", "CDMMETADATA"};
+
+    @Test
+    @DataSet(value="FirstDataInserterTest.testBlankDB.xml")
+    @ExpectedDataSet(value="FirstDataInserterTest.testBlankDB-result.xml")
+    public void testBlankDB(){
+
+        commitAndStartNewTransaction(null);
+//        printDataSet(System.err, tableNames);
+    }
+
+}
index a4200c226ec64c203807a99b27363a7a5960eda9..1a6214f4b9c3c8956c273ffd19ad9f95161b2852 100644 (file)
 
 package eu.etaxonomy.cdm.api.service;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
@@ -26,25 +22,22 @@ import org.apache.log4j.Level;
 import org.apache.log4j.Logger;
 import org.junit.Ignore;
 import org.junit.Test;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.unitils.dbunit.annotation.DataSet;
 import org.unitils.spring.annotation.SpringBeanByType;
 
 import eu.etaxonomy.cdm.model.name.Rank;
 import eu.etaxonomy.cdm.model.taxon.Classification;
-import eu.etaxonomy.cdm.model.taxon.ITaxonNodeComparator;
 import eu.etaxonomy.cdm.model.taxon.TaxonNode;
 import eu.etaxonomy.cdm.model.taxon.TaxonNodeByNameComparator;
 import eu.etaxonomy.cdm.test.integration.CdmIntegrationTest;
 
-import eu.etaxonomy.cdm.model.name.NonViralName;
-
 /**
  * @author n.hoffmann
  * @created Sep 22, 2009
  * @version 1.0
  */
 public class ClassificationServiceImplTest extends CdmIntegrationTest{
+
     private static final Logger logger = Logger.getLogger(ClassificationServiceImplTest.class);
 
     @SpringBeanByType
@@ -113,27 +106,27 @@ public class ClassificationServiceImplTest extends CdmIntegrationTest{
         taxonNodes.remove(index);
         Collections.sort(taxonNodes, taxonNodeComparator);
 
-               /**
-                * expected order is:
-                *  Acacia subg. Aculeiferum Pedley
+        /**
+         * expected order is:
+         *  Acacia subg. Aculeiferum Pedley
          *  Acacia sect. Botrycephalae Yuji Sasaki
          *  Acacia subg. Phyllodineae N.Jacobsen, Bastm. & Yuji Sasaki
          *  Acacia cuspidifolia Maslin
          *  Acacia mearnsii Benth
-                */
+         */
 
-               logger.setLevel(Level.DEBUG);
-               if(logger.isDebugEnabled()){
-                       logger.debug("-------------");
+        logger.setLevel(Level.DEBUG);
+        if(logger.isDebugEnabled()){
+            logger.debug("-------------");
         for (TaxonNode node: taxonNodes){
-                               logger.debug(node.getTaxon().getName().getTitleCache() );
+                logger.debug(node.getTaxon().getName().getTitleCache() );
             /*for (TaxonNode child : node.getChildNodes()){
-                               logger.debug(child.getTaxon().getName().getTitleCache());
+                    logger.debug(child.getTaxon().getName().getTitleCache());
             }*/
         }
-               }
+        }
 
-               Assert.assertEquals("Acacia subg. Aculeiferum Pedley", taxonNodes.get(0).getTaxon().getName().getTitleCache());
+        Assert.assertEquals("Acacia subg. Aculeiferum Pedley", taxonNodes.get(0).getTaxon().getName().getTitleCache());
 
         /*
         ((TaxonNodeByNameComparator)taxonNodeComparator).setSortInfraGenericFirst(false);
index 11a4ab29654fe9d4ddb8cb9f93cca0d9bda17006..a66461422cc1266ba05be085f63b80655a68aed5 100644 (file)
@@ -1,8 +1,8 @@
 /**\r
 * Copyright (C) 2009 EDIT\r
-* European Distributed Institute of Taxonomy \r
+* European Distributed Institute of Taxonomy\r
 * http://www.e-taxonomy.eu\r
-* \r
+*\r
 * The contents of this file are subject to the Mozilla Public License Version 1.1\r
 * See LICENSE.TXT at the top of this package for the full license terms.\r
 */\r
@@ -21,7 +21,6 @@ import junit.framework.Assert;
 import org.apache.log4j.Logger;\r
 import org.junit.Test;\r
 import org.unitils.dbunit.annotation.DataSet;\r
-import org.unitils.spring.annotation.SpringApplicationContext;\r
 import org.unitils.spring.annotation.SpringBeanByType;\r
 \r
 import eu.etaxonomy.cdm.api.service.pager.Pager;\r
@@ -40,130 +39,129 @@ import eu.etaxonomy.cdm.test.integration.CdmIntegrationTest;
  * @version 1.0\r
  */\r
 \r
-@SpringApplicationContext("file:./target/test-classes/eu/etaxonomy/cdm/applicationContext-test.xml")\r
 public class DescriptionServiceImplTest extends CdmIntegrationTest {\r
-       @SuppressWarnings("unused")\r
-       private static Logger logger = Logger.getLogger(DescriptionServiceImplTest.class);\r
-       \r
-       @SpringBeanByType\r
-       private IDescriptionService service;\r
-\r
-       @SpringBeanByType\r
-       private ITermService termService;\r
-\r
-       \r
-\r
-       @Test\r
-       public void testGetDefaultFeatureVocabulary() {\r
-               \r
-               service.getDefaultFeatureVocabulary();\r
-       }\r
-       \r
-       @Test\r
-       @DataSet("CommonServiceImplTest.xml")\r
-       public void testChangeDescriptionElement(){\r
-               DescriptionBase descBase = service.find(UUID.fromString("eb17b80a-9be6-4642-a6a8-b19a318925e6"));\r
-               Set<DescriptionElementBase> elements = descBase.getElements();\r
-               Iterator iterator = elements.iterator();\r
-               while (iterator.hasNext()){\r
-                       DescriptionElementBase base = (DescriptionElementBase) iterator.next();\r
-                       if (base instanceof TextData){\r
-                               TextData textdata = (TextData) base;\r
-                               Set <Entry<Language,LanguageString>> entries = textdata.getMultilanguageText().entrySet();\r
-                               Iterator entryIterator = entries.iterator();\r
-                               while (entryIterator.hasNext()){\r
-                                       Entry <Language, LanguageString> entry = (Entry<Language, LanguageString>) entryIterator.next();\r
-                                       LanguageString langString = entry.getValue();\r
+    @SuppressWarnings("unused")\r
+    private static Logger logger = Logger.getLogger(DescriptionServiceImplTest.class);\r
+\r
+    @SpringBeanByType\r
+    private IDescriptionService service;\r
+\r
+    @SpringBeanByType\r
+    private ITermService termService;\r
+\r
+\r
+\r
+    @Test\r
+    public void testGetDefaultFeatureVocabulary() {\r
+\r
+        service.getDefaultFeatureVocabulary();\r
+    }\r
+\r
+    @Test\r
+    @DataSet("CommonServiceImplTest.xml")\r
+    public void testChangeDescriptionElement(){\r
+        DescriptionBase descBase = service.find(UUID.fromString("eb17b80a-9be6-4642-a6a8-b19a318925e6"));\r
+        Set<DescriptionElementBase> elements = descBase.getElements();\r
+        Iterator iterator = elements.iterator();\r
+        while (iterator.hasNext()){\r
+            DescriptionElementBase base = (DescriptionElementBase) iterator.next();\r
+            if (base instanceof TextData){\r
+                TextData textdata = (TextData) base;\r
+                Set <Entry<Language,LanguageString>> entries = textdata.getMultilanguageText().entrySet();\r
+                Iterator entryIterator = entries.iterator();\r
+                while (entryIterator.hasNext()){\r
+                    Entry <Language, LanguageString> entry = (Entry<Language, LanguageString>) entryIterator.next();\r
+                    LanguageString langString = entry.getValue();\r
 //                                     System.out.println(langString);\r
-                                       langString.setText("blablubber");\r
-                               }\r
-                       }\r
-                       \r
-               }\r
-               service.saveOrUpdate(descBase);\r
-               Pager<DescriptionElementBase> allElements = service.getDescriptionElements(null, null, null, null, null, null);\r
-               Assert.assertEquals(1, allElements.getCount().intValue());\r
-               DescriptionElementBase test = allElements.getRecords().get(0);\r
-               if (test instanceof TextData){\r
-               \r
-                       Set <Entry<Language,LanguageString>> entries = ((TextData) test).getMultilanguageText().entrySet();\r
-                       Iterator entryIterator = entries.iterator();\r
-                       while (entryIterator.hasNext()){\r
-                               Entry <Language, LanguageString> entry = (Entry<Language, LanguageString>) entryIterator.next();\r
-                               LanguageString langString = entry.getValue();\r
+                    langString.setText("blablubber");\r
+                }\r
+            }\r
+\r
+        }\r
+        service.saveOrUpdate(descBase);\r
+        Pager<DescriptionElementBase> allElements = service.getDescriptionElements(null, null, null, null, null, null);\r
+        Assert.assertEquals(1, allElements.getCount().intValue());\r
+        DescriptionElementBase test = allElements.getRecords().get(0);\r
+        if (test instanceof TextData){\r
+\r
+            Set <Entry<Language,LanguageString>> entries = ((TextData) test).getMultilanguageText().entrySet();\r
+            Iterator entryIterator = entries.iterator();\r
+            while (entryIterator.hasNext()){\r
+                Entry <Language, LanguageString> entry = (Entry<Language, LanguageString>) entryIterator.next();\r
+                LanguageString langString = entry.getValue();\r
 //                             System.out.println(langString);\r
-                       }\r
-               }\r
-       }\r
-       \r
-       @Test\r
-       public void testMoveDescriptionElementsToTaxon(){\r
-               UUID commonNameFeatureUuid = Feature.COMMON_NAME().getUuid();\r
-               \r
-               Feature commonNameFeature = (Feature)termService.find(commonNameFeatureUuid);\r
-               \r
-               TaxonDescription sourceDescription = TaxonDescription.NewInstance();\r
-               \r
-               TextData element = TextData.NewInstance();\r
-               element.setFeature(commonNameFeature);\r
-               sourceDescription.addElement(element);\r
-               \r
-               TextData element2 = TextData.NewInstance();\r
-               element2.setFeature(commonNameFeature);\r
-               sourceDescription.addElement(element2);\r
-               \r
-               Collection<DescriptionElementBase> sourceCollection = new HashSet<DescriptionElementBase>();\r
-               sourceCollection.addAll(sourceDescription.getElements());\r
-               TextData element3 = TextData.NewInstance();\r
-               element3.setFeature(commonNameFeature);\r
-               \r
-               sourceDescription.addElement(element3);\r
-\r
-               Assert.assertEquals(3, sourceDescription.getElements().size());\r
-               \r
-               TaxonDescription targetDescription = TaxonDescription.NewInstance();\r
-               this.service.save(sourceDescription);\r
-               this.service.save(targetDescription);\r
-               \r
-               service.moveDescriptionElementsToDescription(sourceCollection, targetDescription, false);\r
-               \r
-               Assert.assertEquals("Source descirption should have 1 element left", 1, sourceDescription.getElements().size());\r
-               Assert.assertEquals("Target descriptoin should have 2 new elements", 2, targetDescription.getElements().size());\r
+            }\r
+        }\r
+    }\r
+\r
+    @Test\r
+    public void testMoveDescriptionElementsToTaxon(){\r
+        UUID commonNameFeatureUuid = Feature.COMMON_NAME().getUuid();\r
+\r
+        Feature commonNameFeature = (Feature)termService.find(commonNameFeatureUuid);\r
+\r
+        TaxonDescription sourceDescription = TaxonDescription.NewInstance();\r
+\r
+        TextData element = TextData.NewInstance();\r
+        element.setFeature(commonNameFeature);\r
+        sourceDescription.addElement(element);\r
+\r
+        TextData element2 = TextData.NewInstance();\r
+        element2.setFeature(commonNameFeature);\r
+        sourceDescription.addElement(element2);\r
+\r
+        Collection<DescriptionElementBase> sourceCollection = new HashSet<DescriptionElementBase>();\r
+        sourceCollection.addAll(sourceDescription.getElements());\r
+        TextData element3 = TextData.NewInstance();\r
+        element3.setFeature(commonNameFeature);\r
+\r
+        sourceDescription.addElement(element3);\r
+\r
+        Assert.assertEquals(3, sourceDescription.getElements().size());\r
+\r
+        TaxonDescription targetDescription = TaxonDescription.NewInstance();\r
+        this.service.save(sourceDescription);\r
+        this.service.save(targetDescription);\r
+\r
+        service.moveDescriptionElementsToDescription(sourceCollection, targetDescription, false);\r
+\r
+        Assert.assertEquals("Source descirption should have 1 element left", 1, sourceDescription.getElements().size());\r
+        Assert.assertEquals("Target descriptoin should have 2 new elements", 2, targetDescription.getElements().size());\r
 //the following tests are not valid anymore as elements are cloned now even if isCopy is false\r
 //             Assert.assertTrue("The moved element should be in the new description", targetDescription.getElements().contains(element));\r
 //             Assert.assertTrue("The moved element2 should be in the new description", targetDescription.getElements().contains(element2));\r
 //             Assert.assertFalse("Element3 should not be in the new description", targetDescription.getElements().contains(element3));\r
-               Assert.assertTrue("Element3 should remain in the old description", sourceDescription.getElements().contains(element3));\r
-               this.service.save(sourceDescription);\r
-               this.service.save(targetDescription);\r
-               \r
-               try {\r
-                       service.moveDescriptionElementsToDescription(targetDescription.getElements(), sourceDescription, false);\r
-               } catch (Exception e) {\r
-                       //asserting that no ConcurrentModificationException is thrown when the elements collection is passed as a parameter\r
-                       e.printStackTrace();\r
-                       Assert.fail();\r
-               }\r
-               \r
-               Assert.assertEquals("Source description should have 3 elements again", 3, sourceDescription.getElements().size());\r
-               Assert.assertEquals("Destination description should have no elements again", 0, targetDescription.getElements().size());\r
-               this.service.save(sourceDescription);\r
-               this.service.save(targetDescription);\r
-               \r
-               //test copy\r
-               sourceCollection.clear();\r
-               sourceCollection.add(sourceDescription.getElements().iterator().next());\r
-               service.moveDescriptionElementsToDescription(sourceCollection, targetDescription, true);\r
-               \r
-               Assert.assertEquals("Source description should still have 3 elements", 3, sourceDescription.getElements().size());\r
-               int size = targetDescription.getElements().size();\r
-               Assert.assertEquals("Destination descirption should have 1 element again", 1, size);\r
-               for (DescriptionElementBase targetElement : targetDescription.getElements()){\r
-                       Assert.assertFalse("Target elements may not be in sourced description as they are only clones (but not same).", sourceDescription.getElements().contains(targetElement));\r
-               }\r
-               this.service.save(targetDescription);\r
-               this.service.save(sourceDescription);\r
-               \r
-               \r
-       }\r
+        Assert.assertTrue("Element3 should remain in the old description", sourceDescription.getElements().contains(element3));\r
+        this.service.save(sourceDescription);\r
+        this.service.save(targetDescription);\r
+\r
+        try {\r
+            service.moveDescriptionElementsToDescription(targetDescription.getElements(), sourceDescription, false);\r
+        } catch (Exception e) {\r
+            //asserting that no ConcurrentModificationException is thrown when the elements collection is passed as a parameter\r
+            e.printStackTrace();\r
+            Assert.fail();\r
+        }\r
+\r
+        Assert.assertEquals("Source description should have 3 elements again", 3, sourceDescription.getElements().size());\r
+        Assert.assertEquals("Destination description should have no elements again", 0, targetDescription.getElements().size());\r
+        this.service.save(sourceDescription);\r
+        this.service.save(targetDescription);\r
+\r
+        //test copy\r
+        sourceCollection.clear();\r
+        sourceCollection.add(sourceDescription.getElements().iterator().next());\r
+        service.moveDescriptionElementsToDescription(sourceCollection, targetDescription, true);\r
+\r
+        Assert.assertEquals("Source description should still have 3 elements", 3, sourceDescription.getElements().size());\r
+        int size = targetDescription.getElements().size();\r
+        Assert.assertEquals("Destination descirption should have 1 element again", 1, size);\r
+        for (DescriptionElementBase targetElement : targetDescription.getElements()){\r
+            Assert.assertFalse("Target elements may not be in sourced description as they are only clones (but not same).", sourceDescription.getElements().contains(targetElement));\r
+        }\r
+        this.service.save(targetDescription);\r
+        this.service.save(sourceDescription);\r
+\r
+\r
+    }\r
 }\r
index 7c739b636efda0dbe328939626022af2cea689b2..93141db39472dc76250630db1447466c49a95df6 100644 (file)
@@ -234,7 +234,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{
             userService.createUser(User.NewInstance("new guy", "alkjdsfalkj"));\r
             commitAndStartNewTransaction(null);\r
         } catch (AccessDeniedException e){\r
-            logger.error("Unexpected failure of evaluation.", e);\r
+            logger.debug("Expected failure of evaluation.", e);\r
             exception = e;\r
         } catch (RuntimeException e){\r
             exception = findThrowableOfTypeIn(EvaluationFailedException.class, e);\r
@@ -690,6 +690,7 @@ public class SecurityTest extends CdmTransactionalIntegrationTestWithSecurity{
             commitAndStartNewTransaction(null);\r
         } catch (RuntimeException e){\r
             securityException = findSecurityRuntimeException(e);\r
+            logger.error("RuntimeException caught");\r
             logger.debug("Expected failure of evaluation.", securityException);\r
         } finally {\r
             // needed in case saveOrUpdate was interrupted by the RuntimeException\r
index 1f23b4914f1449fe960e950d977a1e75b4bb3766..23b5d1b58f05d222495f3eeb89bf580867371b45 100644 (file)
@@ -23,7 +23,6 @@ import java.util.Set;
 import java.util.UUID;\r
 \r
 import org.apache.commons.lang.RandomStringUtils;\r
-import org.apache.commons.lang.StringUtils;\r
 import org.apache.log4j.Logger;\r
 import org.apache.lucene.document.Document;\r
 import org.apache.lucene.index.CorruptIndexException;\r
@@ -37,7 +36,6 @@ import org.unitils.spring.annotation.SpringBeanByType;
 import eu.etaxonomy.cdm.api.service.config.FindTaxaAndNamesConfiguratorImpl;\r
 import eu.etaxonomy.cdm.api.service.config.IFindTaxaAndNamesConfigurator;\r
 import eu.etaxonomy.cdm.api.service.pager.Pager;\r
-import eu.etaxonomy.cdm.api.service.pager.impl.DefaultPagerImpl;\r
 import eu.etaxonomy.cdm.api.service.search.ICdmMassIndexer;\r
 import eu.etaxonomy.cdm.api.service.search.SearchResult;\r
 import eu.etaxonomy.cdm.common.monitor.DefaultProgressMonitor;\r
@@ -76,7 +74,7 @@ import eu.etaxonomy.cdm.test.unitils.CleanSweepInsertLoadStrategy;
  * @created 04.02.2009\r
  * @version 1.0\r
  */\r
-\r
+@Ignore\r
 public class TaxonServiceSearchTest extends CdmTransactionalIntegrationTest {\r
 \r
     private static final String ABIES_BALSAMEA_UUID = "f65d47bd-4f49-4ab1-bc4a-bc4551eaa1a8";\r
diff --git a/cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB-result.xml b/cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB-result.xml
new file mode 100644 (file)
index 0000000..0406857
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<dataset>
+  <USERACCOUNT ACCOUNTNONEXPIRED="true" ACCOUNTNONLOCKED="true" CREDENTIALSNONEXPIRED="true" ENABLED="true" PASSWORD="dd55f17f6275cf0fc63962d1015e18fb" USERNAME="admin"/>
+  <USERACCOUNT_GRANTEDAUTHORITYIMPL USERACCOUNT_ID="1000" GRANTEDAUTHORITIES_ID="1000"/>
+  <!-- ROLE_ADMIN.uuid is fixed ! -->
+  <GRANTEDAUTHORITYIMPL UUID="56eac992-67ba-40be-896c-4e992ca2afc0" AUTHORITY="ROLE_ADMIN"/>
+  <!-- cannot test for VALUES -->
+  <CDMMETADATA PROPERTYNAME="0" />
+  <CDMMETADATA PROPERTYNAME="1" />
+  <CDMMETADATA PROPERTYNAME="2" />
+</dataset>
\ No newline at end of file
diff --git a/cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB.xml b/cdmlib-services/src/test/resources/eu/etaxonomy/cdm/api/application/FirstDataInserterTest.testBlankDB.xml
new file mode 100644 (file)
index 0000000..2fa290d
--- /dev/null
@@ -0,0 +1,4 @@
+<?xml version='1.0' encoding='UTF-8'?>\r
+<dataset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../service/dataset.xsd">\r
+</dataset>\r
+\r
index 7a90b1cf3891438a9fd7bb2423aa1d5c36e6a4a6..136c15e7e4f2c689ba067b95cadd9061ae5198d0 100644 (file)
@@ -5,11 +5,11 @@
     xmlns:tx="http://www.springframework.org/schema/tx"\r
     xmlns:security="http://www.springframework.org/schema/security"\r
     xsi:schemaLocation="http://www.springframework.org/schema/beans\r
-    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd\r
-    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd\r
-    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd\r
-    http://www.springframework.org/schema/security\r
-    http://www.springframework.org/schema/security/spring-security-3.0.4.xsd">\r
+        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd\r
+        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd\r
+        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd\r
+        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.4.xsd\r
+     ">\r
 \r
     <import resource="classpath:/eu/etaxonomy/cdm/applicationContext-test.xml" />\r
 \r
index 2f731e6aff9c1a95f692579b37b17fbe31a1dae0..5af8ee643244a73a09d5123e2910717b4513ebc7 100644 (file)
@@ -6,7 +6,8 @@
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd\r
-    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
+    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd\r
+    ">
 \r
     <context:property-override location="classpath:override.properties"/>\r
 \r
         </property>\r
     </bean>\r
 \r
+\r
+    <!-- equips a new and empty database with the initial set of meta data and admin user   -->\r
+    <bean id="firstDataInserter" class="eu.etaxonomy.cdm.api.application.FirstDataInserter" />\r
+\r
     <!-- security  -->\r
     <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/>\r
     <bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">\r
index 7f34dcf679652f6fe918798ef3577d9b70366431..6647598c4180a806a40d6e8c3d9e40997c63e425 100644 (file)
@@ -37,7 +37,7 @@ log4j.logger.eu.etaxonomy.cdm.model.common.init = warn
 log4j.logger.eu.etaxonomy.cdm.test.function = info
 log4j.logger.eu.etaxonomy.cdm.test.integration = info
 log4j.logger.eu.etaxonomy.cdm.api.application = warn
-log4j.logger.eu.etaxonomy.cdm.api.service = debug
+log4j.logger.eu.etaxonomy.cdm.api.service = info
 #log4j.logger.eu.etaxonomy.cdm.database.VocabularyStoreImpl = warn
 #
 log4j.logger.eu.etaxonomy.cdm.database.init = warn
@@ -55,6 +55,7 @@ log4j.logger.org.springframework.orm.hibernate3.SessionFactoryUtils = warn
 log4j.logger.org.springframework.orm.hibernate3 = warn
 log4j.logger.org.springframework.FileSystemXmlApplicationContext = warn;
 log4j.logger.org.springframework.core.io.support = warn
+#log4j.logger.org.springframework.context.support = trace
 
 
   ### ***HIBERNATE ************ ###
diff --git a/pom.xml b/pom.xml
index cc4dd91f8e2e9346a3ba0731cedb1b018c6a7617..2855d3456789127eb1947be6ccfcf4bbe4efebd5 100644 (file)
--- a/pom.xml
+++ b/pom.xml
                 <configuration>
                     <source>${java.codelevel}</source>
                     <target>${java.codelevel}</target>
+                    <encoding>UTF-8</encoding>
                 </configuration>
                 <version>2.3.2</version>
             </plugin>
                 <artifactId>activation</artifactId>
                 <version>1.1</version>
             </dependency>
-            <!--dependency>
-                <groupId>javax.xml.bind</groupId>
-                <artifactId>jsr173_api</artifactId>
-                <version>1.0</version>
-                <scope>system</scope>
-                               <systemPath>${java.home}/lib/rt.jar</systemPath>
-            </dependency-->
             <dependency>
                 <groupId>com.sun.xml.bind</groupId>
                 <artifactId>jaxb-impl</artifactId>
                 <artifactId>ojdbc14</artifactId>
                 <version>10.2.0.2</version>
             </dependency>
+            <!--dependency>
+                <groupId>oracle</groupId>
+                <artifactId>ojdbc14</artifactId>
+                <version>9i</version>
+            </dependency>
+            <dependency>
+                <groupId>oracle</groupId>
+                <artifactId>ojdbc14</artifactId>
+                <version>9.2.0.5</version>
+            </dependency-->
             <dependency>
                 <groupId>com.h2database</groupId>
                 <artifactId>h2</artifactId>