Echobase-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
August 2013
- 2 participants
- 23 discussions
20 Aug '13
Author: tchemit
Date: 2013-08-20 08:07:41 +0200 (Tue, 20 Aug 2013)
New Revision: 843
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/843
Log:
refs #3061: Visualisation des donn?\195?\169es spatiales (continue with leaflet, but still in progress)
Added:
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/DisplaySpatialData.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GeoJsonObject.java
trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData-validation.xml
trunk/echobase-ui/src/main/webapp/js/images/
trunk/echobase-ui/src/main/webapp/js/images/layers-2x.png
trunk/echobase-ui/src/main/webapp/js/images/layers.png
trunk/echobase-ui/src/main/webapp/js/images/marker-icon-2x.png
trunk/echobase-ui/src/main/webapp/js/images/marker-icon.png
trunk/echobase-ui/src/main/webapp/js/images/marker-shadow.png
trunk/echobase-ui/src/main/webapp/js/leaflet-src.js
trunk/echobase-ui/src/main/webapp/js/spatial.js
trunk/echobase-ui/src/main/webapp/js/test.js
Removed:
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java
trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml
Modified:
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java
trunk/echobase-ui/src/main/resources/config/struts-spatial.xml
trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml
trunk/echobase-ui/src/main/webapp/WEB-INF/includes/metas.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp
trunk/echobase-ui/src/main/webapp/js/gridHelper.js
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.entities;
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.TopiaReplicationSupport;
import org.nuiton.topia.TopiaTransaction;
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.entities;
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.TopiaSqlSupport;
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.entities;
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.TopiaReplicationSupport;
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.entities;
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import com.google.common.base.Preconditions;
import fr.ifremer.echobase.EchoBaseTechnicalException;
import org.apache.commons.lang3.StringUtils;
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -4,7 +4,7 @@
* #%L
* EchoBase :: Domain
* $Id$
- * $HeadURL:$
+ * $HeadURL$
* %%
* Copyright (C) 2011 - 2013 Ifremer, Codelutin
* %%
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -24,6 +24,7 @@
*/
+import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.references.DataMetadata;
@@ -70,4 +71,12 @@
public Serializable getDataValue() {
return result.getResultValue();
}
+
+ public String getId() {
+ return result.getTopiaId();
+ }
+
+ public Cell getCell() {
+ return result.getCell();
+ }
}
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.entities.spatial;
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.logging.Log;
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.services.service;
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import fr.ifremer.echobase.entities.AbstractTopiaEchoBaseInternalPersistenceContext;
import fr.ifremer.echobase.entities.EchoBaseInternalEntityEnum;
import fr.ifremer.echobase.entities.EchoBaseUserDAO;
Property changes on: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.services.service;
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import fr.ifremer.echobase.entities.EntityModificationLogDAO;
import fr.ifremer.echobase.entities.ImportLogDAO;
import fr.ifremer.echobase.entities.data.CategoryDAO;
Property changes on: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -33,15 +33,10 @@
import com.google.common.collect.Sets;
import fr.ifremer.echobase.EchoBaseFunctions;
import fr.ifremer.echobase.entities.data.Category;
-import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.CellDAO;
-import fr.ifremer.echobase.entities.data.DataAcquisition;
-import fr.ifremer.echobase.entities.data.DataProcessing;
import fr.ifremer.echobase.entities.data.Echotype;
import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.ResultDAO;
-import fr.ifremer.echobase.entities.data.Transect;
-import fr.ifremer.echobase.entities.data.Transit;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.DataMetadata;
import fr.ifremer.echobase.entities.references.Species;
@@ -58,7 +53,6 @@
import org.nuiton.topia.persistence.TopiaEntities;
import org.nuiton.util.TimeLog;
-import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -84,33 +78,34 @@
Decorator<DataMetadata> decorator = service.getDecorator(getLocale(), DataMetadata.class, null);
- addResult(voyage.getPostCell(), result, decorator);
- if (!voyage.isTransitEmpty()) {
+ long s0 = TimeLog.getTime();
- for (Transit transit : voyage.getTransit()) {
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
+ ResultDAO resultDao = getEchoBasePersistenceContext().getResultDAO();
- if (!transit.isTransectEmpty()) {
- for (Transect transect : transit.getTransect()) {
+ // get all cell with spatial points
+ List<CellPoint> voyageCellPoints = dao.getVoyageCellPoints(voyage);
+ int nbCells = voyageCellPoints.size();
+ s0 = TILE_LOG.log(s0, String.format("Get cell points (%s)", nbCells));
- if (!transect.isDataAcquisitionEmpty()) {
+ final Map<String, CellPoint> cellPointById = Maps.uniqueIndex(voyageCellPoints, EchoBaseFunctions.CELL_POINT_CELL_ID_FUNCTION);
- for (DataAcquisition dataAcquisition : transect.getDataAcquisition()) {
+ Set<String> cellIds = Sets.newHashSet(cellPointById.keySet());
+ s0 = TILE_LOG.log(s0, String.format("Get cell points list and map (%s)", nbCells));
- if (!dataAcquisition.isDataProcessingEmpty()) {
- for (DataProcessing dataProcessing : dataAcquisition.getDataProcessing()) {
+ String query = "SELECT DISTINCT(r.dataMetadata) " + resultDao.createSimpleQuery("r") + " WHERE r.cell.id IN :cell";
+ List<DataMetadata> results = resultDao.findAllByQuery(DataMetadata.class,
+ query, Result.PROPERTY_CELL, cellIds);
- addResult(dataProcessing.getCell(), result, decorator);
+ TILE_LOG.log(s0, String.format("Get all matching datametadata (%s)", results.size()));
- }
- }
- }
- }
- }
- }
- }
+ for (DataMetadata dataMetadata : results) {
+ String key = dataMetadata.getTopiaId();
+ String value = decorator.toString(dataMetadata);
+ result.put(key, value);
}
return result;
}
@@ -257,28 +252,28 @@
return speciesPredicate;
}
- protected void addResult(Collection<Cell> cells,
- Map<String, String> result,
- Decorator<DataMetadata> decorator) {
+// protected void addResult(Collection<Cell> cells,
+// Map<String, String> result,
+// Decorator<DataMetadata> decorator) {
+//
+// if (CollectionUtils.isNotEmpty(cells)) {
+// for (Cell cell : cells) {
+// if (!cell.isResultEmpty()) {
+//
+// for (Result result1 : cell.getResult()) {
+//
+// DataMetadata dataMetadata = result1.getDataMetadata();
+// String key = dataMetadata.getTopiaId();
+// if (!result.containsKey(key)) {
+// String value = decorator.toString(dataMetadata);
+// result.put(key, value);
+// }
+// }
+// }
+// }
+// }
+// }
- if (CollectionUtils.isNotEmpty(cells)) {
- for (Cell cell : cells) {
- if (!cell.isResultEmpty()) {
-
- for (Result result1 : cell.getResult()) {
-
- DataMetadata dataMetadata = result1.getDataMetadata();
- String key = dataMetadata.getTopiaId();
- if (!result.containsKey(key)) {
- String value = decorator.toString(dataMetadata);
- result.put(key, value);
- }
- }
- }
- }
- }
- }
-
public boolean isSpatialAware() {
boolean result = getEchoBasePersistenceContext().isSpatialAware();
return result;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -23,7 +23,6 @@
*/
package fr.ifremer.echobase.ui;
-import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.opensymphony.xwork2.ActionContext;
@@ -32,8 +31,6 @@
import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
import fr.ifremer.echobase.persistence.JdbcConfiguration;
import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
-import fr.ifremer.echobase.entities.spatial.SpatialData;
-import fr.ifremer.echobase.ui.actions.spatial.ShowSpatialModel;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -44,7 +41,6 @@
import java.io.Closeable;
import java.io.Serializable;
import java.util.Collection;
-import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@@ -282,29 +278,6 @@
}
}
- public Set<SpatialData> getSpatialData(ShowSpatialModel model) {
- List<ShowSpatialModel> list = get(PROPERTY_SPATIAL_DATA, List.class);
- Set<SpatialData> result = null;
- if (list != null) {
- int i = list.indexOf(model);
- if (i != -1) {
- ShowSpatialModel showSpatialModel = list.get(i);
- result = showSpatialModel.getSpatialData();
- }
- }
-
- return result;
- }
-
- public void setSpatialData(ShowSpatialModel model) {
- List<ShowSpatialModel> list = get(PROPERTY_SPATIAL_DATA, List.class);
- if (list == null) {
- list = Lists.newArrayList();
- set(PROPERTY_SPATIAL_DATA, list);
- }
- list.add(model);
- }
-
protected Map<String, Object> getDynamicData() {
if (store == null) {
store = Maps.newHashMap();
Deleted: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,83 +0,0 @@
-package fr.ifremer.echobase.ui.actions.spatial;
-
-/*
- * #%L
- * EchoBase :: UI
- * $Id$
- * $HeadURL:$
- * %%
- * Copyright (C) 2011 - 2013 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
-import fr.ifremer.echobase.services.service.spatial.SpatialService;
-import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
-
-import java.util.Map;
-
-/**
- * To configure and show spatial datas.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.2
- */
-public class ConfigureShowSpatialData extends EchoBaseActionSupport {
-
- private static final long serialVersionUID = 1L;
-
- protected final ShowSpatialModel model = new ShowSpatialModel();
-
- /** Universe of existing voyages. */
- protected Map<String, String> voyages;
-
- public ShowSpatialModel getModel() {
- return model;
- }
-
- public Map<String, String> getVoyages() {
- return voyages;
- }
-
- @Override
- public String execute() throws Exception {
-
- model.setJdbcUrl(getServiceContext().getWorkgingDbUrl());
- model.setWithSpatial(spatialService.isSpatialAware());
-
- voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
-
- return SUCCESS;
- }
-
- //------------------------------------------------------------------------//
- //-- Injected objects //
- //------------------------------------------------------------------------//
-
- protected transient WorkingDbPersistenceService workingDbPersistenceService;
-
- public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
- this.workingDbPersistenceService = workingDbPersistenceService;
- }
-
- protected transient SpatialService spatialService;
-
- public void setSpatialService(SpatialService spatialService) {
- this.spatialService = spatialService;
- }
-
-}
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/DisplaySpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/DisplaySpatialData.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/DisplaySpatialData.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -0,0 +1,52 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
+
+/**
+ * To display only the spatial data map.
+ * <p/>
+ * This action will be reused to raster spatial data maps.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class DisplaySpatialData extends EchoBaseActionSupport {
+
+ private static final long serialVersionUID = 1L;
+
+ protected final ShowSpatialModel model = new ShowSpatialModel();
+
+ public ShowSpatialModel getModel() {
+ return model;
+ }
+
+ @Override
+ public String execute() throws Exception {
+
+
+ return SUCCESS;
+ }
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/DisplaySpatialData.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GeoJsonObject.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GeoJsonObject.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GeoJsonObject.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -0,0 +1,153 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+import java.io.Serializable;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class GeoJsonObject implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+
+ public static GeoJsonObjectBuilder newBuilder(String type) {
+ return new GeoJsonObjectBuilder(type);
+ }
+
+ public static class GeoJsonObjectBuilder {
+
+ GeoJsonObject result = new GeoJsonObject();
+
+ GeoJsonFeature feature;
+
+ public GeoJsonObjectBuilder(String type) {
+ result.type = type;
+ }
+
+ public GeoJsonObjectBuilder newFeature(String type,
+ String id,
+ String geometryType) {
+ feature = new GeoJsonFeature(type, id);
+ result.features.add(feature);
+ feature.geometry = new GeoJsonGeometry(geometryType);
+ return this;
+ }
+
+ public GeoJsonObjectBuilder addFeatureProperty(String key, Serializable value) {
+ Preconditions.checkNotNull(feature, "No feature (use before newFeature method)");
+ feature.getProperties().put(key, value);
+ return this;
+ }
+
+ public GeoJsonObjectBuilder addFeatureGeometryPoint(double latitude, double longitude) {
+ Preconditions.checkNotNull(feature, "No feature (use before newFeature method)");
+ feature.geometry.coordinates = new double[]{latitude, longitude};
+ return this;
+ }
+
+ public GeoJsonObject flush() {
+ return result;
+ }
+ }
+
+ protected String type;
+
+ protected final List<GeoJsonFeature> features = Lists.newArrayList();
+
+ public String getType() {
+ return type;
+ }
+
+ public List<GeoJsonFeature> getFeatures() {
+ return features;
+ }
+
+ public static class GeoJsonFeature implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ protected String type;
+
+ protected String id;
+
+ protected final Map<String, Serializable> properties =
+ Maps.newLinkedHashMap();
+
+ protected GeoJsonGeometry geometry;
+
+ public GeoJsonFeature(String type, String id) {
+ this.type = type;
+ this.id = id;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public Map<String, Serializable> getProperties() {
+ return properties;
+ }
+
+ public GeoJsonGeometry getGeometry() {
+ return geometry;
+ }
+ }
+
+ public static class GeoJsonGeometry implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ protected String type;
+
+ protected double[] coordinates;
+
+ public GeoJsonGeometry(String type) {
+ this.type = type;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public double[] getCoordinates() {
+ return coordinates;
+ }
+ }
+
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GeoJsonObject.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -23,7 +23,6 @@
* #L%
*/
-import com.google.common.base.Preconditions;
import fr.ifremer.echobase.entities.spatial.SpatialData;
import fr.ifremer.echobase.services.service.spatial.SpatialService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
@@ -31,7 +30,7 @@
import java.util.Set;
/**
- * Otain all dataMetadata used for a given voyage.
+ * Obtain all spatial data used for a given voyage.
*
* @author tchemit <chemit(a)codelutin.com>
* @since 2.2
@@ -42,21 +41,31 @@
protected final ShowSpatialModel model = new ShowSpatialModel();
+ protected GeoJsonObject data;
+
public ShowSpatialModel getModel() {
return model;
}
+ public GeoJsonObject getData() {
+ return data;
+ }
+
@Override
public String execute() throws Exception {
- boolean withSpatial = getModel().isWithSpatial();
- Preconditions.checkArgument(withSpatial, "Database is not spatial aware.");
+ Set<SpatialData> spatialData = spatialService.getSpatialData(model);
- model.setJdbcUrl(getServiceContext().getWorkgingDbUrl());
+ GeoJsonObject.GeoJsonObjectBuilder builder =
+ GeoJsonObject.newBuilder("Feature");
- Set<SpatialData> spatialData = spatialService.getSpatialData(model);
- getModel().setSpatialData(spatialData);
- getModel().setWithData(true);
+ for (SpatialData s : spatialData) {
+ builder.newFeature("Feature", s.getId(), "Point")
+ .addFeatureProperty("name", s.getCell().getName())
+ .addFeatureProperty(s.getDataMetadata().getName(), s.getDataValue())
+ .addFeatureGeometryPoint(s.getLongitude(), s.getLatitude());
+ }
+ data = builder.flush();
return SUCCESS;
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -4,7 +4,7 @@
* #%L
* EchoBase :: UI
* $Id$
- * $HeadURL:$
+ * $HeadURL$
* %%
* Copyright (C) 2011 - 2013 Ifremer, Codelutin
* %%
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -26,13 +26,11 @@
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.entities.spatial.SpatialData;
import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
import fr.ifremer.echobase.services.service.spatial.SpatialService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.util.Map;
-import java.util.Set;
/**
* To configure and show spatial datas.
@@ -62,23 +60,20 @@
voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
model.setJdbcUrl(getServiceContext().getWorkgingDbUrl());
+ model.setWithSpatial(spatialService.isSpatialAware());
}
@Override
public String input() throws Exception {
- model.setWithSpatial(spatialService.isSpatialAware());
-
+// model.setWithSpatial(spatialService.isSpatialAware());
+ model.setWithData(false);
return SUCCESS;
}
@InputConfig(methodName = "input")
@Override
public String execute() throws Exception {
-
- Set<SpatialData> spatialData = spatialService.getSpatialData(model);
-
- getModel().setSpatialData(spatialData);
getModel().setWithData(true);
return SUCCESS;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -45,10 +45,13 @@
protected Set<SpatialData> spatialData;
/**
- * Can we use spatial data ?
+ * Can we use spatial data (means is the database is spatial?).
*/
protected boolean withSpatial;
+ /**
+ * Can we collect spatial data (means is the configuration filled enough ?).
+ */
protected boolean withData;
public boolean isWithSpatial() {
@@ -59,14 +62,6 @@
this.withSpatial = withSpatial;
}
- public Set<SpatialData> getSpatialData() {
- return spatialData;
- }
-
- public void setSpatialData(Set<SpatialData> spatialData) {
- this.spatialData = spatialData;
- }
-
public boolean isWithData() {
return withData;
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,5 +1,28 @@
package fr.ifremer.echobase.ui.interceptors;
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
import com.google.common.base.Preconditions;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/echobase-ui/src/main/resources/config/struts-spatial.xml
===================================================================
--- trunk/echobase-ui/src/main/resources/config/struts-spatial.xml 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/resources/config/struts-spatial.xml 2013-08-20 06:07:41 UTC (rev 843)
@@ -30,16 +30,16 @@
<package name="spatial" extends="logguedAndWithDb" namespace="/spatial">
- <!-- Configure import -->
- <action name="configure"
- class="fr.ifremer.echobase.ui.actions.spatial.ConfigureShowSpatialData">
+ <!-- Configure show spatial data -->
+ <action name="configure" method="input"
+ class="fr.ifremer.echobase.ui.actions.spatial.ShowSpatialData">
<interceptor-ref name="basicStackLogguedWithdb"/>
<result>/WEB-INF/jsp/spatial/showData.jsp</result>
</action>
- <!-- Reconfigure import -->
- <action name="reconfigure"
- class="fr.ifremer.echobase.ui.actions.spatial.ConfigureShowSpatialData">
+ <!-- Reconfigure show spatial data -->
+ <action name="reconfigure" method="input"
+ class="fr.ifremer.echobase.ui.actions.spatial.ShowSpatialData">
<interceptor-ref name="basicStackLogguedWithdb"/>
<result type="redirectAction">
<param name="namespace">/spatial</param>
@@ -54,9 +54,16 @@
<result>/WEB-INF/jsp/spatial/showData.jsp</result>
</action>
- <!-- Get all data of a voyage -->
- <action name="getVoyage*"
- class="fr.ifremer.echobase.ui.actions.spatial.GetVoyage{1}">
+ <!-- display spatial map from the given selected data -->
+ <action name="displaySpatial"
+ class="fr.ifremer.echobase.ui.actions.spatial.DisplaySpatialData">
+ <interceptor-ref name="prepareParamsStackLogguedWithDb"/>
+ <result>/WEB-INF/jsp/spatial/showDataMap.jsp</result>
+ </action>
+
+ <!-- Get json data -->
+ <action name="get*"
+ class="fr.ifremer.echobase.ui.actions.spatial.Get{1}">
<interceptor-ref name="basicStackLogguedWithdb"/>
<result type="json"/>
</action>
Deleted: trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml
===================================================================
--- trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml 2013-08-20 06:07:41 UTC (rev 843)
@@ -1,40 +0,0 @@
-<!--
- #%L
- EchoBase :: UI
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 - 2013 Ifremer, Codelutin
- %%
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
- "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
-<validators>
-
- <field name="model.voyageId">
- <field-validator type="nrequiredstring">
- <message key="echobase.error.showData.voyage.required"/>
- </field-validator>
- </field>
-
- <field name="model.dataMetadataId">
- <field-validator type="nrequiredstring">
- <message key="echobase.error.showData.dataMetadata.required"/>
- </field-validator>
- </field>
-
-
-</validators>
\ No newline at end of file
Copied: trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData-validation.xml (from rev 842, trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml)
===================================================================
--- trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData-validation.xml (rev 0)
+++ trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData-validation.xml 2013-08-20 06:07:41 UTC (rev 843)
@@ -0,0 +1,40 @@
+<!--
+ #%L
+ EchoBase :: UI
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ %%
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
+ "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
+<validators>
+
+ <field name="model.voyageId">
+ <field-validator type="nrequiredstring">
+ <message key="echobase.error.showData.voyage.required"/>
+ </field-validator>
+ </field>
+
+ <field name="model.dataMetadataId">
+ <field-validator type="nrequiredstring">
+ <message key="echobase.error.showData.dataMetadata.required"/>
+ </field-validator>
+ </field>
+
+
+</validators>
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml 2013-08-20 06:07:41 UTC (rev 843)
@@ -36,6 +36,7 @@
<pattern>/exportQuery/confirmDelete*</pattern>
<pattern>/importData/get*</pattern>
<pattern>/spatial/get*</pattern>
+ <pattern>/spatial/displaySpatial*</pattern>
<pattern>/workingDb/confirmDelete*</pattern>
<pattern>/workingDb/get*</pattern>
<!--<pattern>/removeData/confirmDelete*</pattern>-->
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/includes/metas.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/includes/metas.jsp 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/includes/metas.jsp 2013-08-20 06:07:41 UTC (rev 843)
@@ -32,5 +32,5 @@
href="<s:url value='/css/screen.css' />"/>
<link rel="icon" type="image/png"
href="<s:url value='/images/logo_codelutin.png' />"/>
- <sj:head jqueryui="true" jquerytheme="echobase-theme"/>
+ <sj:head jqueryui="true" jquerytheme="echobase-theme" debug="true" compressed="false" />
</head>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp 2013-08-20 06:07:41 UTC (rev 843)
@@ -62,6 +62,21 @@
'<s:property value="model.echotypeId"/>'
);
+ <s:if test="model.withData">
+ jQuery.get(
+ '<s:url action="displaySpatial" namespace="/spatial"/>',
+ {
+ "model.voyageId": '<s:property value="model.voyageId"/>',
+ "model.dataMetadataId": '<s:property value="model.dataMetadataId"/>',
+ "model.speciesId": '<s:property value="model.speciesId"/>',
+ "model.echotypeId": '<s:property value="model.echotypeId"/>'
+ },
+ function (result) {
+
+ // inject result
+ $('#dataPanel').html(result);
+ });
+ </s:if>
});
</script>
@@ -110,7 +125,7 @@
<s:submit action='save' key="echobase.action.save"/>
</li>
<li>
- <s:submit action="showSpatial" key='echobase.action.display'/>
+ <s:submit action="showSpatial" key='echobase.action.display'/>
</li>
</ul>
</div>
@@ -118,18 +133,15 @@
<s:if test="model.withData">
<fieldset>
- <legend>
- <s:text name="echobase.legend.showData.result"/>
- </legend>
- <s:textfield label='%{getText("echobase.common.nbSpatialData")}'
- readonly="true"
- value="%{model.spatialData.size}" requiredLabel="true"/>
+ <legend>
+ <s:text name="echobase.legend.showData.result"/>
+ </legend>
+
+ <div id="dataPanel">
+ <center>Loading...</center>
+ </div>
</fieldset>
-
</s:if>
- <div id="dataPanel">
- <center>DOME!</center>
- </div>
</s:form>
</s:if>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp 2013-08-20 06:07:41 UTC (rev 843)
@@ -24,20 +24,57 @@
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sj" uri="/struts-jquery-tags" %>
+<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" />
+<!--[if lte IE 8]>
+<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.ie.css" />
+<![endif]-->
+
+<sj:head jqueryui="true" jquerytheme="echobase-theme" debug="true" compressed="false" />
+
+<%--<script type="text/javascript"--%>
+ <%--src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>--%>
<script type="text/javascript"
- src="<s:url value='/js/gridHelper.js' />"></script>
+ src="<s:url value='/js/leaflet-src.js' />"></script>
-<s:form namespace="/spatial" method="POST" enctype="multipart/form-data">
+<%--<script type="text/javascript"--%>
+ <%--src="<s:url value='/js/gridHelper.js' />"></script>--%>
- <s:hidden key="model.withData" label=' '/>
- <s:hidden key="model.withSpatial" label=' '/>
- <s:hidden key="model.voyageId" label=' '/>
- <s:hidden key="model.dataMetadataId" label=' '/>
- <s:hidden key="model.categoryId" label=' '/>
+<script type="text/javascript">
-</s:form>
+ jQuery(document).ready(function () {
-<div id="dataPanel">
+ console.info("LL2= "+L);
+ jQuery.getJSON(
+ '<s:url action="getSpatialData" namespace="/spatial"/>',
+ {
+ "model.voyageId": '<s:property value="model.voyageId"/>',
+ "model.dataMetadataId": '<s:property value="model.dataMetadataId"/>',
+ "model.speciesId": '<s:property value="model.speciesId"/>',
+ "model.echotypeId": '<s:property value="model.echotypeId"/>'
+ },
+ function (result) {
+
+ console.info("LL3= "+L);
+
+ // create a map in the "map" div, set the view to a given place and zoom
+ var map = L.map('map').setView([51.505, -0.09], 13);
+
+ // add an OpenStreetMap tile layer
+ L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
+ attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
+ }).addTo(map);
+
+ // get geoJson object
+ var geoJson = result.data;
+
+ // add it to map
+ L.geoJson(geoJson).addTo(map);
+ });
+
+ });
+</script>
+<div id="map">
+Loading...
</div>
Modified: trunk/echobase-ui/src/main/webapp/js/gridHelper.js
===================================================================
--- trunk/echobase-ui/src/main/webapp/js/gridHelper.js 2013-08-15 10:53:16 UTC (rev 842)
+++ trunk/echobase-ui/src/main/webapp/js/gridHelper.js 2013-08-20 06:07:41 UTC (rev 843)
@@ -148,7 +148,7 @@
updateSelectBoxContent: function (url, params, jsonTarget, target, callback) {
- // call url to obtain datas to injetc in target select box
+ // call url to obtain datas to inject in target select box
jQuery.getJSON(url, params, function (result) {
// will contains selectBox html code
Added: trunk/echobase-ui/src/main/webapp/js/images/layers-2x.png
===================================================================
(Binary files differ)
Property changes on: trunk/echobase-ui/src/main/webapp/js/images/layers-2x.png
___________________________________________________________________
Added: svn:mime-type
+ image/png
Added: trunk/echobase-ui/src/main/webapp/js/images/layers.png
===================================================================
(Binary files differ)
Property changes on: trunk/echobase-ui/src/main/webapp/js/images/layers.png
___________________________________________________________________
Added: svn:mime-type
+ image/png
Added: trunk/echobase-ui/src/main/webapp/js/images/marker-icon-2x.png
===================================================================
(Binary files differ)
Property changes on: trunk/echobase-ui/src/main/webapp/js/images/marker-icon-2x.png
___________________________________________________________________
Added: svn:mime-type
+ image/png
Added: trunk/echobase-ui/src/main/webapp/js/images/marker-icon.png
===================================================================
(Binary files differ)
Property changes on: trunk/echobase-ui/src/main/webapp/js/images/marker-icon.png
___________________________________________________________________
Added: svn:mime-type
+ image/png
Added: trunk/echobase-ui/src/main/webapp/js/images/marker-shadow.png
===================================================================
(Binary files differ)
Property changes on: trunk/echobase-ui/src/main/webapp/js/images/marker-shadow.png
___________________________________________________________________
Added: svn:mime-type
+ image/png
Added: trunk/echobase-ui/src/main/webapp/js/leaflet-src.js
===================================================================
--- trunk/echobase-ui/src/main/webapp/js/leaflet-src.js (rev 0)
+++ trunk/echobase-ui/src/main/webapp/js/leaflet-src.js 2013-08-20 06:07:41 UTC (rev 843)
@@ -0,0 +1,8931 @@
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL:$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+/*
+ Leaflet, a JavaScript library for mobile-friendly interactive maps. http://leafletjs.com
+ (c) 2010-2013, Vladimir Agafonkin
+ (c) 2010-2011, CloudMade
+*/
+(function (window, document, undefined) {
+var oldL = window.L,
+ L = {};
+
+L.version = '0.6.4';
+
+// define Leaflet for Node module pattern loaders, including Browserify
+if (typeof module === 'object' && typeof module.exports === 'object') {
+ module.exports = L;
+
+// define Leaflet as an AMD module
+} else if (typeof define === 'function' && define.amd) {
+ define(L);
+}
+
+// define Leaflet as a global L variable, saving the original L to restore later if needed
+
+L.noConflict = function () {
+ window.L = oldL;
+ return this;
+};
+
+window.L = L;
+
+
+/*
+ * L.Util contains various utility functions used throughout Leaflet code.
+ */
+
+L.Util = {
+ extend: function (dest) { // (Object[, Object, ...]) ->
+ var sources = Array.prototype.slice.call(arguments, 1),
+ i, j, len, src;
+
+ for (j = 0, len = sources.length; j < len; j++) {
+ src = sources[j] || {};
+ for (i in src) {
+ if (src.hasOwnProperty(i)) {
+ dest[i] = src[i];
+ }
+ }
+ }
+ return dest;
+ },
+
+ bind: function (fn, obj) { // (Function, Object) -> Function
+ var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : null;
+ return function () {
+ return fn.apply(obj, args || arguments);
+ };
+ },
+
+ stamp: (function () {
+ var lastId = 0,
+ key = '_leaflet_id';
+ return function (obj) {
+ obj[key] = obj[key] || ++lastId;
+ return obj[key];
+ };
+ }()),
+
+ invokeEach: function (obj, method, context) {
+ var i, args;
+
+ if (typeof obj === 'object') {
+ args = Array.prototype.slice.call(arguments, 3);
+
+ for (i in obj) {
+ method.apply(context, [i, obj[i]].concat(args));
+ }
+ return true;
+ }
+
+ return false;
+ },
+
+ limitExecByInterval: function (fn, time, context) {
+ var lock, execOnUnlock;
+
+ return function wrapperFn() {
+ var args = arguments;
+
+ if (lock) {
+ execOnUnlock = true;
+ return;
+ }
+
+ lock = true;
+
+ setTimeout(function () {
+ lock = false;
+
+ if (execOnUnlock) {
+ wrapperFn.apply(context, args);
+ execOnUnlock = false;
+ }
+ }, time);
+
+ fn.apply(context, args);
+ };
+ },
+
+ falseFn: function () {
+ return false;
+ },
+
+ formatNum: function (num, digits) {
+ var pow = Math.pow(10, digits || 5);
+ return Math.round(num * pow) / pow;
+ },
+
+ trim: function (str) {
+ return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
+ },
+
+ splitWords: function (str) {
+ return L.Util.trim(str).split(/\s+/);
+ },
+
+ setOptions: function (obj, options) {
+ obj.options = L.extend({}, obj.options, options);
+ return obj.options;
+ },
+
+ getParamString: function (obj, existingUrl, uppercase) {
+ var params = [];
+ for (var i in obj) {
+ params.push(encodeURIComponent(uppercase ? i.toUpperCase() : i) + '=' + encodeURIComponent(obj[i]));
+ }
+ return ((!existingUrl || existingUrl.indexOf('?') === -1) ? '?' : '&') + params.join('&');
+ },
+
+ template: function (str, data) {
+ return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
+ var value = data[key];
+ if (value === undefined) {
+ throw new Error('No value provided for variable ' + str);
+ } else if (typeof value === 'function') {
+ value = value(data);
+ }
+ return value;
+ });
+ },
+
+ isArray: function (obj) {
+ return (Object.prototype.toString.call(obj) === '[object Array]');
+ },
+
+ emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
+};
+
+(function () {
+
+ // inspired by http://paulirish.com/2011/requestanimationframe-for-smart-animating/
+
+ function getPrefixed(name) {
+ var i, fn,
+ prefixes = ['webkit', 'moz', 'o', 'ms'];
+
+ for (i = 0; i < prefixes.length && !fn; i++) {
+ fn = window[prefixes[i] + name];
+ }
+
+ return fn;
+ }
+
+ var lastTime = 0;
+
+ function timeoutDefer(fn) {
+ var time = +new Date(),
+ timeToCall = Math.max(0, 16 - (time - lastTime));
+
+ lastTime = time + timeToCall;
+ return window.setTimeout(fn, timeToCall);
+ }
+
+ var requestFn = window.requestAnimationFrame ||
+ getPrefixed('RequestAnimationFrame') || timeoutDefer;
+
+ var cancelFn = window.cancelAnimationFrame ||
+ getPrefixed('CancelAnimationFrame') ||
+ getPrefixed('CancelRequestAnimationFrame') ||
+ function (id) { window.clearTimeout(id); };
+
+
+ L.Util.requestAnimFrame = function (fn, context, immediate, element) {
+ fn = L.bind(fn, context);
+
+ if (immediate && requestFn === timeoutDefer) {
+ fn();
+ } else {
+ return requestFn.call(window, fn, element);
+ }
+ };
+
+ L.Util.cancelAnimFrame = function (id) {
+ if (id) {
+ cancelFn.call(window, id);
+ }
+ };
+
+}());
+
+// shortcuts for most used utility functions
+L.extend = L.Util.extend;
+L.bind = L.Util.bind;
+L.stamp = L.Util.stamp;
+L.setOptions = L.Util.setOptions;
+
+
+/*
+ * L.Class powers the OOP facilities of the library.
+ * Thanks to John Resig and Dean Edwards for inspiration!
+ */
+
+L.Class = function () {};
+
+L.Class.extend = function (props) {
+
+ // extended class with the new prototype
+ var NewClass = function () {
+
+ // call the constructor
+ if (this.initialize) {
+ this.initialize.apply(this, arguments);
+ }
+
+ // call all constructor hooks
+ if (this._initHooks) {
+ this.callInitHooks();
+ }
+ };
+
+ // instantiate class without calling constructor
+ var F = function () {};
+ F.prototype = this.prototype;
+
+ var proto = new F();
+ proto.constructor = NewClass;
+
+ NewClass.prototype = proto;
+
+ //inherit parent's statics
+ for (var i in this) {
+ if (this.hasOwnProperty(i) && i !== 'prototype') {
+ NewClass[i] = this[i];
+ }
+ }
+
+ // mix static properties into the class
+ if (props.statics) {
+ L.extend(NewClass, props.statics);
+ delete props.statics;
+ }
+
+ // mix includes into the prototype
+ if (props.includes) {
+ L.Util.extend.apply(null, [proto].concat(props.includes));
+ delete props.includes;
+ }
+
+ // merge options
+ if (props.options && proto.options) {
+ props.options = L.extend({}, proto.options, props.options);
+ }
+
+ // mix given properties into the prototype
+ L.extend(proto, props);
+
+ proto._initHooks = [];
+
+ var parent = this;
+ // jshint camelcase: false
+ NewClass.__super__ = parent.prototype;
+
+ // add method for calling all hooks
+ proto.callInitHooks = function () {
+
+ if (this._initHooksCalled) { return; }
+
+ if (parent.prototype.callInitHooks) {
+ parent.prototype.callInitHooks.call(this);
+ }
+
+ this._initHooksCalled = true;
+
+ for (var i = 0, len = proto._initHooks.length; i < len; i++) {
+ proto._initHooks[i].call(this);
+ }
+ };
+
+ return NewClass;
+};
+
+
+// method for adding properties to prototype
+L.Class.include = function (props) {
+ L.extend(this.prototype, props);
+};
+
+// merge new default options to the Class
+L.Class.mergeOptions = function (options) {
+ L.extend(this.prototype.options, options);
+};
+
+// add a constructor hook
+L.Class.addInitHook = function (fn) { // (Function) || (String, args...)
+ var args = Array.prototype.slice.call(arguments, 1);
+
+ var init = typeof fn === 'function' ? fn : function () {
+ this[fn].apply(this, args);
+ };
+
+ this.prototype._initHooks = this.prototype._initHooks || [];
+ this.prototype._initHooks.push(init);
+};
+
+
+/*
+ * L.Mixin.Events is used to add custom events functionality to Leaflet classes.
+ */
+
+var eventsKey = '_leaflet_events';
+
+L.Mixin = {};
+
+L.Mixin.Events = {
+
+ addEventListener: function (types, fn, context) { // (String, Function[, Object]) or (Object[, Object])
+
+ // types can be a map of types/handlers
+ if (L.Util.invokeEach(types, this.addEventListener, this, fn, context)) { return this; }
+
+ var events = this[eventsKey] = this[eventsKey] || {},
+ contextId = context && L.stamp(context),
+ i, len, event, type, indexKey, indexLenKey, typeIndex;
+
+ // types can be a string of space-separated words
+ types = L.Util.splitWords(types);
+
+ for (i = 0, len = types.length; i < len; i++) {
+ event = {
+ action: fn,
+ context: context || this
+ };
+ type = types[i];
+
+ if (context) {
+ // store listeners of a particular context in a separate hash (if it has an id)
+ // gives a major performance boost when removing thousands of map layers
+
+ indexKey = type + '_idx';
+ indexLenKey = indexKey + '_len';
+
+ typeIndex = events[indexKey] = events[indexKey] || {};
+
+ if (!typeIndex[contextId]) {
+ typeIndex[contextId] = [];
+
+ // keep track of the number of keys in the index to quickly check if it's empty
+ events[indexLenKey] = (events[indexLenKey] || 0) + 1;
+ }
+
+ typeIndex[contextId].push(event);
+
+
+ } else {
+ events[type] = events[type] || [];
+ events[type].push(event);
+ }
+ }
+
+ return this;
+ },
+
+ hasEventListeners: function (type) { // (String) -> Boolean
+ var events = this[eventsKey];
+ return !!events && ((type in events && events[type].length > 0) ||
+ (type + '_idx' in events && events[type + '_idx_len'] > 0));
+ },
+
+ removeEventListener: function (types, fn, context) { // ([String, Function, Object]) or (Object[, Object])
+
+ if (!this[eventsKey]) {
+ return this;
+ }
+
+ if (!types) {
+ return this.clearAllEventListeners();
+ }
+
+ if (L.Util.invokeEach(types, this.removeEventListener, this, fn, context)) { return this; }
+
+ var events = this[eventsKey],
+ contextId = context && L.stamp(context),
+ i, len, type, listeners, j, indexKey, indexLenKey, typeIndex, removed;
+
+ types = L.Util.splitWords(types);
+
+ for (i = 0, len = types.length; i < len; i++) {
+ type = types[i];
+ indexKey = type + '_idx';
+ indexLenKey = indexKey + '_len';
+
+ typeIndex = events[indexKey];
+
+ if (!fn) {
+ // clear all listeners for a type if function isn't specified
+ delete events[type];
+ delete events[indexKey];
+
+ } else {
+ listeners = context && typeIndex ? typeIndex[contextId] : events[type];
+
+ if (listeners) {
+ for (j = listeners.length - 1; j >= 0; j--) {
+ if ((listeners[j].action === fn) && (!context || (listeners[j].context === context))) {
+ removed = listeners.splice(j, 1);
+ // set the old action to a no-op, because it is possible
+ // that the listener is being iterated over as part of a dispatch
+ removed[0].action = L.Util.falseFn;
+ }
+ }
+
+ if (context && typeIndex && (listeners.length === 0)) {
+ delete typeIndex[contextId];
+ events[indexLenKey]--;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ clearAllEventListeners: function () {
+ delete this[eventsKey];
+ return this;
+ },
+
+ fireEvent: function (type, data) { // (String[, Object])
+ if (!this.hasEventListeners(type)) {
+ return this;
+ }
+
+ var event = L.Util.extend({}, data, { type: type, target: this });
+
+ var events = this[eventsKey],
+ listeners, i, len, typeIndex, contextId;
+
+ if (events[type]) {
+ // make sure adding/removing listeners inside other listeners won't cause infinite loop
+ listeners = events[type].slice();
+
+ for (i = 0, len = listeners.length; i < len; i++) {
+ listeners[i].action.call(listeners[i].context || this, event);
+ }
+ }
+
+ // fire event for the context-indexed listeners as well
+ typeIndex = events[type + '_idx'];
+
+ for (contextId in typeIndex) {
+ listeners = typeIndex[contextId].slice();
+
+ if (listeners) {
+ for (i = 0, len = listeners.length; i < len; i++) {
+ listeners[i].action.call(listeners[i].context || this, event);
+ }
+ }
+ }
+
+ return this;
+ },
+
+ addOneTimeEventListener: function (types, fn, context) {
+
+ if (L.Util.invokeEach(types, this.addOneTimeEventListener, this, fn, context)) { return this; }
+
+ var handler = L.bind(function () {
+ this
+ .removeEventListener(types, fn, context)
+ .removeEventListener(types, handler, context);
+ }, this);
+
+ return this
+ .addEventListener(types, fn, context)
+ .addEventListener(types, handler, context);
+ }
+};
+
+L.Mixin.Events.on = L.Mixin.Events.addEventListener;
+L.Mixin.Events.off = L.Mixin.Events.removeEventListener;
+L.Mixin.Events.once = L.Mixin.Events.addOneTimeEventListener;
+L.Mixin.Events.fire = L.Mixin.Events.fireEvent;
+
+
+/*
+ * L.Browser handles different browser and feature detections for internal Leaflet use.
+ */
+
+(function () {
+
+ var ie = !!window.ActiveXObject,
+ ie6 = ie && !window.XMLHttpRequest,
+ ie7 = ie && !document.querySelector,
+ ielt9 = ie && !document.addEventListener,
+
+ // terrible browser detection to work around Safari / iOS / Android browser bugs
+ ua = navigator.userAgent.toLowerCase(),
+ webkit = ua.indexOf('webkit') !== -1,
+ chrome = ua.indexOf('chrome') !== -1,
+ phantomjs = ua.indexOf('phantom') !== -1,
+ android = ua.indexOf('android') !== -1,
+ android23 = ua.search('android [23]') !== -1,
+
+ mobile = typeof orientation !== undefined + '',
+ msTouch = window.navigator && window.navigator.msPointerEnabled &&
+ window.navigator.msMaxTouchPoints,
+ retina = ('devicePixelRatio' in window && window.devicePixelRatio > 1) ||
+ ('matchMedia' in window && window.matchMedia('(min-resolution:144dpi)') &&
+ window.matchMedia('(min-resolution:144dpi)').matches),
+
+ doc = document.documentElement,
+ ie3d = ie && ('transition' in doc.style),
+ webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()),
+ gecko3d = 'MozPerspective' in doc.style,
+ opera3d = 'OTransition' in doc.style,
+ any3d = !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs;
+
+
+ // PhantomJS has 'ontouchstart' in document.documentElement, but doesn't actually support touch.
+ // https://github.com/Leaflet/Leaflet/pull/1434#issuecomment-13843151
+
+ var touch = !window.L_NO_TOUCH && !phantomjs && (function () {
+
+ var startName = 'ontouchstart';
+
+ // IE10+ (We simulate these into touch* events in L.DomEvent and L.DomEvent.MsTouch) or WebKit, etc.
+ if (msTouch || (startName in doc)) {
+ return true;
+ }
+
+ // Firefox/Gecko
+ var div = document.createElement('div'),
+ supported = false;
+
+ if (!div.setAttribute) {
+ return false;
+ }
+ div.setAttribute(startName, 'return;');
+
+ if (typeof div[startName] === 'function') {
+ supported = true;
+ }
+
+ div.removeAttribute(startName);
+ div = null;
+
+ return supported;
+ }());
+
+
+ L.Browser = {
+ ie: ie,
+ ie6: ie6,
+ ie7: ie7,
+ ielt9: ielt9,
+ webkit: webkit,
+
+ android: android,
+ android23: android23,
+
+ chrome: chrome,
+
+ ie3d: ie3d,
+ webkit3d: webkit3d,
+ gecko3d: gecko3d,
+ opera3d: opera3d,
+ any3d: any3d,
+
+ mobile: mobile,
+ mobileWebkit: mobile && webkit,
+ mobileWebkit3d: mobile && webkit3d,
+ mobileOpera: mobile && window.opera,
+
+ touch: touch,
+ msTouch: msTouch,
+
+ retina: retina
+ };
+
+}());
+
+
+/*
+ * L.Point represents a point with x and y coordinates.
+ */
+
+L.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
+ this.x = (round ? Math.round(x) : x);
+ this.y = (round ? Math.round(y) : y);
+};
+
+L.Point.prototype = {
+
+ clone: function () {
+ return new L.Point(this.x, this.y);
+ },
+
+ // non-destructive, returns a new point
+ add: function (point) {
+ return this.clone()._add(L.point(point));
+ },
+
+ // destructive, used directly for performance in situations where it's safe to modify existing point
+ _add: function (point) {
+ this.x += point.x;
+ this.y += point.y;
+ return this;
+ },
+
+ subtract: function (point) {
+ return this.clone()._subtract(L.point(point));
+ },
+
+ _subtract: function (point) {
+ this.x -= point.x;
+ this.y -= point.y;
+ return this;
+ },
+
+ divideBy: function (num) {
+ return this.clone()._divideBy(num);
+ },
+
+ _divideBy: function (num) {
+ this.x /= num;
+ this.y /= num;
+ return this;
+ },
+
+ multiplyBy: function (num) {
+ return this.clone()._multiplyBy(num);
+ },
+
+ _multiplyBy: function (num) {
+ this.x *= num;
+ this.y *= num;
+ return this;
+ },
+
+ round: function () {
+ return this.clone()._round();
+ },
+
+ _round: function () {
+ this.x = Math.round(this.x);
+ this.y = Math.round(this.y);
+ return this;
+ },
+
+ floor: function () {
+ return this.clone()._floor();
+ },
+
+ _floor: function () {
+ this.x = Math.floor(this.x);
+ this.y = Math.floor(this.y);
+ return this;
+ },
+
+ distanceTo: function (point) {
+ point = L.point(point);
+
+ var x = point.x - this.x,
+ y = point.y - this.y;
+
+ return Math.sqrt(x * x + y * y);
+ },
+
+ equals: function (point) {
+ point = L.point(point);
+
+ return point.x === this.x &&
+ point.y === this.y;
+ },
+
+ contains: function (point) {
+ point = L.point(point);
+
+ return Math.abs(point.x) <= Math.abs(this.x) &&
+ Math.abs(point.y) <= Math.abs(this.y);
+ },
+
+ toString: function () {
+ return 'Point(' +
+ L.Util.formatNum(this.x) + ', ' +
+ L.Util.formatNum(this.y) + ')';
+ }
+};
+
+L.point = function (x, y, round) {
+ if (x instanceof L.Point) {
+ return x;
+ }
+ if (L.Util.isArray(x)) {
+ return new L.Point(x[0], x[1]);
+ }
+ if (x === undefined || x === null) {
+ return x;
+ }
+ return new L.Point(x, y, round);
+};
+
+
+/*
+ * L.Bounds represents a rectangular area on the screen in pixel coordinates.
+ */
+
+L.Bounds = function (a, b) { //(Point, Point) or Point[]
+ if (!a) { return; }
+
+ var points = b ? [a, b] : a;
+
+ for (var i = 0, len = points.length; i < len; i++) {
+ this.extend(points[i]);
+ }
+};
+
+L.Bounds.prototype = {
+ // extend the bounds to contain the given point
+ extend: function (point) { // (Point)
+ point = L.point(point);
+
+ if (!this.min && !this.max) {
+ this.min = point.clone();
+ this.max = point.clone();
+ } else {
+ this.min.x = Math.min(point.x, this.min.x);
+ this.max.x = Math.max(point.x, this.max.x);
+ this.min.y = Math.min(point.y, this.min.y);
+ this.max.y = Math.max(point.y, this.max.y);
+ }
+ return this;
+ },
+
+ getCenter: function (round) { // (Boolean) -> Point
+ return new L.Point(
+ (this.min.x + this.max.x) / 2,
+ (this.min.y + this.max.y) / 2, round);
+ },
+
+ getBottomLeft: function () { // -> Point
+ return new L.Point(this.min.x, this.max.y);
+ },
+
+ getTopRight: function () { // -> Point
+ return new L.Point(this.max.x, this.min.y);
+ },
+
+ getSize: function () {
+ return this.max.subtract(this.min);
+ },
+
+ contains: function (obj) { // (Bounds) or (Point) -> Boolean
+ var min, max;
+
+ if (typeof obj[0] === 'number' || obj instanceof L.Point) {
+ obj = L.point(obj);
+ } else {
+ obj = L.bounds(obj);
+ }
+
+ if (obj instanceof L.Bounds) {
+ min = obj.min;
+ max = obj.max;
+ } else {
+ min = max = obj;
+ }
+
+ return (min.x >= this.min.x) &&
+ (max.x <= this.max.x) &&
+ (min.y >= this.min.y) &&
+ (max.y <= this.max.y);
+ },
+
+ intersects: function (bounds) { // (Bounds) -> Boolean
+ bounds = L.bounds(bounds);
+
+ var min = this.min,
+ max = this.max,
+ min2 = bounds.min,
+ max2 = bounds.max,
+ xIntersects = (max2.x >= min.x) && (min2.x <= max.x),
+ yIntersects = (max2.y >= min.y) && (min2.y <= max.y);
+
+ return xIntersects && yIntersects;
+ },
+
+ isValid: function () {
+ return !!(this.min && this.max);
+ }
+};
+
+L.bounds = function (a, b) { // (Bounds) or (Point, Point) or (Point[])
+ if (!a || a instanceof L.Bounds) {
+ return a;
+ }
+ return new L.Bounds(a, b);
+};
+
+
+/*
+ * L.Transformation is an utility class to perform simple point transformations through a 2d-matrix.
+ */
+
+L.Transformation = function (a, b, c, d) {
+ this._a = a;
+ this._b = b;
+ this._c = c;
+ this._d = d;
+};
+
+L.Transformation.prototype = {
+ transform: function (point, scale) { // (Point, Number) -> Point
+ return this._transform(point.clone(), scale);
+ },
+
+ // destructive transform (faster)
+ _transform: function (point, scale) {
+ scale = scale || 1;
+ point.x = scale * (this._a * point.x + this._b);
+ point.y = scale * (this._c * point.y + this._d);
+ return point;
+ },
+
+ untransform: function (point, scale) {
+ scale = scale || 1;
+ return new L.Point(
+ (point.x / scale - this._b) / this._a,
+ (point.y / scale - this._d) / this._c);
+ }
+};
+
+
+/*
+ * L.DomUtil contains various utility functions for working with DOM.
+ */
+
+L.DomUtil = {
+ get: function (id) {
+ return (typeof id === 'string' ? document.getElementById(id) : id);
+ },
+
+ getStyle: function (el, style) {
+
+ var value = el.style[style];
+
+ if (!value && el.currentStyle) {
+ value = el.currentStyle[style];
+ }
+
+ if ((!value || value === 'auto') && document.defaultView) {
+ var css = document.defaultView.getComputedStyle(el, null);
+ value = css ? css[style] : null;
+ }
+
+ return value === 'auto' ? null : value;
+ },
+
+ getViewportOffset: function (element) {
+
+ var top = 0,
+ left = 0,
+ el = element,
+ docBody = document.body,
+ docEl = document.documentElement,
+ pos,
+ ie7 = L.Browser.ie7;
+
+ do {
+ top += el.offsetTop || 0;
+ left += el.offsetLeft || 0;
+
+ //add borders
+ top += parseInt(L.DomUtil.getStyle(el, 'borderTopWidth'), 10) || 0;
+ left += parseInt(L.DomUtil.getStyle(el, 'borderLeftWidth'), 10) || 0;
+
+ pos = L.DomUtil.getStyle(el, 'position');
+
+ if (el.offsetParent === docBody && pos === 'absolute') { break; }
+
+ if (pos === 'fixed') {
+ top += docBody.scrollTop || docEl.scrollTop || 0;
+ left += docBody.scrollLeft || docEl.scrollLeft || 0;
+ break;
+ }
+
+ if (pos === 'relative' && !el.offsetLeft) {
+ var width = L.DomUtil.getStyle(el, 'width'),
+ maxWidth = L.DomUtil.getStyle(el, 'max-width'),
+ r = el.getBoundingClientRect();
+
+ if (width !== 'none' || maxWidth !== 'none') {
+ left += r.left + el.clientLeft;
+ }
+
+ //calculate full y offset since we're breaking out of the loop
+ top += r.top + (docBody.scrollTop || docEl.scrollTop || 0);
+
+ break;
+ }
+
+ el = el.offsetParent;
+
+ } while (el);
+
+ el = element;
+
+ do {
+ if (el === docBody) { break; }
+
+ top -= el.scrollTop || 0;
+ left -= el.scrollLeft || 0;
+
+ // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
+ // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/…
+ if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
+ left += el.scrollWidth - el.clientWidth;
+
+ // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
+ // need to add it back in if it is visible; scrollbar is on the left as we are RTL
+ if (ie7 && L.DomUtil.getStyle(el, 'overflow-y') !== 'hidden' &&
+ L.DomUtil.getStyle(el, 'overflow') !== 'hidden') {
+ left += 17;
+ }
+ }
+
+ el = el.parentNode;
+ } while (el);
+
+ return new L.Point(left, top);
+ },
+
+ documentIsLtr: function () {
+ if (!L.DomUtil._docIsLtrCached) {
+ L.DomUtil._docIsLtrCached = true;
+ L.DomUtil._docIsLtr = L.DomUtil.getStyle(document.body, 'direction') === 'ltr';
+ }
+ return L.DomUtil._docIsLtr;
+ },
+
+ create: function (tagName, className, container) {
+
+ var el = document.createElement(tagName);
+ el.className = className;
+
+ if (container) {
+ container.appendChild(el);
+ }
+
+ return el;
+ },
+
+ hasClass: function (el, name) {
+ return (el.className.length > 0) &&
+ new RegExp('(^|\\s)' + name + '(\\s|$)').test(el.className);
+ },
+
+ addClass: function (el, name) {
+ if (!L.DomUtil.hasClass(el, name)) {
+ el.className += (el.className ? ' ' : '') + name;
+ }
+ },
+
+ removeClass: function (el, name) {
+ el.className = L.Util.trim((' ' + el.className + ' ').replace(' ' + name + ' ', ' '));
+ },
+
+ setOpacity: function (el, value) {
+
+ if ('opacity' in el.style) {
+ el.style.opacity = value;
+
+ } else if ('filter' in el.style) {
+
+ var filter = false,
+ filterName = 'DXImageTransform.Microsoft.Alpha';
+
+ // filters collection throws an error if we try to retrieve a filter that doesn't exist
+ try {
+ filter = el.filters.item(filterName);
+ } catch (e) {
+ // don't set opacity to 1 if we haven't already set an opacity,
+ // it isn't needed and breaks transparent pngs.
+ if (value === 1) { return; }
+ }
+
+ value = Math.round(value * 100);
+
+ if (filter) {
+ filter.Enabled = (value !== 100);
+ filter.Opacity = value;
+ } else {
+ el.style.filter += ' progid:' + filterName + '(opacity=' + value + ')';
+ }
+ }
+ },
+
+ testProp: function (props) {
+
+ var style = document.documentElement.style;
+
+ for (var i = 0; i < props.length; i++) {
+ if (props[i] in style) {
+ return props[i];
+ }
+ }
+ return false;
+ },
+
+ getTranslateString: function (point) {
+ // on WebKit browsers (Chrome/Safari/iOS Safari/Android) using translate3d instead of translate
+ // makes animation smoother as it ensures HW accel is used. Firefox 13 doesn't care
+ // (same speed either way), Opera 12 doesn't support translate3d
+
+ var is3d = L.Browser.webkit3d,
+ open = 'translate' + (is3d ? '3d' : '') + '(',
+ close = (is3d ? ',0' : '') + ')';
+
+ return open + point.x + 'px,' + point.y + 'px' + close;
+ },
+
+ getScaleString: function (scale, origin) {
+
+ var preTranslateStr = L.DomUtil.getTranslateString(origin.add(origin.multiplyBy(-1 * scale))),
+ scaleStr = ' scale(' + scale + ') ';
+
+ return preTranslateStr + scaleStr;
+ },
+
+ setPosition: function (el, point, disable3D) { // (HTMLElement, Point[, Boolean])
+
+ // jshint camelcase: false
+ el._leaflet_pos = point;
+
+ if (!disable3D && L.Browser.any3d) {
+ el.style[L.DomUtil.TRANSFORM] = L.DomUtil.getTranslateString(point);
+
+ // workaround for Android 2/3 stability (https://github.com/CloudMade/Leaflet/issues/69)
+ if (L.Browser.mobileWebkit3d) {
+ el.style.WebkitBackfaceVisibility = 'hidden';
+ }
+ } else {
+ el.style.left = point.x + 'px';
+ el.style.top = point.y + 'px';
+ }
+ },
+
+ getPosition: function (el) {
+ // this method is only used for elements previously positioned using setPosition,
+ // so it's safe to cache the position for performance
+
+ // jshint camelcase: false
+ return el._leaflet_pos;
+ }
+};
+
+
+// prefix style property names
+
+L.DomUtil.TRANSFORM = L.DomUtil.testProp(
+ ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']);
+
+// webkitTransition comes first because some browser versions that drop vendor prefix don't do
+// the same for the transitionend event, in particular the Android 4.1 stock browser
+
+L.DomUtil.TRANSITION = L.DomUtil.testProp(
+ ['webkitTransition', 'transition', 'OTransition', 'MozTransition', 'msTransition']);
+
+L.DomUtil.TRANSITION_END =
+ L.DomUtil.TRANSITION === 'webkitTransition' || L.DomUtil.TRANSITION === 'OTransition' ?
+ L.DomUtil.TRANSITION + 'End' : 'transitionend';
+
+(function () {
+ var userSelectProperty = L.DomUtil.testProp(
+ ['userSelect', 'WebkitUserSelect', 'OUserSelect', 'MozUserSelect', 'msUserSelect']);
+
+ L.extend(L.DomUtil, {
+ disableTextSelection: function () {
+ L.DomEvent.on(window, 'selectstart', L.DomEvent.preventDefault);
+ if (userSelectProperty) {
+ var style = document.documentElement.style;
+ this._userSelect = style[userSelectProperty];
+ style[userSelectProperty] = 'none';
+ }
+ },
+
+ enableTextSelection: function () {
+ L.DomEvent.off(window, 'selectstart', L.DomEvent.preventDefault);
+ if (userSelectProperty) {
+ document.documentElement.style[userSelectProperty] = this._userSelect;
+ delete this._userSelect;
+ }
+ },
+
+ disableImageDrag: function () {
+ L.DomEvent.on(window, 'dragstart', L.DomEvent.preventDefault);
+ },
+
+ enableImageDrag: function () {
+ L.DomEvent.off(window, 'dragstart', L.DomEvent.preventDefault);
+ }
+ });
+})();
+
+
+/*
+ * L.LatLng represents a geographical point with latitude and longitude coordinates.
+ */
+
+L.LatLng = function (rawLat, rawLng) { // (Number, Number)
+ var lat = parseFloat(rawLat),
+ lng = parseFloat(rawLng);
+
+ if (isNaN(lat) || isNaN(lng)) {
+ throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
+ }
+
+ this.lat = lat;
+ this.lng = lng;
+};
+
+L.extend(L.LatLng, {
+ DEG_TO_RAD: Math.PI / 180,
+ RAD_TO_DEG: 180 / Math.PI,
+ MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
+});
+
+L.LatLng.prototype = {
+ equals: function (obj) { // (LatLng) -> Boolean
+ if (!obj) { return false; }
+
+ obj = L.latLng(obj);
+
+ var margin = Math.max(
+ Math.abs(this.lat - obj.lat),
+ Math.abs(this.lng - obj.lng));
+
+ return margin <= L.LatLng.MAX_MARGIN;
+ },
+
+ toString: function (precision) { // (Number) -> String
+ return 'LatLng(' +
+ L.Util.formatNum(this.lat, precision) + ', ' +
+ L.Util.formatNum(this.lng, precision) + ')';
+ },
+
+ // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
+ // TODO move to projection code, LatLng shouldn't know about Earth
+ distanceTo: function (other) { // (LatLng) -> Number
+ other = L.latLng(other);
+
+ var R = 6378137, // earth radius in meters
+ d2r = L.LatLng.DEG_TO_RAD,
+ dLat = (other.lat - this.lat) * d2r,
+ dLon = (other.lng - this.lng) * d2r,
+ lat1 = this.lat * d2r,
+ lat2 = other.lat * d2r,
+ sin1 = Math.sin(dLat / 2),
+ sin2 = Math.sin(dLon / 2);
+
+ var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
+
+ return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+ },
+
+ wrap: function (a, b) { // (Number, Number) -> LatLng
+ var lng = this.lng;
+
+ a = a || -180;
+ b = b || 180;
+
+ lng = (lng + b) % (b - a) + (lng < a || lng === b ? b : a);
+
+ return new L.LatLng(this.lat, lng);
+ }
+};
+
+L.latLng = function (a, b) { // (LatLng) or ([Number, Number]) or (Number, Number)
+ if (a instanceof L.LatLng) {
+ return a;
+ }
+ if (L.Util.isArray(a)) {
+ return new L.LatLng(a[0], a[1]);
+ }
+ if (a === undefined || a === null) {
+ return a;
+ }
+ if (typeof a === 'object' && 'lat' in a) {
+ return new L.LatLng(a.lat, 'lng' in a ? a.lng : a.lon);
+ }
+ return new L.LatLng(a, b);
+};
+
+
+
+/*
+ * L.LatLngBounds represents a rectangular area on the map in geographical coordinates.
+ */
+
+L.LatLngBounds = function (southWest, northEast) { // (LatLng, LatLng) or (LatLng[])
+ if (!southWest) { return; }
+
+ var latlngs = northEast ? [southWest, northEast] : southWest;
+
+ for (var i = 0, len = latlngs.length; i < len; i++) {
+ this.extend(latlngs[i]);
+ }
+};
+
+L.LatLngBounds.prototype = {
+ // extend the bounds to contain the given point or bounds
+ extend: function (obj) { // (LatLng) or (LatLngBounds)
+ if (!obj) { return this; }
+
+ if (typeof obj[0] === 'number' || typeof obj[0] === 'string' || obj instanceof L.LatLng) {
+ obj = L.latLng(obj);
+ } else {
+ obj = L.latLngBounds(obj);
+ }
+
+ if (obj instanceof L.LatLng) {
+ if (!this._southWest && !this._northEast) {
+ this._southWest = new L.LatLng(obj.lat, obj.lng);
+ this._northEast = new L.LatLng(obj.lat, obj.lng);
+ } else {
+ this._southWest.lat = Math.min(obj.lat, this._southWest.lat);
+ this._southWest.lng = Math.min(obj.lng, this._southWest.lng);
+
+ this._northEast.lat = Math.max(obj.lat, this._northEast.lat);
+ this._northEast.lng = Math.max(obj.lng, this._northEast.lng);
+ }
+ } else if (obj instanceof L.LatLngBounds) {
+ this.extend(obj._southWest);
+ this.extend(obj._northEast);
+ }
+ return this;
+ },
+
+ // extend the bounds by a percentage
+ pad: function (bufferRatio) { // (Number) -> LatLngBounds
+ var sw = this._southWest,
+ ne = this._northEast,
+ heightBuffer = Math.abs(sw.lat - ne.lat) * bufferRatio,
+ widthBuffer = Math.abs(sw.lng - ne.lng) * bufferRatio;
+
+ return new L.LatLngBounds(
+ new L.LatLng(sw.lat - heightBuffer, sw.lng - widthBuffer),
+ new L.LatLng(ne.lat + heightBuffer, ne.lng + widthBuffer));
+ },
+
+ getCenter: function () { // -> LatLng
+ return new L.LatLng(
+ (this._southWest.lat + this._northEast.lat) / 2,
+ (this._southWest.lng + this._northEast.lng) / 2);
+ },
+
+ getSouthWest: function () {
+ return this._southWest;
+ },
+
+ getNorthEast: function () {
+ return this._northEast;
+ },
+
+ getNorthWest: function () {
+ return new L.LatLng(this.getNorth(), this.getWest());
+ },
+
+ getSouthEast: function () {
+ return new L.LatLng(this.getSouth(), this.getEast());
+ },
+
+ getWest: function () {
+ return this._southWest.lng;
+ },
+
+ getSouth: function () {
+ return this._southWest.lat;
+ },
+
+ getEast: function () {
+ return this._northEast.lng;
+ },
+
+ getNorth: function () {
+ return this._northEast.lat;
+ },
+
+ contains: function (obj) { // (LatLngBounds) or (LatLng) -> Boolean
+ if (typeof obj[0] === 'number' || obj instanceof L.LatLng) {
+ obj = L.latLng(obj);
+ } else {
+ obj = L.latLngBounds(obj);
+ }
+
+ var sw = this._southWest,
+ ne = this._northEast,
+ sw2, ne2;
+
+ if (obj instanceof L.LatLngBounds) {
+ sw2 = obj.getSouthWest();
+ ne2 = obj.getNorthEast();
+ } else {
+ sw2 = ne2 = obj;
+ }
+
+ return (sw2.lat >= sw.lat) && (ne2.lat <= ne.lat) &&
+ (sw2.lng >= sw.lng) && (ne2.lng <= ne.lng);
+ },
+
+ intersects: function (bounds) { // (LatLngBounds)
+ bounds = L.latLngBounds(bounds);
+
+ var sw = this._southWest,
+ ne = this._northEast,
+ sw2 = bounds.getSouthWest(),
+ ne2 = bounds.getNorthEast(),
+
+ latIntersects = (ne2.lat >= sw.lat) && (sw2.lat <= ne.lat),
+ lngIntersects = (ne2.lng >= sw.lng) && (sw2.lng <= ne.lng);
+
+ return latIntersects && lngIntersects;
+ },
+
+ toBBoxString: function () {
+ return [this.getWest(), this.getSouth(), this.getEast(), this.getNorth()].join(',');
+ },
+
+ equals: function (bounds) { // (LatLngBounds)
+ if (!bounds) { return false; }
+
+ bounds = L.latLngBounds(bounds);
+
+ return this._southWest.equals(bounds.getSouthWest()) &&
+ this._northEast.equals(bounds.getNorthEast());
+ },
+
+ isValid: function () {
+ return !!(this._southWest && this._northEast);
+ }
+};
+
+//TODO International date line?
+
+L.latLngBounds = function (a, b) { // (LatLngBounds) or (LatLng, LatLng)
+ if (!a || a instanceof L.LatLngBounds) {
+ return a;
+ }
+ return new L.LatLngBounds(a, b);
+};
+
+
+/*
+ * L.Projection contains various geographical projections used by CRS classes.
+ */
+
+L.Projection = {};
+
+
+/*
+ * Spherical Mercator is the most popular map projection, used by EPSG:3857 CRS used by default.
+ */
+
+L.Projection.SphericalMercator = {
+ MAX_LATITUDE: 85.0511287798,
+
+ project: function (latlng) { // (LatLng) -> Point
+ var d = L.LatLng.DEG_TO_RAD,
+ max = this.MAX_LATITUDE,
+ lat = Math.max(Math.min(max, latlng.lat), -max),
+ x = latlng.lng * d,
+ y = lat * d;
+
+ y = Math.log(Math.tan((Math.PI / 4) + (y / 2)));
+
+ return new L.Point(x, y);
+ },
+
+ unproject: function (point) { // (Point, Boolean) -> LatLng
+ var d = L.LatLng.RAD_TO_DEG,
+ lng = point.x * d,
+ lat = (2 * Math.atan(Math.exp(point.y)) - (Math.PI / 2)) * d;
+
+ return new L.LatLng(lat, lng);
+ }
+};
+
+
+/*
+ * Simple equirectangular (Plate Carree) projection, used by CRS like EPSG:4326 and Simple.
+ */
+
+L.Projection.LonLat = {
+ project: function (latlng) {
+ return new L.Point(latlng.lng, latlng.lat);
+ },
+
+ unproject: function (point) {
+ return new L.LatLng(point.y, point.x);
+ }
+};
+
+
+/*
+ * L.CRS is a base object for all defined CRS (Coordinate Reference Systems) in Leaflet.
+ */
+
+L.CRS = {
+ latLngToPoint: function (latlng, zoom) { // (LatLng, Number) -> Point
+ var projectedPoint = this.projection.project(latlng),
+ scale = this.scale(zoom);
+
+ return this.transformation._transform(projectedPoint, scale);
+ },
+
+ pointToLatLng: function (point, zoom) { // (Point, Number[, Boolean]) -> LatLng
+ var scale = this.scale(zoom),
+ untransformedPoint = this.transformation.untransform(point, scale);
+
+ return this.projection.unproject(untransformedPoint);
+ },
+
+ project: function (latlng) {
+ return this.projection.project(latlng);
+ },
+
+ scale: function (zoom) {
+ return 256 * Math.pow(2, zoom);
+ }
+};
+
+
+/*
+ * A simple CRS that can be used for flat non-Earth maps like panoramas or game maps.
+ */
+
+L.CRS.Simple = L.extend({}, L.CRS, {
+ projection: L.Projection.LonLat,
+ transformation: new L.Transformation(1, 0, -1, 0),
+
+ scale: function (zoom) {
+ return Math.pow(2, zoom);
+ }
+});
+
+
+/*
+ * L.CRS.EPSG3857 (Spherical Mercator) is the most common CRS for web mapping
+ * and is used by Leaflet by default.
+ */
+
+L.CRS.EPSG3857 = L.extend({}, L.CRS, {
+ code: 'EPSG:3857',
+
+ projection: L.Projection.SphericalMercator,
+ transformation: new L.Transformation(0.5 / Math.PI, 0.5, -0.5 / Math.PI, 0.5),
+
+ project: function (latlng) { // (LatLng) -> Point
+ var projectedPoint = this.projection.project(latlng),
+ earthRadius = 6378137;
+ return projectedPoint.multiplyBy(earthRadius);
+ }
+});
+
+L.CRS.EPSG900913 = L.extend({}, L.CRS.EPSG3857, {
+ code: 'EPSG:900913'
+});
+
+
+/*
+ * L.CRS.EPSG4326 is a CRS popular among advanced GIS specialists.
+ */
+
+L.CRS.EPSG4326 = L.extend({}, L.CRS, {
+ code: 'EPSG:4326',
+
+ projection: L.Projection.LonLat,
+ transformation: new L.Transformation(1 / 360, 0.5, -1 / 360, 0.5)
+});
+
+
+/*
+ * L.Map is the central class of the API - it is used to create a map.
+ */
+
+L.Map = L.Class.extend({
+
+ includes: L.Mixin.Events,
+
+ options: {
+ crs: L.CRS.EPSG3857,
+
+ /*
+ center: LatLng,
+ zoom: Number,
+ layers: Array,
+ */
+
+ fadeAnimation: L.DomUtil.TRANSITION && !L.Browser.android23,
+ trackResize: true,
+ markerZoomAnimation: L.DomUtil.TRANSITION && L.Browser.any3d
+ },
+
+ initialize: function (id, options) { // (HTMLElement or String, Object)
+ options = L.setOptions(this, options);
+
+ this._initContainer(id);
+ this._initLayout();
+ this._initEvents();
+
+ if (options.maxBounds) {
+ this.setMaxBounds(options.maxBounds);
+ }
+
+ if (options.center && options.zoom !== undefined) {
+ this.setView(L.latLng(options.center), options.zoom, {reset: true});
+ }
+
+ this._handlers = [];
+
+ this._layers = {};
+ this._zoomBoundLayers = {};
+ this._tileLayersNum = 0;
+
+ this.callInitHooks();
+
+ this._addLayers(options.layers);
+ },
+
+
+ // public methods that modify map state
+
+ // replaced by animation-powered implementation in Map.PanAnimation.js
+ setView: function (center, zoom) {
+ this._resetView(L.latLng(center), this._limitZoom(zoom));
+ return this;
+ },
+
+ setZoom: function (zoom, options) {
+ return this.setView(this.getCenter(), zoom, {zoom: options});
+ },
+
+ zoomIn: function (delta, options) {
+ return this.setZoom(this._zoom + (delta || 1), options);
+ },
+
+ zoomOut: function (delta, options) {
+ return this.setZoom(this._zoom - (delta || 1), options);
+ },
+
+ setZoomAround: function (latlng, zoom, options) {
+ var scale = this.getZoomScale(zoom),
+ viewHalf = this.getSize().divideBy(2),
+ containerPoint = latlng instanceof L.Point ? latlng : this.latLngToContainerPoint(latlng),
+
+ centerOffset = containerPoint.subtract(viewHalf).multiplyBy(1 - 1 / scale),
+ newCenter = this.containerPointToLatLng(viewHalf.add(centerOffset));
+
+ return this.setView(newCenter, zoom, {zoom: options});
+ },
+
+ fitBounds: function (bounds, options) {
+
+ options = options || {};
+ bounds = bounds.getBounds ? bounds.getBounds() : L.latLngBounds(bounds);
+
+ var paddingTL = L.point(options.paddingTopLeft || options.padding || [0, 0]),
+ paddingBR = L.point(options.paddingBottomRight || options.padding || [0, 0]),
+
+ zoom = this.getBoundsZoom(bounds, false, paddingTL.add(paddingBR)),
+ paddingOffset = paddingBR.subtract(paddingTL).divideBy(2),
+
+ swPoint = this.project(bounds.getSouthWest(), zoom),
+ nePoint = this.project(bounds.getNorthEast(), zoom),
+ center = this.unproject(swPoint.add(nePoint).divideBy(2).add(paddingOffset), zoom);
+
+ return this.setView(center, zoom, options);
+ },
+
+ fitWorld: function (options) {
+ return this.fitBounds([[-90, -180], [90, 180]], options);
+ },
+
+ panTo: function (center, options) { // (LatLng)
+ return this.setView(center, this._zoom, {pan: options});
+ },
+
+ panBy: function (offset) { // (Point)
+ // replaced with animated panBy in Map.Animation.js
+ this.fire('movestart');
+
+ this._rawPanBy(L.point(offset));
+
+ this.fire('move');
+ return this.fire('moveend');
+ },
+
+ setMaxBounds: function (bounds, options) {
+ bounds = L.latLngBounds(bounds);
+
+ this.options.maxBounds = bounds;
+
+ if (!bounds) {
+ this._boundsMinZoom = null;
+ this.off('moveend', this._panInsideMaxBounds, this);
+ return this;
+ }
+
+ var minZoom = this.getBoundsZoom(bounds, true);
+
+ this._boundsMinZoom = minZoom;
+
+ if (this._loaded) {
+ if (this._zoom < minZoom) {
+ this.setView(bounds.getCenter(), minZoom, options);
+ } else {
+ this.panInsideBounds(bounds);
+ }
+ }
+
+ this.on('moveend', this._panInsideMaxBounds, this);
+
+ return this;
+ },
+
+ panInsideBounds: function (bounds) {
+ bounds = L.latLngBounds(bounds);
+
+ var viewBounds = this.getPixelBounds(),
+ viewSw = viewBounds.getBottomLeft(),
+ viewNe = viewBounds.getTopRight(),
+ sw = this.project(bounds.getSouthWest()),
+ ne = this.project(bounds.getNorthEast()),
+ dx = 0,
+ dy = 0;
+
+ if (viewNe.y < ne.y) { // north
+ dy = Math.ceil(ne.y - viewNe.y);
+ }
+ if (viewNe.x > ne.x) { // east
+ dx = Math.floor(ne.x - viewNe.x);
+ }
+ if (viewSw.y > sw.y) { // south
+ dy = Math.floor(sw.y - viewSw.y);
+ }
+ if (viewSw.x < sw.x) { // west
+ dx = Math.ceil(sw.x - viewSw.x);
+ }
+
+ if (dx || dy) {
+ return this.panBy([dx, dy]);
+ }
+
+ return this;
+ },
+
+ addLayer: function (layer) {
+ // TODO method is too big, refactor
+
+ var id = L.stamp(layer);
+
+ if (this._layers[id]) { return this; }
+
+ this._layers[id] = layer;
+
+ // TODO getMaxZoom, getMinZoom in ILayer (instead of options)
+ if (layer.options && (!isNaN(layer.options.maxZoom) || !isNaN(layer.options.minZoom))) {
+ this._zoomBoundLayers[id] = layer;
+ this._updateZoomLevels();
+ }
+
+ // TODO looks ugly, refactor!!!
+ if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
+ this._tileLayersNum++;
+ this._tileLayersToLoad++;
+ layer.on('load', this._onTileLayerLoad, this);
+ }
+
+ if (this._loaded) {
+ this._layerAdd(layer);
+ }
+
+ return this;
+ },
+
+ removeLayer: function (layer) {
+ var id = L.stamp(layer);
+
+ if (!this._layers[id]) { return; }
+
+ if (this._loaded) {
+ layer.onRemove(this);
+ }
+
+ delete this._layers[id];
+
+ if (this._loaded) {
+ this.fire('layerremove', {layer: layer});
+ }
+
+ if (this._zoomBoundLayers[id]) {
+ delete this._zoomBoundLayers[id];
+ this._updateZoomLevels();
+ }
+
+ // TODO looks ugly, refactor
+ if (this.options.zoomAnimation && L.TileLayer && (layer instanceof L.TileLayer)) {
+ this._tileLayersNum--;
+ this._tileLayersToLoad--;
+ layer.off('load', this._onTileLayerLoad, this);
+ }
+
+ return this;
+ },
+
+ hasLayer: function (layer) {
+ if (!layer) { return false; }
+
+ return (L.stamp(layer) in this._layers);
+ },
+
+ eachLayer: function (method, context) {
+ for (var i in this._layers) {
+ method.call(context, this._layers[i]);
+ }
+ return this;
+ },
+
+ invalidateSize: function (options) {
+ options = L.extend({
+ animate: false,
+ pan: true
+ }, options === true ? {animate: true} : options);
+
+ var oldSize = this.getSize();
+ this._sizeChanged = true;
+
+ if (this.options.maxBounds) {
+ this.setMaxBounds(this.options.maxBounds);
+ }
+
+ if (!this._loaded) { return this; }
+
+ var newSize = this.getSize(),
+ offset = oldSize.subtract(newSize).divideBy(2).round();
+
+ if (!offset.x && !offset.y) { return this; }
+
+ if (options.animate && options.pan) {
+ this.panBy(offset);
+
+ } else {
+ if (options.pan) {
+ this._rawPanBy(offset);
+ }
+
+ this.fire('move');
+
+ // make sure moveend is not fired too often on resize
+ clearTimeout(this._sizeTimer);
+ this._sizeTimer = setTimeout(L.bind(this.fire, this, 'moveend'), 200);
+ }
+
+ return this.fire('resize', {
+ oldSize: oldSize,
+ newSize: newSize
+ });
+ },
+
+ // TODO handler.addTo
+ addHandler: function (name, HandlerClass) {
+ if (!HandlerClass) { return; }
+
+ var handler = this[name] = new HandlerClass(this);
+
+ this._handlers.push(handler);
+
+ if (this.options[name]) {
+ handler.enable();
+ }
+
+ return this;
+ },
+
+ remove: function () {
+ if (this._loaded) {
+ this.fire('unload');
+ }
+
+ this._initEvents('off');
+
+ delete this._container._leaflet;
+
+ this._clearPanes();
+ if (this._clearControlPos) {
+ this._clearControlPos();
+ }
+
+ this._clearHandlers();
+
+ return this;
+ },
+
+
+ // public methods for getting map state
+
+ getCenter: function () { // (Boolean) -> LatLng
+ this._checkIfLoaded();
+
+ if (!this._moved()) {
+ return this._initialCenter;
+ }
+ return this.layerPointToLatLng(this._getCenterLayerPoint());
+ },
+
+ getZoom: function () {
+ return this._zoom;
+ },
+
+ getBounds: function () {
+ var bounds = this.getPixelBounds(),
+ sw = this.unproject(bounds.getBottomLeft()),
+ ne = this.unproject(bounds.getTopRight());
+
+ return new L.LatLngBounds(sw, ne);
+ },
+
+ getMinZoom: function () {
+ var z1 = this._layersMinZoom === undefined ? 0 : this._layersMinZoom,
+ z2 = this._boundsMinZoom === undefined ? 0 : this._boundsMinZoom;
+ return this.options.minZoom === undefined ? Math.max(z1, z2) : this.options.minZoom;
+ },
+
+ getMaxZoom: function () {
+ return this.options.maxZoom === undefined ?
+ (this._layersMaxZoom === undefined ? Infinity : this._layersMaxZoom) :
+ this.options.maxZoom;
+ },
+
+ getBoundsZoom: function (bounds, inside, padding) { // (LatLngBounds[, Boolean, Point]) -> Number
+ bounds = L.latLngBounds(bounds);
+
+ var zoom = this.getMinZoom() - (inside ? 1 : 0),
+ maxZoom = this.getMaxZoom(),
+ size = this.getSize(),
+
+ nw = bounds.getNorthWest(),
+ se = bounds.getSouthEast(),
+
+ zoomNotFound = true,
+ boundsSize;
+
+ padding = L.point(padding || [0, 0]);
+
+ do {
+ zoom++;
+ boundsSize = this.project(se, zoom).subtract(this.project(nw, zoom)).add(padding);
+ zoomNotFound = !inside ? size.contains(boundsSize) : boundsSize.x < size.x || boundsSize.y < size.y;
+
+ } while (zoomNotFound && zoom <= maxZoom);
+
+ if (zoomNotFound && inside) {
+ return null;
+ }
+
+ return inside ? zoom : zoom - 1;
+ },
+
+ getSize: function () {
+ if (!this._size || this._sizeChanged) {
+ this._size = new L.Point(
+ this._container.clientWidth,
+ this._container.clientHeight);
+
+ this._sizeChanged = false;
+ }
+ return this._size.clone();
+ },
+
+ getPixelBounds: function () {
+ var topLeftPoint = this._getTopLeftPoint();
+ return new L.Bounds(topLeftPoint, topLeftPoint.add(this.getSize()));
+ },
+
+ getPixelOrigin: function () {
+ this._checkIfLoaded();
+ return this._initialTopLeftPoint;
+ },
+
+ getPanes: function () {
+ return this._panes;
+ },
+
+ getContainer: function () {
+ return this._container;
+ },
+
+
+ // TODO replace with universal implementation after refactoring projections
+
+ getZoomScale: function (toZoom) {
+ var crs = this.options.crs;
+ return crs.scale(toZoom) / crs.scale(this._zoom);
+ },
+
+ getScaleZoom: function (scale) {
+ return this._zoom + (Math.log(scale) / Math.LN2);
+ },
+
+
+ // conversion methods
+
+ project: function (latlng, zoom) { // (LatLng[, Number]) -> Point
+ zoom = zoom === undefined ? this._zoom : zoom;
+ return this.options.crs.latLngToPoint(L.latLng(latlng), zoom);
+ },
+
+ unproject: function (point, zoom) { // (Point[, Number]) -> LatLng
+ zoom = zoom === undefined ? this._zoom : zoom;
+ return this.options.crs.pointToLatLng(L.point(point), zoom);
+ },
+
+ layerPointToLatLng: function (point) { // (Point)
+ var projectedPoint = L.point(point).add(this.getPixelOrigin());
+ return this.unproject(projectedPoint);
+ },
+
+ latLngToLayerPoint: function (latlng) { // (LatLng)
+ var projectedPoint = this.project(L.latLng(latlng))._round();
+ return projectedPoint._subtract(this.getPixelOrigin());
+ },
+
+ containerPointToLayerPoint: function (point) { // (Point)
+ return L.point(point).subtract(this._getMapPanePos());
+ },
+
+ layerPointToContainerPoint: function (point) { // (Point)
+ return L.point(point).add(this._getMapPanePos());
+ },
+
+ containerPointToLatLng: function (point) {
+ var layerPoint = this.containerPointToLayerPoint(L.point(point));
+ return this.layerPointToLatLng(layerPoint);
+ },
+
+ latLngToContainerPoint: function (latlng) {
+ return this.layerPointToContainerPoint(this.latLngToLayerPoint(L.latLng(latlng)));
+ },
+
+ mouseEventToContainerPoint: function (e) { // (MouseEvent)
+ return L.DomEvent.getMousePosition(e, this._container);
+ },
+
+ mouseEventToLayerPoint: function (e) { // (MouseEvent)
+ return this.containerPointToLayerPoint(this.mouseEventToContainerPoint(e));
+ },
+
+ mouseEventToLatLng: function (e) { // (MouseEvent)
+ return this.layerPointToLatLng(this.mouseEventToLayerPoint(e));
+ },
+
+
+ // map initialization methods
+
+ _initContainer: function (id) {
+ var container = this._container = L.DomUtil.get(id);
+
+ if (!container) {
+ throw new Error('Map container not found.');
+ } else if (container._leaflet) {
+ throw new Error('Map container is already initialized.');
+ }
+
+ container._leaflet = true;
+ },
+
+ _initLayout: function () {
+ var container = this._container;
+
+ L.DomUtil.addClass(container, 'leaflet-container' +
+ (L.Browser.touch ? ' leaflet-touch' : '') +
+ (L.Browser.retina ? ' leaflet-retina' : '') +
+ (this.options.fadeAnimation ? ' leaflet-fade-anim' : ''));
+
+ var position = L.DomUtil.getStyle(container, 'position');
+
+ if (position !== 'absolute' && position !== 'relative' && position !== 'fixed') {
+ container.style.position = 'relative';
+ }
+
+ this._initPanes();
+
+ if (this._initControlPos) {
+ this._initControlPos();
+ }
+ },
+
+ _initPanes: function () {
+ var panes = this._panes = {};
+
+ this._mapPane = panes.mapPane = this._createPane('leaflet-map-pane', this._container);
+
+ this._tilePane = panes.tilePane = this._createPane('leaflet-tile-pane', this._mapPane);
+ panes.objectsPane = this._createPane('leaflet-objects-pane', this._mapPane);
+ panes.shadowPane = this._createPane('leaflet-shadow-pane');
+ panes.overlayPane = this._createPane('leaflet-overlay-pane');
+ panes.markerPane = this._createPane('leaflet-marker-pane');
+ panes.popupPane = this._createPane('leaflet-popup-pane');
+
+ var zoomHide = ' leaflet-zoom-hide';
+
+ if (!this.options.markerZoomAnimation) {
+ L.DomUtil.addClass(panes.markerPane, zoomHide);
+ L.DomUtil.addClass(panes.shadowPane, zoomHide);
+ L.DomUtil.addClass(panes.popupPane, zoomHide);
+ }
+ },
+
+ _createPane: function (className, container) {
+ return L.DomUtil.create('div', className, container || this._panes.objectsPane);
+ },
+
+ _clearPanes: function () {
+ this._container.removeChild(this._mapPane);
+ },
+
+ _addLayers: function (layers) {
+ layers = layers ? (L.Util.isArray(layers) ? layers : [layers]) : [];
+
+ for (var i = 0, len = layers.length; i < len; i++) {
+ this.addLayer(layers[i]);
+ }
+ },
+
+
+ // private methods that modify map state
+
+ _resetView: function (center, zoom, preserveMapOffset, afterZoomAnim) {
+
+ var zoomChanged = (this._zoom !== zoom);
+
+ if (!afterZoomAnim) {
+ this.fire('movestart');
+
+ if (zoomChanged) {
+ this.fire('zoomstart');
+ }
+ }
+
+ this._zoom = zoom;
+ this._initialCenter = center;
+
+ this._initialTopLeftPoint = this._getNewTopLeftPoint(center);
+
+ if (!preserveMapOffset) {
+ L.DomUtil.setPosition(this._mapPane, new L.Point(0, 0));
+ } else {
+ this._initialTopLeftPoint._add(this._getMapPanePos());
+ }
+
+ this._tileLayersToLoad = this._tileLayersNum;
+
+ var loading = !this._loaded;
+ this._loaded = true;
+
+ if (loading) {
+ this.fire('load');
+ this.eachLayer(this._layerAdd, this);
+ }
+
+ this.fire('viewreset', {hard: !preserveMapOffset});
+
+ this.fire('move');
+
+ if (zoomChanged || afterZoomAnim) {
+ this.fire('zoomend');
+ }
+
+ this.fire('moveend', {hard: !preserveMapOffset});
+ },
+
+ _rawPanBy: function (offset) {
+ L.DomUtil.setPosition(this._mapPane, this._getMapPanePos().subtract(offset));
+ },
+
+ _getZoomSpan: function () {
+ return this.getMaxZoom() - this.getMinZoom();
+ },
+
+ _updateZoomLevels: function () {
+ var i,
+ minZoom = Infinity,
+ maxZoom = -Infinity,
+ oldZoomSpan = this._getZoomSpan();
+
+ for (i in this._zoomBoundLayers) {
+ var layer = this._zoomBoundLayers[i];
+ if (!isNaN(layer.options.minZoom)) {
+ minZoom = Math.min(minZoom, layer.options.minZoom);
+ }
+ if (!isNaN(layer.options.maxZoom)) {
+ maxZoom = Math.max(maxZoom, layer.options.maxZoom);
+ }
+ }
+
+ if (i === undefined) { // we have no tilelayers
+ this._layersMaxZoom = this._layersMinZoom = undefined;
+ } else {
+ this._layersMaxZoom = maxZoom;
+ this._layersMinZoom = minZoom;
+ }
+
+ if (oldZoomSpan !== this._getZoomSpan()) {
+ this.fire('zoomlevelschange');
+ }
+ },
+
+ _panInsideMaxBounds: function () {
+ this.panInsideBounds(this.options.maxBounds);
+ },
+
+ _checkIfLoaded: function () {
+ if (!this._loaded) {
+ throw new Error('Set map center and zoom first.');
+ }
+ },
+
+ // map events
+
+ _initEvents: function (onOff) {
+ if (!L.DomEvent) { return; }
+
+ onOff = onOff || 'on';
+
+ L.DomEvent[onOff](this._container, 'click', this._onMouseClick, this);
+
+ var events = ['dblclick', 'mousedown', 'mouseup', 'mouseenter',
+ 'mouseleave', 'mousemove', 'contextmenu'],
+ i, len;
+
+ for (i = 0, len = events.length; i < len; i++) {
+ L.DomEvent[onOff](this._container, events[i], this._fireMouseEvent, this);
+ }
+
+ if (this.options.trackResize) {
+ L.DomEvent[onOff](window, 'resize', this._onResize, this);
+ }
+ },
+
+ _onResize: function () {
+ L.Util.cancelAnimFrame(this._resizeRequest);
+ this._resizeRequest = L.Util.requestAnimFrame(
+ this.invalidateSize, this, false, this._container);
+ },
+
+ _onMouseClick: function (e) {
+ if (!this._loaded || (!e._simulated && this.dragging && this.dragging.moved()) ||
+ L.DomEvent._skipped(e)) { return; }
+
+ this.fire('preclick');
+ this._fireMouseEvent(e);
+ },
+
+ _fireMouseEvent: function (e) {
+ if (!this._loaded || L.DomEvent._skipped(e)) { return; }
+
+ var type = e.type;
+
+ type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
+
+ if (!this.hasEventListeners(type)) { return; }
+
+ if (type === 'contextmenu') {
+ L.DomEvent.preventDefault(e);
+ }
+
+ var containerPoint = this.mouseEventToContainerPoint(e),
+ layerPoint = this.containerPointToLayerPoint(containerPoint),
+ latlng = this.layerPointToLatLng(layerPoint);
+
+ this.fire(type, {
+ latlng: latlng,
+ layerPoint: layerPoint,
+ containerPoint: containerPoint,
+ originalEvent: e
+ });
+ },
+
+ _onTileLayerLoad: function () {
+ this._tileLayersToLoad--;
+ if (this._tileLayersNum && !this._tileLayersToLoad) {
+ this.fire('tilelayersload');
+ }
+ },
+
+ _clearHandlers: function () {
+ for (var i = 0, len = this._handlers.length; i < len; i++) {
+ this._handlers[i].disable();
+ }
+ },
+
+ whenReady: function (callback, context) {
+ if (this._loaded) {
+ callback.call(context || this, this);
+ } else {
+ this.on('load', callback, context);
+ }
+ return this;
+ },
+
+ _layerAdd: function (layer) {
+ layer.onAdd(this);
+ this.fire('layeradd', {layer: layer});
+ },
+
+
+ // private methods for getting map state
+
+ _getMapPanePos: function () {
+ return L.DomUtil.getPosition(this._mapPane);
+ },
+
+ _moved: function () {
+ var pos = this._getMapPanePos();
+ return pos && !pos.equals([0, 0]);
+ },
+
+ _getTopLeftPoint: function () {
+ return this.getPixelOrigin().subtract(this._getMapPanePos());
+ },
+
+ _getNewTopLeftPoint: function (center, zoom) {
+ var viewHalf = this.getSize()._divideBy(2);
+ // TODO round on display, not calculation to increase precision?
+ return this.project(center, zoom)._subtract(viewHalf)._round();
+ },
+
+ _latLngToNewLayerPoint: function (latlng, newZoom, newCenter) {
+ var topLeft = this._getNewTopLeftPoint(newCenter, newZoom).add(this._getMapPanePos());
+ return this.project(latlng, newZoom)._subtract(topLeft);
+ },
+
+ // layer point of the current center
+ _getCenterLayerPoint: function () {
+ return this.containerPointToLayerPoint(this.getSize()._divideBy(2));
+ },
+
+ // offset of the specified place to the current center in pixels
+ _getCenterOffset: function (latlng) {
+ return this.latLngToLayerPoint(latlng).subtract(this._getCenterLayerPoint());
+ },
+
+ _limitZoom: function (zoom) {
+ var min = this.getMinZoom(),
+ max = this.getMaxZoom();
+
+ return Math.max(min, Math.min(max, zoom));
+ }
+});
+
+L.map = function (id, options) {
+ return new L.Map(id, options);
+};
+
+
+/*
+ * Mercator projection that takes into account that the Earth is not a perfect sphere.
+ * Less popular than spherical mercator; used by projections like EPSG:3395.
+ */
+
+L.Projection.Mercator = {
+ MAX_LATITUDE: 85.0840591556,
+
+ R_MINOR: 6356752.314245179,
+ R_MAJOR: 6378137,
+
+ project: function (latlng) { // (LatLng) -> Point
+ var d = L.LatLng.DEG_TO_RAD,
+ max = this.MAX_LATITUDE,
+ lat = Math.max(Math.min(max, latlng.lat), -max),
+ r = this.R_MAJOR,
+ r2 = this.R_MINOR,
+ x = latlng.lng * d * r,
+ y = lat * d,
+ tmp = r2 / r,
+ eccent = Math.sqrt(1.0 - tmp * tmp),
+ con = eccent * Math.sin(y);
+
+ con = Math.pow((1 - con) / (1 + con), eccent * 0.5);
+
+ var ts = Math.tan(0.5 * ((Math.PI * 0.5) - y)) / con;
+ y = -r * Math.log(ts);
+
+ return new L.Point(x, y);
+ },
+
+ unproject: function (point) { // (Point, Boolean) -> LatLng
+ var d = L.LatLng.RAD_TO_DEG,
+ r = this.R_MAJOR,
+ r2 = this.R_MINOR,
+ lng = point.x * d / r,
+ tmp = r2 / r,
+ eccent = Math.sqrt(1 - (tmp * tmp)),
+ ts = Math.exp(- point.y / r),
+ phi = (Math.PI / 2) - 2 * Math.atan(ts),
+ numIter = 15,
+ tol = 1e-7,
+ i = numIter,
+ dphi = 0.1,
+ con;
+
+ while ((Math.abs(dphi) > tol) && (--i > 0)) {
+ con = eccent * Math.sin(phi);
+ dphi = (Math.PI / 2) - 2 * Math.atan(ts *
+ Math.pow((1.0 - con) / (1.0 + con), 0.5 * eccent)) - phi;
+ phi += dphi;
+ }
+
+ return new L.LatLng(phi * d, lng);
+ }
+};
+
+
+
+L.CRS.EPSG3395 = L.extend({}, L.CRS, {
+ code: 'EPSG:3395',
+
+ projection: L.Projection.Mercator,
+
+ transformation: (function () {
+ var m = L.Projection.Mercator,
+ r = m.R_MAJOR,
+ r2 = m.R_MINOR;
+
+ return new L.Transformation(0.5 / (Math.PI * r), 0.5, -0.5 / (Math.PI * r2), 0.5);
+ }())
+});
+
+
+/*
+ * L.TileLayer is used for standard xyz-numbered tile layers.
+ */
+
+L.TileLayer = L.Class.extend({
+ includes: L.Mixin.Events,
+
+ options: {
+ minZoom: 0,
+ maxZoom: 18,
+ tileSize: 256,
+ subdomains: 'abc',
+ errorTileUrl: '',
+ attribution: '',
+ zoomOffset: 0,
+ opacity: 1,
+ /* (undefined works too)
+ zIndex: null,
+ tms: false,
+ continuousWorld: false,
+ noWrap: false,
+ zoomReverse: false,
+ detectRetina: false,
+ reuseTiles: false,
+ bounds: false,
+ */
+ unloadInvisibleTiles: L.Browser.mobile,
+ updateWhenIdle: L.Browser.mobile
+ },
+
+ initialize: function (url, options) {
+ options = L.setOptions(this, options);
+
+ // detecting retina displays, adjusting tileSize and zoom levels
+ if (options.detectRetina && L.Browser.retina && options.maxZoom > 0) {
+
+ options.tileSize = Math.floor(options.tileSize / 2);
+ options.zoomOffset++;
+
+ if (options.minZoom > 0) {
+ options.minZoom--;
+ }
+ this.options.maxZoom--;
+ }
+
+ if (options.bounds) {
+ options.bounds = L.latLngBounds(options.bounds);
+ }
+
+ this._url = url;
+
+ var subdomains = this.options.subdomains;
+
+ if (typeof subdomains === 'string') {
+ this.options.subdomains = subdomains.split('');
+ }
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+ this._animated = map._zoomAnimated;
+
+ // create a container div for tiles
+ this._initContainer();
+
+ // create an image to clone for tiles
+ this._createTileProto();
+
+ // set up events
+ map.on({
+ 'viewreset': this._reset,
+ 'moveend': this._update
+ }, this);
+
+ if (this._animated) {
+ map.on({
+ 'zoomanim': this._animateZoom,
+ 'zoomend': this._endZoomAnim
+ }, this);
+ }
+
+ if (!this.options.updateWhenIdle) {
+ this._limitedUpdate = L.Util.limitExecByInterval(this._update, 150, this);
+ map.on('move', this._limitedUpdate, this);
+ }
+
+ this._reset();
+ this._update();
+ },
+
+ addTo: function (map) {
+ map.addLayer(this);
+ return this;
+ },
+
+ onRemove: function (map) {
+ this._container.parentNode.removeChild(this._container);
+
+ map.off({
+ 'viewreset': this._reset,
+ 'moveend': this._update
+ }, this);
+
+ if (this._animated) {
+ map.off({
+ 'zoomanim': this._animateZoom,
+ 'zoomend': this._endZoomAnim
+ }, this);
+ }
+
+ if (!this.options.updateWhenIdle) {
+ map.off('move', this._limitedUpdate, this);
+ }
+
+ this._container = null;
+ this._map = null;
+ },
+
+ bringToFront: function () {
+ var pane = this._map._panes.tilePane;
+
+ if (this._container) {
+ pane.appendChild(this._container);
+ this._setAutoZIndex(pane, Math.max);
+ }
+
+ return this;
+ },
+
+ bringToBack: function () {
+ var pane = this._map._panes.tilePane;
+
+ if (this._container) {
+ pane.insertBefore(this._container, pane.firstChild);
+ this._setAutoZIndex(pane, Math.min);
+ }
+
+ return this;
+ },
+
+ getAttribution: function () {
+ return this.options.attribution;
+ },
+
+ getContainer: function () {
+ return this._container;
+ },
+
+ setOpacity: function (opacity) {
+ this.options.opacity = opacity;
+
+ if (this._map) {
+ this._updateOpacity();
+ }
+
+ return this;
+ },
+
+ setZIndex: function (zIndex) {
+ this.options.zIndex = zIndex;
+ this._updateZIndex();
+
+ return this;
+ },
+
+ setUrl: function (url, noRedraw) {
+ this._url = url;
+
+ if (!noRedraw) {
+ this.redraw();
+ }
+
+ return this;
+ },
+
+ redraw: function () {
+ if (this._map) {
+ this._reset({hard: true});
+ this._update();
+ }
+ return this;
+ },
+
+ _updateZIndex: function () {
+ if (this._container && this.options.zIndex !== undefined) {
+ this._container.style.zIndex = this.options.zIndex;
+ }
+ },
+
+ _setAutoZIndex: function (pane, compare) {
+
+ var layers = pane.children,
+ edgeZIndex = -compare(Infinity, -Infinity), // -Infinity for max, Infinity for min
+ zIndex, i, len;
+
+ for (i = 0, len = layers.length; i < len; i++) {
+
+ if (layers[i] !== this._container) {
+ zIndex = parseInt(layers[i].style.zIndex, 10);
+
+ if (!isNaN(zIndex)) {
+ edgeZIndex = compare(edgeZIndex, zIndex);
+ }
+ }
+ }
+
+ this.options.zIndex = this._container.style.zIndex =
+ (isFinite(edgeZIndex) ? edgeZIndex : 0) + compare(1, -1);
+ },
+
+ _updateOpacity: function () {
+ var i,
+ tiles = this._tiles;
+
+ if (L.Browser.ielt9) {
+ for (i in tiles) {
+ L.DomUtil.setOpacity(tiles[i], this.options.opacity);
+ }
+ } else {
+ L.DomUtil.setOpacity(this._container, this.options.opacity);
+ }
+ },
+
+ _initContainer: function () {
+ var tilePane = this._map._panes.tilePane;
+
+ if (!this._container) {
+ this._container = L.DomUtil.create('div', 'leaflet-layer');
+
+ this._updateZIndex();
+
+ if (this._animated) {
+ var className = 'leaflet-tile-container leaflet-zoom-animated';
+
+ this._bgBuffer = L.DomUtil.create('div', className, this._container);
+ this._tileContainer = L.DomUtil.create('div', className, this._container);
+
+ } else {
+ this._tileContainer = this._container;
+ }
+
+ tilePane.appendChild(this._container);
+
+ if (this.options.opacity < 1) {
+ this._updateOpacity();
+ }
+ }
+ },
+
+ _reset: function (e) {
+ for (var key in this._tiles) {
+ this.fire('tileunload', {tile: this._tiles[key]});
+ }
+
+ this._tiles = {};
+ this._tilesToLoad = 0;
+
+ if (this.options.reuseTiles) {
+ this._unusedTiles = [];
+ }
+
+ this._tileContainer.innerHTML = '';
+
+ if (this._animated && e && e.hard) {
+ this._clearBgBuffer();
+ }
+
+ this._initContainer();
+ },
+
+ _update: function () {
+
+ if (!this._map) { return; }
+
+ var bounds = this._map.getPixelBounds(),
+ zoom = this._map.getZoom(),
+ tileSize = this.options.tileSize;
+
+ if (zoom > this.options.maxZoom || zoom < this.options.minZoom) {
+ return;
+ }
+
+ var tileBounds = L.bounds(
+ bounds.min.divideBy(tileSize)._floor(),
+ bounds.max.divideBy(tileSize)._floor());
+
+ this._addTilesFromCenterOut(tileBounds);
+
+ if (this.options.unloadInvisibleTiles || this.options.reuseTiles) {
+ this._removeOtherTiles(tileBounds);
+ }
+ },
+
+ _addTilesFromCenterOut: function (bounds) {
+ var queue = [],
+ center = bounds.getCenter();
+
+ var j, i, point;
+
+ for (j = bounds.min.y; j <= bounds.max.y; j++) {
+ for (i = bounds.min.x; i <= bounds.max.x; i++) {
+ point = new L.Point(i, j);
+
+ if (this._tileShouldBeLoaded(point)) {
+ queue.push(point);
+ }
+ }
+ }
+
+ var tilesToLoad = queue.length;
+
+ if (tilesToLoad === 0) { return; }
+
+ // load tiles in order of their distance to center
+ queue.sort(function (a, b) {
+ return a.distanceTo(center) - b.distanceTo(center);
+ });
+
+ var fragment = document.createDocumentFragment();
+
+ // if its the first batch of tiles to load
+ if (!this._tilesToLoad) {
+ this.fire('loading');
+ }
+
+ this._tilesToLoad += tilesToLoad;
+
+ for (i = 0; i < tilesToLoad; i++) {
+ this._addTile(queue[i], fragment);
+ }
+
+ this._tileContainer.appendChild(fragment);
+ },
+
+ _tileShouldBeLoaded: function (tilePoint) {
+ if ((tilePoint.x + ':' + tilePoint.y) in this._tiles) {
+ return false; // already loaded
+ }
+
+ var options = this.options;
+
+ if (!options.continuousWorld) {
+ var limit = this._getWrapTileNum();
+
+ // don't load if exceeds world bounds
+ if ((options.noWrap && (tilePoint.x < 0 || tilePoint.x >= limit)) ||
+ tilePoint.y < 0 || tilePoint.y >= limit) { return false; }
+ }
+
+ if (options.bounds) {
+ var tileSize = options.tileSize,
+ nwPoint = tilePoint.multiplyBy(tileSize),
+ sePoint = nwPoint.add([tileSize, tileSize]),
+ nw = this._map.unproject(nwPoint),
+ se = this._map.unproject(sePoint);
+
+ // TODO temporary hack, will be removed after refactoring projections
+ // https://github.com/Leaflet/Leaflet/issues/1618
+ if (!options.continuousWorld && !options.noWrap) {
+ nw = nw.wrap();
+ se = se.wrap();
+ }
+
+ if (!options.bounds.intersects([nw, se])) { return false; }
+ }
+
+ return true;
+ },
+
+ _removeOtherTiles: function (bounds) {
+ var kArr, x, y, key;
+
+ for (key in this._tiles) {
+ kArr = key.split(':');
+ x = parseInt(kArr[0], 10);
+ y = parseInt(kArr[1], 10);
+
+ // remove tile if it's out of bounds
+ if (x < bounds.min.x || x > bounds.max.x || y < bounds.min.y || y > bounds.max.y) {
+ this._removeTile(key);
+ }
+ }
+ },
+
+ _removeTile: function (key) {
+ var tile = this._tiles[key];
+
+ this.fire('tileunload', {tile: tile, url: tile.src});
+
+ if (this.options.reuseTiles) {
+ L.DomUtil.removeClass(tile, 'leaflet-tile-loaded');
+ this._unusedTiles.push(tile);
+
+ } else if (tile.parentNode === this._tileContainer) {
+ this._tileContainer.removeChild(tile);
+ }
+
+ // for https://github.com/CloudMade/Leaflet/issues/137
+ if (!L.Browser.android) {
+ tile.onload = null;
+ tile.src = L.Util.emptyImageUrl;
+ }
+
+ delete this._tiles[key];
+ },
+
+ _addTile: function (tilePoint, container) {
+ var tilePos = this._getTilePos(tilePoint);
+
+ // get unused tile - or create a new tile
+ var tile = this._getTile();
+
+ /*
+ Chrome 20 layouts much faster with top/left (verify with timeline, frames)
+ Android 4 browser has display issues with top/left and requires transform instead
+ Android 2 browser requires top/left or tiles disappear on load or first drag
+ (reappear after zoom) https://github.com/CloudMade/Leaflet/issues/866
+ (other browsers don't currently care) - see debug/hacks/jitter.html for an example
+ */
+ L.DomUtil.setPosition(tile, tilePos, L.Browser.chrome || L.Browser.android23);
+
+ this._tiles[tilePoint.x + ':' + tilePoint.y] = tile;
+
+ this._loadTile(tile, tilePoint);
+
+ if (tile.parentNode !== this._tileContainer) {
+ container.appendChild(tile);
+ }
+ },
+
+ _getZoomForUrl: function () {
+
+ var options = this.options,
+ zoom = this._map.getZoom();
+
+ if (options.zoomReverse) {
+ zoom = options.maxZoom - zoom;
+ }
+
+ return zoom + options.zoomOffset;
+ },
+
+ _getTilePos: function (tilePoint) {
+ var origin = this._map.getPixelOrigin(),
+ tileSize = this.options.tileSize;
+
+ return tilePoint.multiplyBy(tileSize).subtract(origin);
+ },
+
+ // image-specific code (override to implement e.g. Canvas or SVG tile layer)
+
+ getTileUrl: function (tilePoint) {
+ return L.Util.template(this._url, L.extend({
+ s: this._getSubdomain(tilePoint),
+ z: tilePoint.z,
+ x: tilePoint.x,
+ y: tilePoint.y
+ }, this.options));
+ },
+
+ _getWrapTileNum: function () {
+ // TODO refactor, limit is not valid for non-standard projections
+ return Math.pow(2, this._getZoomForUrl());
+ },
+
+ _adjustTilePoint: function (tilePoint) {
+
+ var limit = this._getWrapTileNum();
+
+ // wrap tile coordinates
+ if (!this.options.continuousWorld && !this.options.noWrap) {
+ tilePoint.x = ((tilePoint.x % limit) + limit) % limit;
+ }
+
+ if (this.options.tms) {
+ tilePoint.y = limit - tilePoint.y - 1;
+ }
+
+ tilePoint.z = this._getZoomForUrl();
+ },
+
+ _getSubdomain: function (tilePoint) {
+ var index = Math.abs(tilePoint.x + tilePoint.y) % this.options.subdomains.length;
+ return this.options.subdomains[index];
+ },
+
+ _createTileProto: function () {
+ var img = this._tileImg = L.DomUtil.create('img', 'leaflet-tile');
+ img.style.width = img.style.height = this.options.tileSize + 'px';
+ img.galleryimg = 'no';
+ },
+
+ _getTile: function () {
+ if (this.options.reuseTiles && this._unusedTiles.length > 0) {
+ var tile = this._unusedTiles.pop();
+ this._resetTile(tile);
+ return tile;
+ }
+ return this._createTile();
+ },
+
+ // Override if data stored on a tile needs to be cleaned up before reuse
+ _resetTile: function (/*tile*/) {},
+
+ _createTile: function () {
+ var tile = this._tileImg.cloneNode(false);
+ tile.onselectstart = tile.onmousemove = L.Util.falseFn;
+
+ if (L.Browser.ielt9 && this.options.opacity !== undefined) {
+ L.DomUtil.setOpacity(tile, this.options.opacity);
+ }
+ return tile;
+ },
+
+ _loadTile: function (tile, tilePoint) {
+ tile._layer = this;
+ tile.onload = this._tileOnLoad;
+ tile.onerror = this._tileOnError;
+
+ this._adjustTilePoint(tilePoint);
+ tile.src = this.getTileUrl(tilePoint);
+ },
+
+ _tileLoaded: function () {
+ this._tilesToLoad--;
+ if (!this._tilesToLoad) {
+ this.fire('load');
+
+ if (this._animated) {
+ // clear scaled tiles after all new tiles are loaded (for performance)
+ clearTimeout(this._clearBgBufferTimer);
+ this._clearBgBufferTimer = setTimeout(L.bind(this._clearBgBuffer, this), 500);
+ }
+ }
+ },
+
+ _tileOnLoad: function () {
+ var layer = this._layer;
+
+ //Only if we are loading an actual image
+ if (this.src !== L.Util.emptyImageUrl) {
+ L.DomUtil.addClass(this, 'leaflet-tile-loaded');
+
+ layer.fire('tileload', {
+ tile: this,
+ url: this.src
+ });
+ }
+
+ layer._tileLoaded();
+ },
+
+ _tileOnError: function () {
+ var layer = this._layer;
+
+ layer.fire('tileerror', {
+ tile: this,
+ url: this.src
+ });
+
+ var newUrl = layer.options.errorTileUrl;
+ if (newUrl) {
+ this.src = newUrl;
+ }
+
+ layer._tileLoaded();
+ }
+});
+
+L.tileLayer = function (url, options) {
+ return new L.TileLayer(url, options);
+};
+
+
+/*
+ * L.TileLayer.WMS is used for putting WMS tile layers on the map.
+ */
+
+L.TileLayer.WMS = L.TileLayer.extend({
+
+ defaultWmsParams: {
+ service: 'WMS',
+ request: 'GetMap',
+ version: '1.1.1',
+ layers: '',
+ styles: '',
+ format: 'image/jpeg',
+ transparent: false
+ },
+
+ initialize: function (url, options) { // (String, Object)
+
+ this._url = url;
+
+ var wmsParams = L.extend({}, this.defaultWmsParams),
+ tileSize = options.tileSize || this.options.tileSize;
+
+ if (options.detectRetina && L.Browser.retina) {
+ wmsParams.width = wmsParams.height = tileSize * 2;
+ } else {
+ wmsParams.width = wmsParams.height = tileSize;
+ }
+
+ for (var i in options) {
+ // all keys that are not TileLayer options go to WMS params
+ if (!this.options.hasOwnProperty(i) && i !== 'crs') {
+ wmsParams[i] = options[i];
+ }
+ }
+
+ this.wmsParams = wmsParams;
+
+ L.setOptions(this, options);
+ },
+
+ onAdd: function (map) {
+
+ this._crs = this.options.crs || map.options.crs;
+
+ var projectionKey = parseFloat(this.wmsParams.version) >= 1.3 ? 'crs' : 'srs';
+ this.wmsParams[projectionKey] = this._crs.code;
+
+ L.TileLayer.prototype.onAdd.call(this, map);
+ },
+
+ getTileUrl: function (tilePoint, zoom) { // (Point, Number) -> String
+
+ var map = this._map,
+ tileSize = this.options.tileSize,
+
+ nwPoint = tilePoint.multiplyBy(tileSize),
+ sePoint = nwPoint.add([tileSize, tileSize]),
+
+ nw = this._crs.project(map.unproject(nwPoint, zoom)),
+ se = this._crs.project(map.unproject(sePoint, zoom)),
+
+ bbox = [nw.x, se.y, se.x, nw.y].join(','),
+
+ url = L.Util.template(this._url, {s: this._getSubdomain(tilePoint)});
+
+ return url + L.Util.getParamString(this.wmsParams, url, true) + '&BBOX=' + bbox;
+ },
+
+ setParams: function (params, noRedraw) {
+
+ L.extend(this.wmsParams, params);
+
+ if (!noRedraw) {
+ this.redraw();
+ }
+
+ return this;
+ }
+});
+
+L.tileLayer.wms = function (url, options) {
+ return new L.TileLayer.WMS(url, options);
+};
+
+
+/*
+ * L.TileLayer.Canvas is a class that you can use as a base for creating
+ * dynamically drawn Canvas-based tile layers.
+ */
+
+L.TileLayer.Canvas = L.TileLayer.extend({
+ options: {
+ async: false
+ },
+
+ initialize: function (options) {
+ L.setOptions(this, options);
+ },
+
+ redraw: function () {
+ if (this._map) {
+ this._reset({hard: true});
+ this._update();
+ }
+
+ for (var i in this._tiles) {
+ this._redrawTile(this._tiles[i]);
+ }
+ return this;
+ },
+
+ _redrawTile: function (tile) {
+ this.drawTile(tile, tile._tilePoint, this._map._zoom);
+ },
+
+ _createTileProto: function () {
+ var proto = this._canvasProto = L.DomUtil.create('canvas', 'leaflet-tile');
+ proto.width = proto.height = this.options.tileSize;
+ },
+
+ _createTile: function () {
+ var tile = this._canvasProto.cloneNode(false);
+ tile.onselectstart = tile.onmousemove = L.Util.falseFn;
+ return tile;
+ },
+
+ _loadTile: function (tile, tilePoint) {
+ tile._layer = this;
+ tile._tilePoint = tilePoint;
+
+ this._redrawTile(tile);
+
+ if (!this.options.async) {
+ this.tileDrawn(tile);
+ }
+ },
+
+ drawTile: function (/*tile, tilePoint*/) {
+ // override with rendering code
+ },
+
+ tileDrawn: function (tile) {
+ this._tileOnLoad.call(tile);
+ }
+});
+
+
+L.tileLayer.canvas = function (options) {
+ return new L.TileLayer.Canvas(options);
+};
+
+
+/*
+ * L.ImageOverlay is used to overlay images over the map (to specific geographical bounds).
+ */
+
+L.ImageOverlay = L.Class.extend({
+ includes: L.Mixin.Events,
+
+ options: {
+ opacity: 1
+ },
+
+ initialize: function (url, bounds, options) { // (String, LatLngBounds, Object)
+ this._url = url;
+ this._bounds = L.latLngBounds(bounds);
+
+ L.setOptions(this, options);
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+
+ if (!this._image) {
+ this._initImage();
+ }
+
+ map._panes.overlayPane.appendChild(this._image);
+
+ map.on('viewreset', this._reset, this);
+
+ if (map.options.zoomAnimation && L.Browser.any3d) {
+ map.on('zoomanim', this._animateZoom, this);
+ }
+
+ this._reset();
+ },
+
+ onRemove: function (map) {
+ map.getPanes().overlayPane.removeChild(this._image);
+
+ map.off('viewreset', this._reset, this);
+
+ if (map.options.zoomAnimation) {
+ map.off('zoomanim', this._animateZoom, this);
+ }
+ },
+
+ addTo: function (map) {
+ map.addLayer(this);
+ return this;
+ },
+
+ setOpacity: function (opacity) {
+ this.options.opacity = opacity;
+ this._updateOpacity();
+ return this;
+ },
+
+ // TODO remove bringToFront/bringToBack duplication from TileLayer/Path
+ bringToFront: function () {
+ if (this._image) {
+ this._map._panes.overlayPane.appendChild(this._image);
+ }
+ return this;
+ },
+
+ bringToBack: function () {
+ var pane = this._map._panes.overlayPane;
+ if (this._image) {
+ pane.insertBefore(this._image, pane.firstChild);
+ }
+ return this;
+ },
+
+ _initImage: function () {
+ this._image = L.DomUtil.create('img', 'leaflet-image-layer');
+
+ if (this._map.options.zoomAnimation && L.Browser.any3d) {
+ L.DomUtil.addClass(this._image, 'leaflet-zoom-animated');
+ } else {
+ L.DomUtil.addClass(this._image, 'leaflet-zoom-hide');
+ }
+
+ this._updateOpacity();
+
+ //TODO createImage util method to remove duplication
+ L.extend(this._image, {
+ galleryimg: 'no',
+ onselectstart: L.Util.falseFn,
+ onmousemove: L.Util.falseFn,
+ onload: L.bind(this._onImageLoad, this),
+ src: this._url
+ });
+ },
+
+ _animateZoom: function (e) {
+ var map = this._map,
+ image = this._image,
+ scale = map.getZoomScale(e.zoom),
+ nw = this._bounds.getNorthWest(),
+ se = this._bounds.getSouthEast(),
+
+ topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
+ size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
+ origin = topLeft._add(size._multiplyBy((1 / 2) * (1 - 1 / scale)));
+
+ image.style[L.DomUtil.TRANSFORM] =
+ L.DomUtil.getTranslateString(origin) + ' scale(' + scale + ') ';
+ },
+
+ _reset: function () {
+ var image = this._image,
+ topLeft = this._map.latLngToLayerPoint(this._bounds.getNorthWest()),
+ size = this._map.latLngToLayerPoint(this._bounds.getSouthEast())._subtract(topLeft);
+
+ L.DomUtil.setPosition(image, topLeft);
+
+ image.style.width = size.x + 'px';
+ image.style.height = size.y + 'px';
+ },
+
+ _onImageLoad: function () {
+ this.fire('load');
+ },
+
+ _updateOpacity: function () {
+ L.DomUtil.setOpacity(this._image, this.options.opacity);
+ }
+});
+
+L.imageOverlay = function (url, bounds, options) {
+ return new L.ImageOverlay(url, bounds, options);
+};
+
+
+/*
+ * L.Icon is an image-based icon class that you can use with L.Marker for custom markers.
+ */
+
+L.Icon = L.Class.extend({
+ options: {
+ /*
+ iconUrl: (String) (required)
+ iconRetinaUrl: (String) (optional, used for retina devices if detected)
+ iconSize: (Point) (can be set through CSS)
+ iconAnchor: (Point) (centered by default, can be set in CSS with negative margins)
+ popupAnchor: (Point) (if not specified, popup opens in the anchor point)
+ shadowUrl: (String) (no shadow by default)
+ shadowRetinaUrl: (String) (optional, used for retina devices if detected)
+ shadowSize: (Point)
+ shadowAnchor: (Point)
+ */
+ className: ''
+ },
+
+ initialize: function (options) {
+ L.setOptions(this, options);
+ },
+
+ createIcon: function (oldIcon) {
+ return this._createIcon('icon', oldIcon);
+ },
+
+ createShadow: function (oldIcon) {
+ return this._createIcon('shadow', oldIcon);
+ },
+
+ _createIcon: function (name, oldIcon) {
+ var src = this._getIconUrl(name);
+
+ if (!src) {
+ if (name === 'icon') {
+ throw new Error('iconUrl not set in Icon options (see the docs).');
+ }
+ return null;
+ }
+
+ var img;
+ if (!oldIcon || oldIcon.tagName !== 'IMG') {
+ img = this._createImg(src);
+ } else {
+ img = this._createImg(src, oldIcon);
+ }
+ this._setIconStyles(img, name);
+
+ return img;
+ },
+
+ _setIconStyles: function (img, name) {
+ var options = this.options,
+ size = L.point(options[name + 'Size']),
+ anchor;
+
+ if (name === 'shadow') {
+ anchor = L.point(options.shadowAnchor || options.iconAnchor);
+ } else {
+ anchor = L.point(options.iconAnchor);
+ }
+
+ if (!anchor && size) {
+ anchor = size.divideBy(2, true);
+ }
+
+ img.className = 'leaflet-marker-' + name + ' ' + options.className;
+
+ if (anchor) {
+ img.style.marginLeft = (-anchor.x) + 'px';
+ img.style.marginTop = (-anchor.y) + 'px';
+ }
+
+ if (size) {
+ img.style.width = size.x + 'px';
+ img.style.height = size.y + 'px';
+ }
+ },
+
+ _createImg: function (src, el) {
+
+ if (!L.Browser.ie6) {
+ if (!el) {
+ el = document.createElement('img');
+ }
+ el.src = src;
+ } else {
+ if (!el) {
+ el = document.createElement('div');
+ }
+ el.style.filter =
+ 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '")';
+ }
+ return el;
+ },
+
+ _getIconUrl: function (name) {
+ if (L.Browser.retina && this.options[name + 'RetinaUrl']) {
+ return this.options[name + 'RetinaUrl'];
+ }
+ return this.options[name + 'Url'];
+ }
+});
+
+L.icon = function (options) {
+ return new L.Icon(options);
+};
+
+
+/*
+ * L.Icon.Default is the blue marker icon used by default in Leaflet.
+ */
+
+L.Icon.Default = L.Icon.extend({
+
+ options: {
+ iconSize: [25, 41],
+ iconAnchor: [12, 41],
+ popupAnchor: [1, -34],
+
+ shadowSize: [41, 41]
+ },
+
+ _getIconUrl: function (name) {
+ var key = name + 'Url';
+
+ if (this.options[key]) {
+ return this.options[key];
+ }
+
+ if (L.Browser.retina && name === 'icon') {
+ name += '-2x';
+ }
+
+ var path = L.Icon.Default.imagePath;
+
+ if (!path) {
+ throw new Error('Couldn\'t autodetect L.Icon.Default.imagePath, set it manually.');
+ }
+
+ return path + '/marker-' + name + '.png';
+ }
+});
+
+L.Icon.Default.imagePath = (function () {
+ var scripts = document.getElementsByTagName('script'),
+ leafletRe = /[\/^]leaflet[\-\._]?([\w\-\._]*)\.js\??/;
+
+ var i, len, src, matches, path;
+
+ for (i = 0, len = scripts.length; i < len; i++) {
+ src = scripts[i].src;
+ matches = src.match(leafletRe);
+
+ if (matches) {
+ path = src.split(leafletRe)[0];
+ return (path ? path + '/' : '') + 'images';
+ }
+ }
+}());
+
+
+/*
+ * L.Marker is used to display clickable/draggable icons on the map.
+ */
+
+L.Marker = L.Class.extend({
+
+ includes: L.Mixin.Events,
+
+ options: {
+ icon: new L.Icon.Default(),
+ title: '',
+ clickable: true,
+ draggable: false,
+ keyboard: true,
+ zIndexOffset: 0,
+ opacity: 1,
+ riseOnHover: false,
+ riseOffset: 250
+ },
+
+ initialize: function (latlng, options) {
+ L.setOptions(this, options);
+ this._latlng = L.latLng(latlng);
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+
+ map.on('viewreset', this.update, this);
+
+ this._initIcon();
+ this.update();
+
+ if (map.options.zoomAnimation && map.options.markerZoomAnimation) {
+ map.on('zoomanim', this._animateZoom, this);
+ }
+ },
+
+ addTo: function (map) {
+ map.addLayer(this);
+ return this;
+ },
+
+ onRemove: function (map) {
+ if (this.dragging) {
+ this.dragging.disable();
+ }
+
+ this._removeIcon();
+ this._removeShadow();
+
+ this.fire('remove');
+
+ map.off({
+ 'viewreset': this.update,
+ 'zoomanim': this._animateZoom
+ }, this);
+
+ this._map = null;
+ },
+
+ getLatLng: function () {
+ return this._latlng;
+ },
+
+ setLatLng: function (latlng) {
+ this._latlng = L.latLng(latlng);
+
+ this.update();
+
+ return this.fire('move', { latlng: this._latlng });
+ },
+
+ setZIndexOffset: function (offset) {
+ this.options.zIndexOffset = offset;
+ this.update();
+
+ return this;
+ },
+
+ setIcon: function (icon) {
+
+ this.options.icon = icon;
+
+ if (this._map) {
+ this._initIcon();
+ this.update();
+ }
+
+ return this;
+ },
+
+ update: function () {
+ if (this._icon) {
+ var pos = this._map.latLngToLayerPoint(this._latlng).round();
+ this._setPos(pos);
+ }
+
+ return this;
+ },
+
+ _initIcon: function () {
+ var options = this.options,
+ map = this._map,
+ animation = (map.options.zoomAnimation && map.options.markerZoomAnimation),
+ classToAdd = animation ? 'leaflet-zoom-animated' : 'leaflet-zoom-hide';
+
+ var icon = options.icon.createIcon(this._icon),
+ addIcon = false;
+
+ // if we're not reusing the icon, remove the old one and init new one
+ if (icon !== this._icon) {
+ if (this._icon) {
+ this._removeIcon();
+ }
+ addIcon = true;
+
+ if (options.title) {
+ icon.title = options.title;
+ }
+ }
+
+ L.DomUtil.addClass(icon, classToAdd);
+
+ if (options.keyboard) {
+ icon.tabIndex = '0';
+ }
+
+ this._icon = icon;
+
+ this._initInteraction();
+
+ if (options.riseOnHover) {
+ L.DomEvent
+ .on(icon, 'mouseover', this._bringToFront, this)
+ .on(icon, 'mouseout', this._resetZIndex, this);
+ }
+
+ var newShadow = options.icon.createShadow(this._shadow),
+ addShadow = false;
+
+ if (newShadow !== this._shadow) {
+ this._removeShadow();
+ addShadow = true;
+ }
+
+ if (newShadow) {
+ L.DomUtil.addClass(newShadow, classToAdd);
+ }
+ this._shadow = newShadow;
+
+
+ if (options.opacity < 1) {
+ this._updateOpacity();
+ }
+
+
+ var panes = this._map._panes;
+
+ if (addIcon) {
+ panes.markerPane.appendChild(this._icon);
+ }
+
+ if (newShadow && addShadow) {
+ panes.shadowPane.appendChild(this._shadow);
+ }
+ },
+
+ _removeIcon: function () {
+ if (this.options.riseOnHover) {
+ L.DomEvent
+ .off(this._icon, 'mouseover', this._bringToFront)
+ .off(this._icon, 'mouseout', this._resetZIndex);
+ }
+
+ this._map._panes.markerPane.removeChild(this._icon);
+
+ this._icon = null;
+ },
+
+ _removeShadow: function () {
+ if (this._shadow) {
+ this._map._panes.shadowPane.removeChild(this._shadow);
+ }
+ this._shadow = null;
+ },
+
+ _setPos: function (pos) {
+ L.DomUtil.setPosition(this._icon, pos);
+
+ if (this._shadow) {
+ L.DomUtil.setPosition(this._shadow, pos);
+ }
+
+ this._zIndex = pos.y + this.options.zIndexOffset;
+
+ this._resetZIndex();
+ },
+
+ _updateZIndex: function (offset) {
+ this._icon.style.zIndex = this._zIndex + offset;
+ },
+
+ _animateZoom: function (opt) {
+ var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
+
+ this._setPos(pos);
+ },
+
+ _initInteraction: function () {
+
+ if (!this.options.clickable) { return; }
+
+ // TODO refactor into something shared with Map/Path/etc. to DRY it up
+
+ var icon = this._icon,
+ events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];
+
+ L.DomUtil.addClass(icon, 'leaflet-clickable');
+ L.DomEvent.on(icon, 'click', this._onMouseClick, this);
+ L.DomEvent.on(icon, 'keypress', this._onKeyPress, this);
+
+ for (var i = 0; i < events.length; i++) {
+ L.DomEvent.on(icon, events[i], this._fireMouseEvent, this);
+ }
+
+ if (L.Handler.MarkerDrag) {
+ this.dragging = new L.Handler.MarkerDrag(this);
+
+ if (this.options.draggable) {
+ this.dragging.enable();
+ }
+ }
+ },
+
+ _onMouseClick: function (e) {
+ var wasDragged = this.dragging && this.dragging.moved();
+
+ if (this.hasEventListeners(e.type) || wasDragged) {
+ L.DomEvent.stopPropagation(e);
+ }
+
+ if (wasDragged) { return; }
+
+ if ((!this.dragging || !this.dragging._enabled) && this._map.dragging && this._map.dragging.moved()) { return; }
+
+ this.fire(e.type, {
+ originalEvent: e,
+ latlng: this._latlng
+ });
+ },
+
+ _onKeyPress: function (e) {
+ if (e.keyCode === 13) {
+ this.fire('click', {
+ originalEvent: e,
+ latlng: this._latlng
+ });
+ }
+ },
+
+ _fireMouseEvent: function (e) {
+
+ this.fire(e.type, {
+ originalEvent: e,
+ latlng: this._latlng
+ });
+
+ // TODO proper custom event propagation
+ // this line will always be called if marker is in a FeatureGroup
+ if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
+ L.DomEvent.preventDefault(e);
+ }
+ if (e.type !== 'mousedown') {
+ L.DomEvent.stopPropagation(e);
+ } else {
+ L.DomEvent.preventDefault(e);
+ }
+ },
+
+ setOpacity: function (opacity) {
+ this.options.opacity = opacity;
+ if (this._map) {
+ this._updateOpacity();
+ }
+
+ return this;
+ },
+
+ _updateOpacity: function () {
+ L.DomUtil.setOpacity(this._icon, this.options.opacity);
+ if (this._shadow) {
+ L.DomUtil.setOpacity(this._shadow, this.options.opacity);
+ }
+ },
+
+ _bringToFront: function () {
+ this._updateZIndex(this.options.riseOffset);
+ },
+
+ _resetZIndex: function () {
+ this._updateZIndex(0);
+ }
+});
+
+L.marker = function (latlng, options) {
+ return new L.Marker(latlng, options);
+};
+
+
+/*
+ * L.DivIcon is a lightweight HTML-based icon class (as opposed to the image-based L.Icon)
+ * to use with L.Marker.
+ */
+
+L.DivIcon = L.Icon.extend({
+ options: {
+ iconSize: [12, 12], // also can be set through CSS
+ /*
+ iconAnchor: (Point)
+ popupAnchor: (Point)
+ html: (String)
+ bgPos: (Point)
+ */
+ className: 'leaflet-div-icon',
+ html: false
+ },
+
+ createIcon: function (oldIcon) {
+ var div = (oldIcon && oldIcon.tagName === 'DIV') ? oldIcon : document.createElement('div'),
+ options = this.options;
+
+ if (options.html !== false) {
+ div.innerHTML = options.html;
+ } else {
+ div.innerHTML = '';
+ }
+
+ if (options.bgPos) {
+ div.style.backgroundPosition =
+ (-options.bgPos.x) + 'px ' + (-options.bgPos.y) + 'px';
+ }
+
+ this._setIconStyles(div, 'icon');
+ return div;
+ },
+
+ createShadow: function () {
+ return null;
+ }
+});
+
+L.divIcon = function (options) {
+ return new L.DivIcon(options);
+};
+
+
+/*
+ * L.Popup is used for displaying popups on the map.
+ */
+
+L.Map.mergeOptions({
+ closePopupOnClick: true
+});
+
+L.Popup = L.Class.extend({
+ includes: L.Mixin.Events,
+
+ options: {
+ minWidth: 50,
+ maxWidth: 300,
+ maxHeight: null,
+ autoPan: true,
+ closeButton: true,
+ offset: [0, 7],
+ autoPanPadding: [5, 5],
+ keepInView: false,
+ className: '',
+ zoomAnimation: true
+ },
+
+ initialize: function (options, source) {
+ L.setOptions(this, options);
+
+ this._source = source;
+ this._animated = L.Browser.any3d && this.options.zoomAnimation;
+ this._isOpen = false;
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+
+ if (!this._container) {
+ this._initLayout();
+ }
+ this._updateContent();
+
+ var animFade = map.options.fadeAnimation;
+
+ if (animFade) {
+ L.DomUtil.setOpacity(this._container, 0);
+ }
+ map._panes.popupPane.appendChild(this._container);
+
+ map.on(this._getEvents(), this);
+
+ this._update();
+
+ if (animFade) {
+ L.DomUtil.setOpacity(this._container, 1);
+ }
+
+ this.fire('open');
+
+ map.fire('popupopen', {popup: this});
+
+ if (this._source) {
+ this._source.fire('popupopen', {popup: this});
+ }
+ },
+
+ addTo: function (map) {
+ map.addLayer(this);
+ return this;
+ },
+
+ openOn: function (map) {
+ map.openPopup(this);
+ return this;
+ },
+
+ onRemove: function (map) {
+ map._panes.popupPane.removeChild(this._container);
+
+ L.Util.falseFn(this._container.offsetWidth); // force reflow
+
+ map.off(this._getEvents(), this);
+
+ if (map.options.fadeAnimation) {
+ L.DomUtil.setOpacity(this._container, 0);
+ }
+
+ this._map = null;
+
+ this.fire('close');
+
+ map.fire('popupclose', {popup: this});
+
+ if (this._source) {
+ this._source.fire('popupclose', {popup: this});
+ }
+ },
+
+ setLatLng: function (latlng) {
+ this._latlng = L.latLng(latlng);
+ this._update();
+ return this;
+ },
+
+ setContent: function (content) {
+ this._content = content;
+ this._update();
+ return this;
+ },
+
+ _getEvents: function () {
+ var events = {
+ viewreset: this._updatePosition
+ };
+
+ if (this._animated) {
+ events.zoomanim = this._zoomAnimation;
+ }
+ if ('closeOnClick' in this.options ? this.options.closeOnClick : this._map.options.closePopupOnClick) {
+ events.preclick = this._close;
+ }
+ if (this.options.keepInView) {
+ events.moveend = this._adjustPan;
+ }
+
+ return events;
+ },
+
+ _close: function () {
+ if (this._map) {
+ this._map.closePopup(this);
+ }
+ },
+
+ _initLayout: function () {
+ var prefix = 'leaflet-popup',
+ containerClass = prefix + ' ' + this.options.className + ' leaflet-zoom-' +
+ (this._animated ? 'animated' : 'hide'),
+ container = this._container = L.DomUtil.create('div', containerClass),
+ closeButton;
+
+ if (this.options.closeButton) {
+ closeButton = this._closeButton =
+ L.DomUtil.create('a', prefix + '-close-button', container);
+ closeButton.href = '#close';
+ closeButton.innerHTML = '×';
+ L.DomEvent.disableClickPropagation(closeButton);
+
+ L.DomEvent.on(closeButton, 'click', this._onCloseButtonClick, this);
+ }
+
+ var wrapper = this._wrapper =
+ L.DomUtil.create('div', prefix + '-content-wrapper', container);
+ L.DomEvent.disableClickPropagation(wrapper);
+
+ this._contentNode = L.DomUtil.create('div', prefix + '-content', wrapper);
+ L.DomEvent.on(this._contentNode, 'mousewheel', L.DomEvent.stopPropagation);
+ L.DomEvent.on(this._contentNode, 'MozMousePixelScroll', L.DomEvent.stopPropagation);
+ L.DomEvent.on(wrapper, 'contextmenu', L.DomEvent.stopPropagation);
+ this._tipContainer = L.DomUtil.create('div', prefix + '-tip-container', container);
+ this._tip = L.DomUtil.create('div', prefix + '-tip', this._tipContainer);
+ },
+
+ _update: function () {
+ if (!this._map) { return; }
+
+ this._container.style.visibility = 'hidden';
+
+ this._updateContent();
+ this._updateLayout();
+ this._updatePosition();
+
+ this._container.style.visibility = '';
+
+ this._adjustPan();
+ },
+
+ _updateContent: function () {
+ if (!this._content) { return; }
+
+ if (typeof this._content === 'string') {
+ this._contentNode.innerHTML = this._content;
+ } else {
+ while (this._contentNode.hasChildNodes()) {
+ this._contentNode.removeChild(this._contentNode.firstChild);
+ }
+ this._contentNode.appendChild(this._content);
+ }
+ this.fire('contentupdate');
+ },
+
+ _updateLayout: function () {
+ var container = this._contentNode,
+ style = container.style;
+
+ style.width = '';
+ style.whiteSpace = 'nowrap';
+
+ var width = container.offsetWidth;
+ width = Math.min(width, this.options.maxWidth);
+ width = Math.max(width, this.options.minWidth);
+
+ style.width = (width + 1) + 'px';
+ style.whiteSpace = '';
+
+ style.height = '';
+
+ var height = container.offsetHeight,
+ maxHeight = this.options.maxHeight,
+ scrolledClass = 'leaflet-popup-scrolled';
+
+ if (maxHeight && height > maxHeight) {
+ style.height = maxHeight + 'px';
+ L.DomUtil.addClass(container, scrolledClass);
+ } else {
+ L.DomUtil.removeClass(container, scrolledClass);
+ }
+
+ this._containerWidth = this._container.offsetWidth;
+ },
+
+ _updatePosition: function () {
+ if (!this._map) { return; }
+
+ var pos = this._map.latLngToLayerPoint(this._latlng),
+ animated = this._animated,
+ offset = L.point(this.options.offset);
+
+ if (animated) {
+ L.DomUtil.setPosition(this._container, pos);
+ }
+
+ this._containerBottom = -offset.y - (animated ? 0 : pos.y);
+ this._containerLeft = -Math.round(this._containerWidth / 2) + offset.x + (animated ? 0 : pos.x);
+
+ // bottom position the popup in case the height of the popup changes (images loading etc)
+ this._container.style.bottom = this._containerBottom + 'px';
+ this._container.style.left = this._containerLeft + 'px';
+ },
+
+ _zoomAnimation: function (opt) {
+ var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);
+
+ L.DomUtil.setPosition(this._container, pos);
+ },
+
+ _adjustPan: function () {
+ if (!this.options.autoPan) { return; }
+
+ var map = this._map,
+ containerHeight = this._container.offsetHeight,
+ containerWidth = this._containerWidth,
+
+ layerPos = new L.Point(this._containerLeft, -containerHeight - this._containerBottom);
+
+ if (this._animated) {
+ layerPos._add(L.DomUtil.getPosition(this._container));
+ }
+
+ var containerPos = map.layerPointToContainerPoint(layerPos),
+ padding = L.point(this.options.autoPanPadding),
+ size = map.getSize(),
+ dx = 0,
+ dy = 0;
+
+ if (containerPos.x + containerWidth > size.x) { // right
+ dx = containerPos.x + containerWidth - size.x + padding.x;
+ }
+ if (containerPos.x - dx < 0) { // left
+ dx = containerPos.x - padding.x;
+ }
+ if (containerPos.y + containerHeight > size.y) { // bottom
+ dy = containerPos.y + containerHeight - size.y + padding.y;
+ }
+ if (containerPos.y - dy < 0) { // top
+ dy = containerPos.y - padding.y;
+ }
+
+ if (dx || dy) {
+ map
+ .fire('autopanstart')
+ .panBy([dx, dy]);
+ }
+ },
+
+ _onCloseButtonClick: function (e) {
+ this._close();
+ L.DomEvent.stop(e);
+ }
+});
+
+L.popup = function (options, source) {
+ return new L.Popup(options, source);
+};
+
+
+L.Map.include({
+ openPopup: function (popup, latlng, options) { // (Popup) or (String || HTMLElement, LatLng[, Object])
+ this.closePopup();
+
+ if (!(popup instanceof L.Popup)) {
+ var content = popup;
+
+ popup = new L.Popup(options)
+ .setLatLng(latlng)
+ .setContent(content);
+ }
+ popup._isOpen = true;
+
+ this._popup = popup;
+ return this.addLayer(popup);
+ },
+
+ closePopup: function (popup) {
+ if (!popup || popup === this._popup) {
+ popup = this._popup;
+ this._popup = null;
+ }
+ if (popup) {
+ this.removeLayer(popup);
+ popup._isOpen = false;
+ }
+ return this;
+ }
+});
+
+
+/*
+ * Popup extension to L.Marker, adding popup-related methods.
+ */
+
+L.Marker.include({
+ openPopup: function () {
+ if (this._popup && this._map && !this._map.hasLayer(this._popup)) {
+ this._popup.setLatLng(this._latlng);
+ this._map.openPopup(this._popup);
+ }
+
+ return this;
+ },
+
+ closePopup: function () {
+ if (this._popup) {
+ this._popup._close();
+ }
+ return this;
+ },
+
+ togglePopup: function () {
+ if (this._popup) {
+ if (this._popup._isOpen) {
+ this.closePopup();
+ } else {
+ this.openPopup();
+ }
+ }
+ return this;
+ },
+
+ bindPopup: function (content, options) {
+ var anchor = L.point(this.options.icon.options.popupAnchor || [0, 0]);
+
+ anchor = anchor.add(L.Popup.prototype.options.offset);
+
+ if (options && options.offset) {
+ anchor = anchor.add(options.offset);
+ }
+
+ options = L.extend({offset: anchor}, options);
+
+ if (!this._popup) {
+ this
+ .on('click', this.togglePopup, this)
+ .on('remove', this.closePopup, this)
+ .on('move', this._movePopup, this);
+ }
+
+ if (content instanceof L.Popup) {
+ L.setOptions(content, options);
+ this._popup = content;
+ } else {
+ this._popup = new L.Popup(options, this)
+ .setContent(content);
+ }
+
+ return this;
+ },
+
+ setPopupContent: function (content) {
+ if (this._popup) {
+ this._popup.setContent(content);
+ }
+ return this;
+ },
+
+ unbindPopup: function () {
+ if (this._popup) {
+ this._popup = null;
+ this
+ .off('click', this.togglePopup)
+ .off('remove', this.closePopup)
+ .off('move', this._movePopup);
+ }
+ return this;
+ },
+
+ _movePopup: function (e) {
+ this._popup.setLatLng(e.latlng);
+ }
+});
+
+
+/*
+ * L.LayerGroup is a class to combine several layers into one so that
+ * you can manipulate the group (e.g. add/remove it) as one layer.
+ */
+
+L.LayerGroup = L.Class.extend({
+ initialize: function (layers) {
+ this._layers = {};
+
+ var i, len;
+
+ if (layers) {
+ for (i = 0, len = layers.length; i < len; i++) {
+ this.addLayer(layers[i]);
+ }
+ }
+ },
+
+ addLayer: function (layer) {
+ var id = this.getLayerId(layer);
+
+ this._layers[id] = layer;
+
+ if (this._map) {
+ this._map.addLayer(layer);
+ }
+
+ return this;
+ },
+
+ removeLayer: function (layer) {
+ var id = layer in this._layers ? layer : this.getLayerId(layer);
+
+ if (this._map && this._layers[id]) {
+ this._map.removeLayer(this._layers[id]);
+ }
+
+ delete this._layers[id];
+
+ return this;
+ },
+
+ hasLayer: function (layer) {
+ if (!layer) { return false; }
+
+ return (layer in this._layers || this.getLayerId(layer) in this._layers);
+ },
+
+ clearLayers: function () {
+ this.eachLayer(this.removeLayer, this);
+ return this;
+ },
+
+ invoke: function (methodName) {
+ var args = Array.prototype.slice.call(arguments, 1),
+ i, layer;
+
+ for (i in this._layers) {
+ layer = this._layers[i];
+
+ if (layer[methodName]) {
+ layer[methodName].apply(layer, args);
+ }
+ }
+
+ return this;
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+ this.eachLayer(map.addLayer, map);
+ },
+
+ onRemove: function (map) {
+ this.eachLayer(map.removeLayer, map);
+ this._map = null;
+ },
+
+ addTo: function (map) {
+ map.addLayer(this);
+ return this;
+ },
+
+ eachLayer: function (method, context) {
+ for (var i in this._layers) {
+ method.call(context, this._layers[i]);
+ }
+ return this;
+ },
+
+ getLayer: function (id) {
+ return this._layers[id];
+ },
+
+ getLayers: function () {
+ var layers = [];
+
+ for (var i in this._layers) {
+ layers.push(this._layers[i]);
+ }
+ return layers;
+ },
+
+ setZIndex: function (zIndex) {
+ return this.invoke('setZIndex', zIndex);
+ },
+
+ getLayerId: function (layer) {
+ return L.stamp(layer);
+ }
+});
+
+L.layerGroup = function (layers) {
+ return new L.LayerGroup(layers);
+};
+
+
+/*
+ * L.FeatureGroup extends L.LayerGroup by introducing mouse events and additional methods
+ * shared between a group of interactive layers (like vectors or markers).
+ */
+
+L.FeatureGroup = L.LayerGroup.extend({
+ includes: L.Mixin.Events,
+
+ statics: {
+ EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
+ },
+
+ addLayer: function (layer) {
+ if (this.hasLayer(layer)) {
+ return this;
+ }
+
+ layer.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
+
+ L.LayerGroup.prototype.addLayer.call(this, layer);
+
+ if (this._popupContent && layer.bindPopup) {
+ layer.bindPopup(this._popupContent, this._popupOptions);
+ }
+
+ return this.fire('layeradd', {layer: layer});
+ },
+
+ removeLayer: function (layer) {
+ if (!this.hasLayer(layer)) {
+ return this;
+ }
+ if (layer in this._layers) {
+ layer = this._layers[layer];
+ }
+
+ layer.off(L.FeatureGroup.EVENTS, this._propagateEvent, this);
+
+ L.LayerGroup.prototype.removeLayer.call(this, layer);
+
+ if (this._popupContent) {
+ this.invoke('unbindPopup');
+ }
+
+ return this.fire('layerremove', {layer: layer});
+ },
+
+ bindPopup: function (content, options) {
+ this._popupContent = content;
+ this._popupOptions = options;
+ return this.invoke('bindPopup', content, options);
+ },
+
+ setStyle: function (style) {
+ return this.invoke('setStyle', style);
+ },
+
+ bringToFront: function () {
+ return this.invoke('bringToFront');
+ },
+
+ bringToBack: function () {
+ return this.invoke('bringToBack');
+ },
+
+ getBounds: function () {
+ var bounds = new L.LatLngBounds();
+
+ this.eachLayer(function (layer) {
+ bounds.extend(layer instanceof L.Marker ? layer.getLatLng() : layer.getBounds());
+ });
+
+ return bounds;
+ },
+
+ _propagateEvent: function (e) {
+ if (!e.layer) {
+ e.layer = e.target;
+ }
+ e.target = this;
+
+ this.fire(e.type, e);
+ }
+});
+
+L.featureGroup = function (layers) {
+ return new L.FeatureGroup(layers);
+};
+
+
+/*
+ * L.Path is a base class for rendering vector paths on a map. Inherited by Polyline, Circle, etc.
+ */
+
+L.Path = L.Class.extend({
+ includes: [L.Mixin.Events],
+
+ statics: {
+ // how much to extend the clip area around the map view
+ // (relative to its size, e.g. 0.5 is half the screen in each direction)
+ // set it so that SVG element doesn't exceed 1280px (vectors flicker on dragend if it is)
+ CLIP_PADDING: (function () {
+ var max = L.Browser.mobile ? 1280 : 2000,
+ target = (max / Math.max(window.outerWidth, window.outerHeight) - 1) / 2;
+ return Math.max(0, Math.min(0.5, target));
+ })()
+ },
+
+ options: {
+ stroke: true,
+ color: '#0033ff',
+ dashArray: null,
+ weight: 5,
+ opacity: 0.5,
+
+ fill: false,
+ fillColor: null, //same as color by default
+ fillOpacity: 0.2,
+
+ clickable: true
+ },
+
+ initialize: function (options) {
+ L.setOptions(this, options);
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+
+ if (!this._container) {
+ this._initElements();
+ this._initEvents();
+ }
+
+ this.projectLatlngs();
+ this._updatePath();
+
+ if (this._container) {
+ this._map._pathRoot.appendChild(this._container);
+ }
+
+ this.fire('add');
+
+ map.on({
+ 'viewreset': this.projectLatlngs,
+ 'moveend': this._updatePath
+ }, this);
+ },
+
+ addTo: function (map) {
+ map.addLayer(this);
+ return this;
+ },
+
+ onRemove: function (map) {
+ map._pathRoot.removeChild(this._container);
+
+ // Need to fire remove event before we set _map to null as the event hooks might need the object
+ this.fire('remove');
+ this._map = null;
+
+ if (L.Browser.vml) {
+ this._container = null;
+ this._stroke = null;
+ this._fill = null;
+ }
+
+ map.off({
+ 'viewreset': this.projectLatlngs,
+ 'moveend': this._updatePath
+ }, this);
+ },
+
+ projectLatlngs: function () {
+ // do all projection stuff here
+ },
+
+ setStyle: function (style) {
+ L.setOptions(this, style);
+
+ if (this._container) {
+ this._updateStyle();
+ }
+
+ return this;
+ },
+
+ redraw: function () {
+ if (this._map) {
+ this.projectLatlngs();
+ this._updatePath();
+ }
+ return this;
+ }
+});
+
+L.Map.include({
+ _updatePathViewport: function () {
+ var p = L.Path.CLIP_PADDING,
+ size = this.getSize(),
+ panePos = L.DomUtil.getPosition(this._mapPane),
+ min = panePos.multiplyBy(-1)._subtract(size.multiplyBy(p)._round()),
+ max = min.add(size.multiplyBy(1 + p * 2)._round());
+
+ this._pathViewport = new L.Bounds(min, max);
+ }
+});
+
+
+/*
+ * Extends L.Path with SVG-specific rendering code.
+ */
+
+L.Path.SVG_NS = 'http://www.w3.org/2000/svg';
+
+L.Browser.svg = !!(document.createElementNS && document.createElementNS(L.Path.SVG_NS, 'svg').createSVGRect);
+
+L.Path = L.Path.extend({
+ statics: {
+ SVG: L.Browser.svg
+ },
+
+ bringToFront: function () {
+ var root = this._map._pathRoot,
+ path = this._container;
+
+ if (path && root.lastChild !== path) {
+ root.appendChild(path);
+ }
+ return this;
+ },
+
+ bringToBack: function () {
+ var root = this._map._pathRoot,
+ path = this._container,
+ first = root.firstChild;
+
+ if (path && first !== path) {
+ root.insertBefore(path, first);
+ }
+ return this;
+ },
+
+ getPathString: function () {
+ // form path string here
+ },
+
+ _createElement: function (name) {
+ return document.createElementNS(L.Path.SVG_NS, name);
+ },
+
+ _initElements: function () {
+ this._map._initPathRoot();
+ this._initPath();
+ this._initStyle();
+ },
+
+ _initPath: function () {
+ this._container = this._createElement('g');
+
+ this._path = this._createElement('path');
+ this._container.appendChild(this._path);
+ },
+
+ _initStyle: function () {
+ if (this.options.stroke) {
+ this._path.setAttribute('stroke-linejoin', 'round');
+ this._path.setAttribute('stroke-linecap', 'round');
+ }
+ if (this.options.fill) {
+ this._path.setAttribute('fill-rule', 'evenodd');
+ }
+ if (this.options.pointerEvents) {
+ this._path.setAttribute('pointer-events', this.options.pointerEvents);
+ }
+ if (!this.options.clickable && !this.options.pointerEvents) {
+ this._path.setAttribute('pointer-events', 'none');
+ }
+ this._updateStyle();
+ },
+
+ _updateStyle: function () {
+ if (this.options.stroke) {
+ this._path.setAttribute('stroke', this.options.color);
+ this._path.setAttribute('stroke-opacity', this.options.opacity);
+ this._path.setAttribute('stroke-width', this.options.weight);
+ if (this.options.dashArray) {
+ this._path.setAttribute('stroke-dasharray', this.options.dashArray);
+ } else {
+ this._path.removeAttribute('stroke-dasharray');
+ }
+ } else {
+ this._path.setAttribute('stroke', 'none');
+ }
+ if (this.options.fill) {
+ this._path.setAttribute('fill', this.options.fillColor || this.options.color);
+ this._path.setAttribute('fill-opacity', this.options.fillOpacity);
+ } else {
+ this._path.setAttribute('fill', 'none');
+ }
+ },
+
+ _updatePath: function () {
+ var str = this.getPathString();
+ if (!str) {
+ // fix webkit empty string parsing bug
+ str = 'M0 0';
+ }
+ this._path.setAttribute('d', str);
+ },
+
+ // TODO remove duplication with L.Map
+ _initEvents: function () {
+ if (this.options.clickable) {
+ if (L.Browser.svg || !L.Browser.vml) {
+ this._path.setAttribute('class', 'leaflet-clickable');
+ }
+
+ L.DomEvent.on(this._container, 'click', this._onMouseClick, this);
+
+ var events = ['dblclick', 'mousedown', 'mouseover',
+ 'mouseout', 'mousemove', 'contextmenu'];
+ for (var i = 0; i < events.length; i++) {
+ L.DomEvent.on(this._container, events[i], this._fireMouseEvent, this);
+ }
+ }
+ },
+
+ _onMouseClick: function (e) {
+ if (this._map.dragging && this._map.dragging.moved()) { return; }
+
+ this._fireMouseEvent(e);
+ },
+
+ _fireMouseEvent: function (e) {
+ if (!this.hasEventListeners(e.type)) { return; }
+
+ var map = this._map,
+ containerPoint = map.mouseEventToContainerPoint(e),
+ layerPoint = map.containerPointToLayerPoint(containerPoint),
+ latlng = map.layerPointToLatLng(layerPoint);
+
+ this.fire(e.type, {
+ latlng: latlng,
+ layerPoint: layerPoint,
+ containerPoint: containerPoint,
+ originalEvent: e
+ });
+
+ if (e.type === 'contextmenu') {
+ L.DomEvent.preventDefault(e);
+ }
+ if (e.type !== 'mousemove') {
+ L.DomEvent.stopPropagation(e);
+ }
+ }
+});
+
+L.Map.include({
+ _initPathRoot: function () {
+ if (!this._pathRoot) {
+ this._pathRoot = L.Path.prototype._createElement('svg');
+ this._panes.overlayPane.appendChild(this._pathRoot);
+
+ if (this.options.zoomAnimation && L.Browser.any3d) {
+ this._pathRoot.setAttribute('class', ' leaflet-zoom-animated');
+
+ this.on({
+ 'zoomanim': this._animatePathZoom,
+ 'zoomend': this._endPathZoom
+ });
+ } else {
+ this._pathRoot.setAttribute('class', ' leaflet-zoom-hide');
+ }
+
+ this.on('moveend', this._updateSvgViewport);
+ this._updateSvgViewport();
+ }
+ },
+
+ _animatePathZoom: function (e) {
+ var scale = this.getZoomScale(e.zoom),
+ offset = this._getCenterOffset(e.center)._multiplyBy(-scale)._add(this._pathViewport.min);
+
+ this._pathRoot.style[L.DomUtil.TRANSFORM] =
+ L.DomUtil.getTranslateString(offset) + ' scale(' + scale + ') ';
+
+ this._pathZooming = true;
+ },
+
+ _endPathZoom: function () {
+ this._pathZooming = false;
+ },
+
+ _updateSvgViewport: function () {
+
+ if (this._pathZooming) {
+ // Do not update SVGs while a zoom animation is going on otherwise the animation will break.
+ // When the zoom animation ends we will be updated again anyway
+ // This fixes the case where you do a momentum move and zoom while the move is still ongoing.
+ return;
+ }
+
+ this._updatePathViewport();
+
+ var vp = this._pathViewport,
+ min = vp.min,
+ max = vp.max,
+ width = max.x - min.x,
+ height = max.y - min.y,
+ root = this._pathRoot,
+ pane = this._panes.overlayPane;
+
+ // Hack to make flicker on drag end on mobile webkit less irritating
+ if (L.Browser.mobileWebkit) {
+ pane.removeChild(root);
+ }
+
+ L.DomUtil.setPosition(root, min);
+ root.setAttribute('width', width);
+ root.setAttribute('height', height);
+ root.setAttribute('viewBox', [min.x, min.y, width, height].join(' '));
+
+ if (L.Browser.mobileWebkit) {
+ pane.appendChild(root);
+ }
+ }
+});
+
+
+/*
+ * Popup extension to L.Path (polylines, polygons, circles), adding popup-related methods.
+ */
+
+L.Path.include({
+
+ bindPopup: function (content, options) {
+
+ if (content instanceof L.Popup) {
+ this._popup = content;
+ } else {
+ if (!this._popup || options) {
+ this._popup = new L.Popup(options, this);
+ }
+ this._popup.setContent(content);
+ }
+
+ if (!this._popupHandlersAdded) {
+ this
+ .on('click', this._openPopup, this)
+ .on('remove', this.closePopup, this);
+
+ this._popupHandlersAdded = true;
+ }
+
+ return this;
+ },
+
+ unbindPopup: function () {
+ if (this._popup) {
+ this._popup = null;
+ this
+ .off('click', this._openPopup)
+ .off('remove', this.closePopup);
+
+ this._popupHandlersAdded = false;
+ }
+ return this;
+ },
+
+ openPopup: function (latlng) {
+
+ if (this._popup) {
+ // open the popup from one of the path's points if not specified
+ latlng = latlng || this._latlng ||
+ this._latlngs[Math.floor(this._latlngs.length / 2)];
+
+ this._openPopup({latlng: latlng});
+ }
+
+ return this;
+ },
+
+ closePopup: function () {
+ if (this._popup) {
+ this._popup._close();
+ }
+ return this;
+ },
+
+ _openPopup: function (e) {
+ this._popup.setLatLng(e.latlng);
+ this._map.openPopup(this._popup);
+ }
+});
+
+
+/*
+ * Vector rendering for IE6-8 through VML.
+ * Thanks to Dmitry Baranovsky and his Raphael library for inspiration!
+ */
+
+L.Browser.vml = !L.Browser.svg && (function () {
+ try {
+ var div = document.createElement('div');
+ div.innerHTML = '<v:shape adj="1"/>';
+
+ var shape = div.firstChild;
+ shape.style.behavior = 'url(#default#VML)';
+
+ return shape && (typeof shape.adj === 'object');
+
+ } catch (e) {
+ return false;
+ }
+}());
+
+L.Path = L.Browser.svg || !L.Browser.vml ? L.Path : L.Path.extend({
+ statics: {
+ VML: true,
+ CLIP_PADDING: 0.02
+ },
+
+ _createElement: (function () {
+ try {
+ document.namespaces.add('lvml', 'urn:schemas-microsoft-com:vml');
+ return function (name) {
+ return document.createElement('<lvml:' + name + ' class="lvml">');
+ };
+ } catch (e) {
+ return function (name) {
+ return document.createElement(
+ '<' + name + ' xmlns="urn:schemas-microsoft.com:vml" class="lvml">');
+ };
+ }
+ }()),
+
+ _initPath: function () {
+ var container = this._container = this._createElement('shape');
+ L.DomUtil.addClass(container, 'leaflet-vml-shape');
+ if (this.options.clickable) {
+ L.DomUtil.addClass(container, 'leaflet-clickable');
+ }
+ container.coordsize = '1 1';
+
+ this._path = this._createElement('path');
+ container.appendChild(this._path);
+
+ this._map._pathRoot.appendChild(container);
+ },
+
+ _initStyle: function () {
+ this._updateStyle();
+ },
+
+ _updateStyle: function () {
+ var stroke = this._stroke,
+ fill = this._fill,
+ options = this.options,
+ container = this._container;
+
+ container.stroked = options.stroke;
+ container.filled = options.fill;
+
+ if (options.stroke) {
+ if (!stroke) {
+ stroke = this._stroke = this._createElement('stroke');
+ stroke.endcap = 'round';
+ container.appendChild(stroke);
+ }
+ stroke.weight = options.weight + 'px';
+ stroke.color = options.color;
+ stroke.opacity = options.opacity;
+
+ if (options.dashArray) {
+ stroke.dashStyle = options.dashArray instanceof Array ?
+ options.dashArray.join(' ') :
+ options.dashArray.replace(/( *, *)/g, ' ');
+ } else {
+ stroke.dashStyle = '';
+ }
+
+ } else if (stroke) {
+ container.removeChild(stroke);
+ this._stroke = null;
+ }
+
+ if (options.fill) {
+ if (!fill) {
+ fill = this._fill = this._createElement('fill');
+ container.appendChild(fill);
+ }
+ fill.color = options.fillColor || options.color;
+ fill.opacity = options.fillOpacity;
+
+ } else if (fill) {
+ container.removeChild(fill);
+ this._fill = null;
+ }
+ },
+
+ _updatePath: function () {
+ var style = this._container.style;
+
+ style.display = 'none';
+ this._path.v = this.getPathString() + ' '; // the space fixes IE empty path string bug
+ style.display = '';
+ }
+});
+
+L.Map.include(L.Browser.svg || !L.Browser.vml ? {} : {
+ _initPathRoot: function () {
+ if (this._pathRoot) { return; }
+
+ var root = this._pathRoot = document.createElement('div');
+ root.className = 'leaflet-vml-container';
+ this._panes.overlayPane.appendChild(root);
+
+ this.on('moveend', this._updatePathViewport);
+ this._updatePathViewport();
+ }
+});
+
+
+/*
+ * Vector rendering for all browsers that support canvas.
+ */
+
+L.Browser.canvas = (function () {
+ return !!document.createElement('canvas').getContext;
+}());
+
+L.Path = (L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? L.Path : L.Path.extend({
+ statics: {
+ //CLIP_PADDING: 0.02, // not sure if there's a need to set it to a small value
+ CANVAS: true,
+ SVG: false
+ },
+
+ redraw: function () {
+ if (this._map) {
+ this.projectLatlngs();
+ this._requestUpdate();
+ }
+ return this;
+ },
+
+ setStyle: function (style) {
+ L.setOptions(this, style);
+
+ if (this._map) {
+ this._updateStyle();
+ this._requestUpdate();
+ }
+ return this;
+ },
+
+ onRemove: function (map) {
+ map
+ .off('viewreset', this.projectLatlngs, this)
+ .off('moveend', this._updatePath, this);
+
+ if (this.options.clickable) {
+ this._map.off('click', this._onClick, this);
+ this._map.off('mousemove', this._onMouseMove, this);
+ }
+
+ this._requestUpdate();
+
+ this._map = null;
+ },
+
+ _requestUpdate: function () {
+ if (this._map && !L.Path._updateRequest) {
+ L.Path._updateRequest = L.Util.requestAnimFrame(this._fireMapMoveEnd, this._map);
+ }
+ },
+
+ _fireMapMoveEnd: function () {
+ L.Path._updateRequest = null;
+ this.fire('moveend');
+ },
+
+ _initElements: function () {
+ this._map._initPathRoot();
+ this._ctx = this._map._canvasCtx;
+ },
+
+ _updateStyle: function () {
+ var options = this.options;
+
+ if (options.stroke) {
+ this._ctx.lineWidth = options.weight;
+ this._ctx.strokeStyle = options.color;
+ }
+ if (options.fill) {
+ this._ctx.fillStyle = options.fillColor || options.color;
+ }
+ },
+
+ _drawPath: function () {
+ var i, j, len, len2, point, drawMethod;
+
+ this._ctx.beginPath();
+
+ for (i = 0, len = this._parts.length; i < len; i++) {
+ for (j = 0, len2 = this._parts[i].length; j < len2; j++) {
+ point = this._parts[i][j];
+ drawMethod = (j === 0 ? 'move' : 'line') + 'To';
+
+ this._ctx[drawMethod](point.x, point.y);
+ }
+ // TODO refactor ugly hack
+ if (this instanceof L.Polygon) {
+ this._ctx.closePath();
+ }
+ }
+ },
+
+ _checkIfEmpty: function () {
+ return !this._parts.length;
+ },
+
+ _updatePath: function () {
+ if (this._checkIfEmpty()) { return; }
+
+ var ctx = this._ctx,
+ options = this.options;
+
+ this._drawPath();
+ ctx.save();
+ this._updateStyle();
+
+ if (options.fill) {
+ ctx.globalAlpha = options.fillOpacity;
+ ctx.fill();
+ }
+
+ if (options.stroke) {
+ ctx.globalAlpha = options.opacity;
+ ctx.stroke();
+ }
+
+ ctx.restore();
+
+ // TODO optimization: 1 fill/stroke for all features with equal style instead of 1 for each feature
+ },
+
+ _initEvents: function () {
+ if (this.options.clickable) {
+ // TODO dblclick
+ this._map.on('mousemove', this._onMouseMove, this);
+ this._map.on('click', this._onClick, this);
+ }
+ },
+
+ _onClick: function (e) {
+ if (this._containsPoint(e.layerPoint)) {
+ this.fire('click', e);
+ }
+ },
+
+ _onMouseMove: function (e) {
+ if (!this._map || this._map._animatingZoom) { return; }
+
+ // TODO don't do on each move
+ if (this._containsPoint(e.layerPoint)) {
+ this._ctx.canvas.style.cursor = 'pointer';
+ this._mouseInside = true;
+ this.fire('mouseover', e);
+
+ } else if (this._mouseInside) {
+ this._ctx.canvas.style.cursor = '';
+ this._mouseInside = false;
+ this.fire('mouseout', e);
+ }
+ }
+});
+
+L.Map.include((L.Path.SVG && !window.L_PREFER_CANVAS) || !L.Browser.canvas ? {} : {
+ _initPathRoot: function () {
+ var root = this._pathRoot,
+ ctx;
+
+ if (!root) {
+ root = this._pathRoot = document.createElement('canvas');
+ root.style.position = 'absolute';
+ ctx = this._canvasCtx = root.getContext('2d');
+
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+
+ this._panes.overlayPane.appendChild(root);
+
+ if (this.options.zoomAnimation) {
+ this._pathRoot.className = 'leaflet-zoom-animated';
+ this.on('zoomanim', this._animatePathZoom);
+ this.on('zoomend', this._endPathZoom);
+ }
+ this.on('moveend', this._updateCanvasViewport);
+ this._updateCanvasViewport();
+ }
+ },
+
+ _updateCanvasViewport: function () {
+ // don't redraw while zooming. See _updateSvgViewport for more details
+ if (this._pathZooming) { return; }
+ this._updatePathViewport();
+
+ var vp = this._pathViewport,
+ min = vp.min,
+ size = vp.max.subtract(min),
+ root = this._pathRoot;
+
+ //TODO check if this works properly on mobile webkit
+ L.DomUtil.setPosition(root, min);
+ root.width = size.x;
+ root.height = size.y;
+ root.getContext('2d').translate(-min.x, -min.y);
+ }
+});
+
+
+/*
+ * L.LineUtil contains different utility functions for line segments
+ * and polylines (clipping, simplification, distances, etc.)
+ */
+
+/*jshint bitwise:false */ // allow bitwise oprations for this file
+
+L.LineUtil = {
+
+ // Simplify polyline with vertex reduction and Douglas-Peucker simplification.
+ // Improves rendering performance dramatically by lessening the number of points to draw.
+
+ simplify: function (/*Point[]*/ points, /*Number*/ tolerance) {
+ if (!tolerance || !points.length) {
+ return points.slice();
+ }
+
+ var sqTolerance = tolerance * tolerance;
+
+ // stage 1: vertex reduction
+ points = this._reducePoints(points, sqTolerance);
+
+ // stage 2: Douglas-Peucker simplification
+ points = this._simplifyDP(points, sqTolerance);
+
+ return points;
+ },
+
+ // distance from a point to a segment between two points
+ pointToSegmentDistance: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
+ return Math.sqrt(this._sqClosestPointOnSegment(p, p1, p2, true));
+ },
+
+ closestPointOnSegment: function (/*Point*/ p, /*Point*/ p1, /*Point*/ p2) {
+ return this._sqClosestPointOnSegment(p, p1, p2);
+ },
+
+ // Douglas-Peucker simplification, see http://en.wikipedia.org/wiki/Douglas-Peucker_algorithm
+ _simplifyDP: function (points, sqTolerance) {
+
+ var len = points.length,
+ ArrayConstructor = typeof Uint8Array !== undefined + '' ? Uint8Array : Array,
+ markers = new ArrayConstructor(len);
+
+ markers[0] = markers[len - 1] = 1;
+
+ this._simplifyDPStep(points, markers, sqTolerance, 0, len - 1);
+
+ var i,
+ newPoints = [];
+
+ for (i = 0; i < len; i++) {
+ if (markers[i]) {
+ newPoints.push(points[i]);
+ }
+ }
+
+ return newPoints;
+ },
+
+ _simplifyDPStep: function (points, markers, sqTolerance, first, last) {
+
+ var maxSqDist = 0,
+ index, i, sqDist;
+
+ for (i = first + 1; i <= last - 1; i++) {
+ sqDist = this._sqClosestPointOnSegment(points[i], points[first], points[last], true);
+
+ if (sqDist > maxSqDist) {
+ index = i;
+ maxSqDist = sqDist;
+ }
+ }
+
+ if (maxSqDist > sqTolerance) {
+ markers[index] = 1;
+
+ this._simplifyDPStep(points, markers, sqTolerance, first, index);
+ this._simplifyDPStep(points, markers, sqTolerance, index, last);
+ }
+ },
+
+ // reduce points that are too close to each other to a single point
+ _reducePoints: function (points, sqTolerance) {
+ var reducedPoints = [points[0]];
+
+ for (var i = 1, prev = 0, len = points.length; i < len; i++) {
+ if (this._sqDist(points[i], points[prev]) > sqTolerance) {
+ reducedPoints.push(points[i]);
+ prev = i;
+ }
+ }
+ if (prev < len - 1) {
+ reducedPoints.push(points[len - 1]);
+ }
+ return reducedPoints;
+ },
+
+ // Cohen-Sutherland line clipping algorithm.
+ // Used to avoid rendering parts of a polyline that are not currently visible.
+
+ clipSegment: function (a, b, bounds, useLastCode) {
+ var codeA = useLastCode ? this._lastCode : this._getBitCode(a, bounds),
+ codeB = this._getBitCode(b, bounds),
+
+ codeOut, p, newCode;
+
+ // save 2nd code to avoid calculating it on the next segment
+ this._lastCode = codeB;
+
+ while (true) {
+ // if a,b is inside the clip window (trivial accept)
+ if (!(codeA | codeB)) {
+ return [a, b];
+ // if a,b is outside the clip window (trivial reject)
+ } else if (codeA & codeB) {
+ return false;
+ // other cases
+ } else {
+ codeOut = codeA || codeB;
+ p = this._getEdgeIntersection(a, b, codeOut, bounds);
+ newCode = this._getBitCode(p, bounds);
+
+ if (codeOut === codeA) {
+ a = p;
+ codeA = newCode;
+ } else {
+ b = p;
+ codeB = newCode;
+ }
+ }
+ }
+ },
+
+ _getEdgeIntersection: function (a, b, code, bounds) {
+ var dx = b.x - a.x,
+ dy = b.y - a.y,
+ min = bounds.min,
+ max = bounds.max;
+
+ if (code & 8) { // top
+ return new L.Point(a.x + dx * (max.y - a.y) / dy, max.y);
+ } else if (code & 4) { // bottom
+ return new L.Point(a.x + dx * (min.y - a.y) / dy, min.y);
+ } else if (code & 2) { // right
+ return new L.Point(max.x, a.y + dy * (max.x - a.x) / dx);
+ } else if (code & 1) { // left
+ return new L.Point(min.x, a.y + dy * (min.x - a.x) / dx);
+ }
+ },
+
+ _getBitCode: function (/*Point*/ p, bounds) {
+ var code = 0;
+
+ if (p.x < bounds.min.x) { // left
+ code |= 1;
+ } else if (p.x > bounds.max.x) { // right
+ code |= 2;
+ }
+ if (p.y < bounds.min.y) { // bottom
+ code |= 4;
+ } else if (p.y > bounds.max.y) { // top
+ code |= 8;
+ }
+
+ return code;
+ },
+
+ // square distance (to avoid unnecessary Math.sqrt calls)
+ _sqDist: function (p1, p2) {
+ var dx = p2.x - p1.x,
+ dy = p2.y - p1.y;
+ return dx * dx + dy * dy;
+ },
+
+ // return closest point on segment or distance to that point
+ _sqClosestPointOnSegment: function (p, p1, p2, sqDist) {
+ var x = p1.x,
+ y = p1.y,
+ dx = p2.x - x,
+ dy = p2.y - y,
+ dot = dx * dx + dy * dy,
+ t;
+
+ if (dot > 0) {
+ t = ((p.x - x) * dx + (p.y - y) * dy) / dot;
+
+ if (t > 1) {
+ x = p2.x;
+ y = p2.y;
+ } else if (t > 0) {
+ x += dx * t;
+ y += dy * t;
+ }
+ }
+
+ dx = p.x - x;
+ dy = p.y - y;
+
+ return sqDist ? dx * dx + dy * dy : new L.Point(x, y);
+ }
+};
+
+
+/*
+ * L.Polyline is used to display polylines on a map.
+ */
+
+L.Polyline = L.Path.extend({
+ initialize: function (latlngs, options) {
+ L.Path.prototype.initialize.call(this, options);
+
+ this._latlngs = this._convertLatLngs(latlngs);
+ },
+
+ options: {
+ // how much to simplify the polyline on each zoom level
+ // more = better performance and smoother look, less = more accurate
+ smoothFactor: 1.0,
+ noClip: false
+ },
+
+ projectLatlngs: function () {
+ this._originalPoints = [];
+
+ for (var i = 0, len = this._latlngs.length; i < len; i++) {
+ this._originalPoints[i] = this._map.latLngToLayerPoint(this._latlngs[i]);
+ }
+ },
+
+ getPathString: function () {
+ for (var i = 0, len = this._parts.length, str = ''; i < len; i++) {
+ str += this._getPathPartStr(this._parts[i]);
+ }
+ return str;
+ },
+
+ getLatLngs: function () {
+ return this._latlngs;
+ },
+
+ setLatLngs: function (latlngs) {
+ this._latlngs = this._convertLatLngs(latlngs);
+ return this.redraw();
+ },
+
+ addLatLng: function (latlng) {
+ this._latlngs.push(L.latLng(latlng));
+ return this.redraw();
+ },
+
+ spliceLatLngs: function () { // (Number index, Number howMany)
+ var removed = [].splice.apply(this._latlngs, arguments);
+ this._convertLatLngs(this._latlngs, true);
+ this.redraw();
+ return removed;
+ },
+
+ closestLayerPoint: function (p) {
+ var minDistance = Infinity, parts = this._parts, p1, p2, minPoint = null;
+
+ for (var j = 0, jLen = parts.length; j < jLen; j++) {
+ var points = parts[j];
+ for (var i = 1, len = points.length; i < len; i++) {
+ p1 = points[i - 1];
+ p2 = points[i];
+ var sqDist = L.LineUtil._sqClosestPointOnSegment(p, p1, p2, true);
+ if (sqDist < minDistance) {
+ minDistance = sqDist;
+ minPoint = L.LineUtil._sqClosestPointOnSegment(p, p1, p2);
+ }
+ }
+ }
+ if (minPoint) {
+ minPoint.distance = Math.sqrt(minDistance);
+ }
+ return minPoint;
+ },
+
+ getBounds: function () {
+ return new L.LatLngBounds(this.getLatLngs());
+ },
+
+ _convertLatLngs: function (latlngs, overwrite) {
+ var i, len, target = overwrite ? latlngs : [];
+
+ for (i = 0, len = latlngs.length; i < len; i++) {
+ if (L.Util.isArray(latlngs[i]) && typeof latlngs[i][0] !== 'number') {
+ return;
+ }
+ target[i] = L.latLng(latlngs[i]);
+ }
+ return target;
+ },
+
+ _initEvents: function () {
+ L.Path.prototype._initEvents.call(this);
+ },
+
+ _getPathPartStr: function (points) {
+ var round = L.Path.VML;
+
+ for (var j = 0, len2 = points.length, str = '', p; j < len2; j++) {
+ p = points[j];
+ if (round) {
+ p._round();
+ }
+ str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
+ }
+ return str;
+ },
+
+ _clipPoints: function () {
+ var points = this._originalPoints,
+ len = points.length,
+ i, k, segment;
+
+ if (this.options.noClip) {
+ this._parts = [points];
+ return;
+ }
+
+ this._parts = [];
+
+ var parts = this._parts,
+ vp = this._map._pathViewport,
+ lu = L.LineUtil;
+
+ for (i = 0, k = 0; i < len - 1; i++) {
+ segment = lu.clipSegment(points[i], points[i + 1], vp, i);
+ if (!segment) {
+ continue;
+ }
+
+ parts[k] = parts[k] || [];
+ parts[k].push(segment[0]);
+
+ // if segment goes out of screen, or it's the last one, it's the end of the line part
+ if ((segment[1] !== points[i + 1]) || (i === len - 2)) {
+ parts[k].push(segment[1]);
+ k++;
+ }
+ }
+ },
+
+ // simplify each clipped part of the polyline
+ _simplifyPoints: function () {
+ var parts = this._parts,
+ lu = L.LineUtil;
+
+ for (var i = 0, len = parts.length; i < len; i++) {
+ parts[i] = lu.simplify(parts[i], this.options.smoothFactor);
+ }
+ },
+
+ _updatePath: function () {
+ if (!this._map) { return; }
+
+ this._clipPoints();
+ this._simplifyPoints();
+
+ L.Path.prototype._updatePath.call(this);
+ }
+});
+
+L.polyline = function (latlngs, options) {
+ return new L.Polyline(latlngs, options);
+};
+
+
+/*
+ * L.PolyUtil contains utility functions for polygons (clipping, etc.).
+ */
+
+/*jshint bitwise:false */ // allow bitwise operations here
+
+L.PolyUtil = {};
+
+/*
+ * Sutherland-Hodgeman polygon clipping algorithm.
+ * Used to avoid rendering parts of a polygon that are not currently visible.
+ */
+L.PolyUtil.clipPolygon = function (points, bounds) {
+ var clippedPoints,
+ edges = [1, 4, 2, 8],
+ i, j, k,
+ a, b,
+ len, edge, p,
+ lu = L.LineUtil;
+
+ for (i = 0, len = points.length; i < len; i++) {
+ points[i]._code = lu._getBitCode(points[i], bounds);
+ }
+
+ // for each edge (left, bottom, right, top)
+ for (k = 0; k < 4; k++) {
+ edge = edges[k];
+ clippedPoints = [];
+
+ for (i = 0, len = points.length, j = len - 1; i < len; j = i++) {
+ a = points[i];
+ b = points[j];
+
+ // if a is inside the clip window
+ if (!(a._code & edge)) {
+ // if b is outside the clip window (a->b goes out of screen)
+ if (b._code & edge) {
+ p = lu._getEdgeIntersection(b, a, edge, bounds);
+ p._code = lu._getBitCode(p, bounds);
+ clippedPoints.push(p);
+ }
+ clippedPoints.push(a);
+
+ // else if b is inside the clip window (a->b enters the screen)
+ } else if (!(b._code & edge)) {
+ p = lu._getEdgeIntersection(b, a, edge, bounds);
+ p._code = lu._getBitCode(p, bounds);
+ clippedPoints.push(p);
+ }
+ }
+ points = clippedPoints;
+ }
+
+ return points;
+};
+
+
+/*
+ * L.Polygon is used to display polygons on a map.
+ */
+
+L.Polygon = L.Polyline.extend({
+ options: {
+ fill: true
+ },
+
+ initialize: function (latlngs, options) {
+ var i, len, hole;
+
+ L.Polyline.prototype.initialize.call(this, latlngs, options);
+
+ if (latlngs && L.Util.isArray(latlngs[0]) && (typeof latlngs[0][0] !== 'number')) {
+ this._latlngs = this._convertLatLngs(latlngs[0]);
+ this._holes = latlngs.slice(1);
+
+ for (i = 0, len = this._holes.length; i < len; i++) {
+ hole = this._holes[i] = this._convertLatLngs(this._holes[i]);
+ if (hole[0].equals(hole[hole.length - 1])) {
+ hole.pop();
+ }
+ }
+ }
+
+ // filter out last point if its equal to the first one
+ latlngs = this._latlngs;
+
+ if (latlngs.length >= 2 && latlngs[0].equals(latlngs[latlngs.length - 1])) {
+ latlngs.pop();
+ }
+ },
+
+ projectLatlngs: function () {
+ L.Polyline.prototype.projectLatlngs.call(this);
+
+ // project polygon holes points
+ // TODO move this logic to Polyline to get rid of duplication
+ this._holePoints = [];
+
+ if (!this._holes) { return; }
+
+ var i, j, len, len2;
+
+ for (i = 0, len = this._holes.length; i < len; i++) {
+ this._holePoints[i] = [];
+
+ for (j = 0, len2 = this._holes[i].length; j < len2; j++) {
+ this._holePoints[i][j] = this._map.latLngToLayerPoint(this._holes[i][j]);
+ }
+ }
+ },
+
+ _clipPoints: function () {
+ var points = this._originalPoints,
+ newParts = [];
+
+ this._parts = [points].concat(this._holePoints);
+
+ if (this.options.noClip) { return; }
+
+ for (var i = 0, len = this._parts.length; i < len; i++) {
+ var clipped = L.PolyUtil.clipPolygon(this._parts[i], this._map._pathViewport);
+ if (clipped.length) {
+ newParts.push(clipped);
+ }
+ }
+
+ this._parts = newParts;
+ },
+
+ _getPathPartStr: function (points) {
+ var str = L.Polyline.prototype._getPathPartStr.call(this, points);
+ return str + (L.Browser.svg ? 'z' : 'x');
+ }
+});
+
+L.polygon = function (latlngs, options) {
+ return new L.Polygon(latlngs, options);
+};
+
+
+/*
+ * Contains L.MultiPolyline and L.MultiPolygon layers.
+ */
+
+(function () {
+ function createMulti(Klass) {
+
+ return L.FeatureGroup.extend({
+
+ initialize: function (latlngs, options) {
+ this._layers = {};
+ this._options = options;
+ this.setLatLngs(latlngs);
+ },
+
+ setLatLngs: function (latlngs) {
+ var i = 0,
+ len = latlngs.length;
+
+ this.eachLayer(function (layer) {
+ if (i < len) {
+ layer.setLatLngs(latlngs[i++]);
+ } else {
+ this.removeLayer(layer);
+ }
+ }, this);
+
+ while (i < len) {
+ this.addLayer(new Klass(latlngs[i++], this._options));
+ }
+
+ return this;
+ },
+
+ getLatLngs: function () {
+ var latlngs = [];
+
+ this.eachLayer(function (layer) {
+ latlngs.push(layer.getLatLngs());
+ });
+
+ return latlngs;
+ }
+ });
+ }
+
+ L.MultiPolyline = createMulti(L.Polyline);
+ L.MultiPolygon = createMulti(L.Polygon);
+
+ L.multiPolyline = function (latlngs, options) {
+ return new L.MultiPolyline(latlngs, options);
+ };
+
+ L.multiPolygon = function (latlngs, options) {
+ return new L.MultiPolygon(latlngs, options);
+ };
+}());
+
+
+/*
+ * L.Rectangle extends Polygon and creates a rectangle when passed a LatLngBounds object.
+ */
+
+L.Rectangle = L.Polygon.extend({
+ initialize: function (latLngBounds, options) {
+ L.Polygon.prototype.initialize.call(this, this._boundsToLatLngs(latLngBounds), options);
+ },
+
+ setBounds: function (latLngBounds) {
+ this.setLatLngs(this._boundsToLatLngs(latLngBounds));
+ },
+
+ _boundsToLatLngs: function (latLngBounds) {
+ latLngBounds = L.latLngBounds(latLngBounds);
+ return [
+ latLngBounds.getSouthWest(),
+ latLngBounds.getNorthWest(),
+ latLngBounds.getNorthEast(),
+ latLngBounds.getSouthEast()
+ ];
+ }
+});
+
+L.rectangle = function (latLngBounds, options) {
+ return new L.Rectangle(latLngBounds, options);
+};
+
+
+/*
+ * L.Circle is a circle overlay (with a certain radius in meters).
+ */
+
+L.Circle = L.Path.extend({
+ initialize: function (latlng, radius, options) {
+ L.Path.prototype.initialize.call(this, options);
+
+ this._latlng = L.latLng(latlng);
+ this._mRadius = radius;
+ },
+
+ options: {
+ fill: true
+ },
+
+ setLatLng: function (latlng) {
+ this._latlng = L.latLng(latlng);
+ return this.redraw();
+ },
+
+ setRadius: function (radius) {
+ this._mRadius = radius;
+ return this.redraw();
+ },
+
+ projectLatlngs: function () {
+ var lngRadius = this._getLngRadius(),
+ latlng = this._latlng,
+ pointLeft = this._map.latLngToLayerPoint([latlng.lat, latlng.lng - lngRadius]);
+
+ this._point = this._map.latLngToLayerPoint(latlng);
+ this._radius = Math.max(this._point.x - pointLeft.x, 1);
+ },
+
+ getBounds: function () {
+ var lngRadius = this._getLngRadius(),
+ latRadius = (this._mRadius / 40075017) * 360,
+ latlng = this._latlng;
+
+ return new L.LatLngBounds(
+ [latlng.lat - latRadius, latlng.lng - lngRadius],
+ [latlng.lat + latRadius, latlng.lng + lngRadius]);
+ },
+
+ getLatLng: function () {
+ return this._latlng;
+ },
+
+ getPathString: function () {
+ var p = this._point,
+ r = this._radius;
+
+ if (this._checkIfEmpty()) {
+ return '';
+ }
+
+ if (L.Browser.svg) {
+ return 'M' + p.x + ',' + (p.y - r) +
+ 'A' + r + ',' + r + ',0,1,1,' +
+ (p.x - 0.1) + ',' + (p.y - r) + ' z';
+ } else {
+ p._round();
+ r = Math.round(r);
+ return 'AL ' + p.x + ',' + p.y + ' ' + r + ',' + r + ' 0,' + (65535 * 360);
+ }
+ },
+
+ getRadius: function () {
+ return this._mRadius;
+ },
+
+ // TODO Earth hardcoded, move into projection code!
+
+ _getLatRadius: function () {
+ return (this._mRadius / 40075017) * 360;
+ },
+
+ _getLngRadius: function () {
+ return this._getLatRadius() / Math.cos(L.LatLng.DEG_TO_RAD * this._latlng.lat);
+ },
+
+ _checkIfEmpty: function () {
+ if (!this._map) {
+ return false;
+ }
+ var vp = this._map._pathViewport,
+ r = this._radius,
+ p = this._point;
+
+ return p.x - r > vp.max.x || p.y - r > vp.max.y ||
+ p.x + r < vp.min.x || p.y + r < vp.min.y;
+ }
+});
+
+L.circle = function (latlng, radius, options) {
+ return new L.Circle(latlng, radius, options);
+};
+
+
+/*
+ * L.CircleMarker is a circle overlay with a permanent pixel radius.
+ */
+
+L.CircleMarker = L.Circle.extend({
+ options: {
+ radius: 10,
+ weight: 2
+ },
+
+ initialize: function (latlng, options) {
+ L.Circle.prototype.initialize.call(this, latlng, null, options);
+ this._radius = this.options.radius;
+ },
+
+ projectLatlngs: function () {
+ this._point = this._map.latLngToLayerPoint(this._latlng);
+ },
+
+ _updateStyle : function () {
+ L.Circle.prototype._updateStyle.call(this);
+ this.setRadius(this.options.radius);
+ },
+
+ setRadius: function (radius) {
+ this.options.radius = this._radius = radius;
+ return this.redraw();
+ }
+});
+
+L.circleMarker = function (latlng, options) {
+ return new L.CircleMarker(latlng, options);
+};
+
+
+/*
+ * Extends L.Polyline to be able to manually detect clicks on Canvas-rendered polylines.
+ */
+
+L.Polyline.include(!L.Path.CANVAS ? {} : {
+ _containsPoint: function (p, closed) {
+ var i, j, k, len, len2, dist, part,
+ w = this.options.weight / 2;
+
+ if (L.Browser.touch) {
+ w += 10; // polyline click tolerance on touch devices
+ }
+
+ for (i = 0, len = this._parts.length; i < len; i++) {
+ part = this._parts[i];
+ for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
+ if (!closed && (j === 0)) {
+ continue;
+ }
+
+ dist = L.LineUtil.pointToSegmentDistance(p, part[k], part[j]);
+
+ if (dist <= w) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+});
+
+
+/*
+ * Extends L.Polygon to be able to manually detect clicks on Canvas-rendered polygons.
+ */
+
+L.Polygon.include(!L.Path.CANVAS ? {} : {
+ _containsPoint: function (p) {
+ var inside = false,
+ part, p1, p2,
+ i, j, k,
+ len, len2;
+
+ // TODO optimization: check if within bounds first
+
+ if (L.Polyline.prototype._containsPoint.call(this, p, true)) {
+ // click on polygon border
+ return true;
+ }
+
+ // ray casting algorithm for detecting if point is in polygon
+
+ for (i = 0, len = this._parts.length; i < len; i++) {
+ part = this._parts[i];
+
+ for (j = 0, len2 = part.length, k = len2 - 1; j < len2; k = j++) {
+ p1 = part[j];
+ p2 = part[k];
+
+ if (((p1.y > p.y) !== (p2.y > p.y)) &&
+ (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {
+ inside = !inside;
+ }
+ }
+ }
+
+ return inside;
+ }
+});
+
+
+/*
+ * Extends L.Circle with Canvas-specific code.
+ */
+
+L.Circle.include(!L.Path.CANVAS ? {} : {
+ _drawPath: function () {
+ var p = this._point;
+ this._ctx.beginPath();
+ this._ctx.arc(p.x, p.y, this._radius, 0, Math.PI * 2, false);
+ },
+
+ _containsPoint: function (p) {
+ var center = this._point,
+ w2 = this.options.stroke ? this.options.weight / 2 : 0;
+
+ return (p.distanceTo(center) <= this._radius + w2);
+ }
+});
+
+
+/*
+ * CircleMarker canvas specific drawing parts.
+ */
+
+L.CircleMarker.include(!L.Path.CANVAS ? {} : {
+ _updateStyle: function () {
+ L.Path.prototype._updateStyle.call(this);
+ }
+});
+
+
+/*
+ * L.GeoJSON turns any GeoJSON data into a Leaflet layer.
+ */
+
+L.GeoJSON = L.FeatureGroup.extend({
+
+ initialize: function (geojson, options) {
+ L.setOptions(this, options);
+
+ this._layers = {};
+
+ if (geojson) {
+ this.addData(geojson);
+ }
+ },
+
+ addData: function (geojson) {
+ var features = L.Util.isArray(geojson) ? geojson : geojson.features,
+ i, len, feature;
+
+ if (features) {
+ for (i = 0, len = features.length; i < len; i++) {
+ // Only add this if geometry or geometries are set and not null
+ feature = features[i];
+ if (feature.geometries || feature.geometry || feature.features || feature.coordinates) {
+ this.addData(features[i]);
+ }
+ }
+ return this;
+ }
+
+ var options = this.options;
+
+ if (options.filter && !options.filter(geojson)) { return; }
+
+ var layer = L.GeoJSON.geometryToLayer(geojson, options.pointToLayer, options.coordsToLatLng);
+ layer.feature = L.GeoJSON.asFeature(geojson);
+
+ layer.defaultOptions = layer.options;
+ this.resetStyle(layer);
+
+ if (options.onEachFeature) {
+ options.onEachFeature(geojson, layer);
+ }
+
+ return this.addLayer(layer);
+ },
+
+ resetStyle: function (layer) {
+ var style = this.options.style;
+ if (style) {
+ // reset any custom styles
+ L.Util.extend(layer.options, layer.defaultOptions);
+
+ this._setLayerStyle(layer, style);
+ }
+ },
+
+ setStyle: function (style) {
+ this.eachLayer(function (layer) {
+ this._setLayerStyle(layer, style);
+ }, this);
+ },
+
+ _setLayerStyle: function (layer, style) {
+ if (typeof style === 'function') {
+ style = style(layer.feature);
+ }
+ if (layer.setStyle) {
+ layer.setStyle(style);
+ }
+ }
+});
+
+L.extend(L.GeoJSON, {
+ geometryToLayer: function (geojson, pointToLayer, coordsToLatLng) {
+ var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
+ coords = geometry.coordinates,
+ layers = [],
+ latlng, latlngs, i, len, layer;
+
+ coordsToLatLng = coordsToLatLng || this.coordsToLatLng;
+
+ switch (geometry.type) {
+ case 'Point':
+ latlng = coordsToLatLng(coords);
+ return pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
+
+ case 'MultiPoint':
+ for (i = 0, len = coords.length; i < len; i++) {
+ latlng = coordsToLatLng(coords[i]);
+ layer = pointToLayer ? pointToLayer(geojson, latlng) : new L.Marker(latlng);
+ layers.push(layer);
+ }
+ return new L.FeatureGroup(layers);
+
+ case 'LineString':
+ latlngs = this.coordsToLatLngs(coords, 0, coordsToLatLng);
+ return new L.Polyline(latlngs);
+
+ case 'Polygon':
+ latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
+ return new L.Polygon(latlngs);
+
+ case 'MultiLineString':
+ latlngs = this.coordsToLatLngs(coords, 1, coordsToLatLng);
+ return new L.MultiPolyline(latlngs);
+
+ case 'MultiPolygon':
+ latlngs = this.coordsToLatLngs(coords, 2, coordsToLatLng);
+ return new L.MultiPolygon(latlngs);
+
+ case 'GeometryCollection':
+ for (i = 0, len = geometry.geometries.length; i < len; i++) {
+
+ layer = this.geometryToLayer({
+ geometry: geometry.geometries[i],
+ type: 'Feature',
+ properties: geojson.properties
+ }, pointToLayer, coordsToLatLng);
+
+ layers.push(layer);
+ }
+ return new L.FeatureGroup(layers);
+
+ default:
+ throw new Error('Invalid GeoJSON object.');
+ }
+ },
+
+ coordsToLatLng: function (coords) { // (Array[, Boolean]) -> LatLng
+ return new L.LatLng(coords[1], coords[0]);
+ },
+
+ coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { // (Array[, Number, Function]) -> Array
+ var latlng, i, len,
+ latlngs = [];
+
+ for (i = 0, len = coords.length; i < len; i++) {
+ latlng = levelsDeep ?
+ this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) :
+ (coordsToLatLng || this.coordsToLatLng)(coords[i]);
+
+ latlngs.push(latlng);
+ }
+
+ return latlngs;
+ },
+
+ latLngToCoords: function (latLng) {
+ return [latLng.lng, latLng.lat];
+ },
+
+ latLngsToCoords: function (latLngs) {
+ var coords = [];
+
+ for (var i = 0, len = latLngs.length; i < len; i++) {
+ coords.push(L.GeoJSON.latLngToCoords(latLngs[i]));
+ }
+
+ return coords;
+ },
+
+ getFeature: function (layer, newGeometry) {
+ return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry);
+ },
+
+ asFeature: function (geoJSON) {
+ if (geoJSON.type === 'Feature') {
+ return geoJSON;
+ }
+
+ return {
+ type: 'Feature',
+ properties: {},
+ geometry: geoJSON
+ };
+ }
+});
+
+var PointToGeoJSON = {
+ toGeoJSON: function () {
+ return L.GeoJSON.getFeature(this, {
+ type: 'Point',
+ coordinates: L.GeoJSON.latLngToCoords(this.getLatLng())
+ });
+ }
+};
+
+L.Marker.include(PointToGeoJSON);
+L.Circle.include(PointToGeoJSON);
+L.CircleMarker.include(PointToGeoJSON);
+
+L.Polyline.include({
+ toGeoJSON: function () {
+ return L.GeoJSON.getFeature(this, {
+ type: 'LineString',
+ coordinates: L.GeoJSON.latLngsToCoords(this.getLatLngs())
+ });
+ }
+});
+
+L.Polygon.include({
+ toGeoJSON: function () {
+ var coords = [L.GeoJSON.latLngsToCoords(this.getLatLngs())],
+ i, len, hole;
+
+ coords[0].push(coords[0][0]);
+
+ if (this._holes) {
+ for (i = 0, len = this._holes.length; i < len; i++) {
+ hole = L.GeoJSON.latLngsToCoords(this._holes[i]);
+ hole.push(hole[0]);
+ coords.push(hole);
+ }
+ }
+
+ return L.GeoJSON.getFeature(this, {
+ type: 'Polygon',
+ coordinates: coords
+ });
+ }
+});
+
+(function () {
+ function includeMulti(Klass, type) {
+ Klass.include({
+ toGeoJSON: function () {
+ var coords = [];
+
+ this.eachLayer(function (layer) {
+ coords.push(layer.toGeoJSON().geometry.coordinates);
+ });
+
+ return L.GeoJSON.getFeature(this, {
+ type: type,
+ coordinates: coords
+ });
+ }
+ });
+ }
+
+ includeMulti(L.MultiPolyline, 'MultiLineString');
+ includeMulti(L.MultiPolygon, 'MultiPolygon');
+}());
+
+L.LayerGroup.include({
+ toGeoJSON: function () {
+ var features = [];
+
+ this.eachLayer(function (layer) {
+ if (layer.toGeoJSON) {
+ features.push(L.GeoJSON.asFeature(layer.toGeoJSON()));
+ }
+ });
+
+ return {
+ type: 'FeatureCollection',
+ features: features
+ };
+ }
+});
+
+L.geoJson = function (geojson, options) {
+ return new L.GeoJSON(geojson, options);
+};
+
+
+/*
+ * L.DomEvent contains functions for working with DOM events.
+ */
+
+L.DomEvent = {
+ /* inspired by John Resig, Dean Edwards and YUI addEvent implementations */
+ addListener: function (obj, type, fn, context) { // (HTMLElement, String, Function[, Object])
+
+ var id = L.stamp(fn),
+ key = '_leaflet_' + type + id,
+ handler, originalHandler, newType;
+
+ if (obj[key]) { return this; }
+
+ handler = function (e) {
+ return fn.call(context || obj, e || L.DomEvent._getEvent());
+ };
+
+ if (L.Browser.msTouch && type.indexOf('touch') === 0) {
+ return this.addMsTouchListener(obj, type, handler, id);
+ }
+ if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
+ this.addDoubleTapListener(obj, handler, id);
+ }
+
+ if ('addEventListener' in obj) {
+
+ if (type === 'mousewheel') {
+ obj.addEventListener('DOMMouseScroll', handler, false);
+ obj.addEventListener(type, handler, false);
+
+ } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
+
+ originalHandler = handler;
+ newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
+
+ handler = function (e) {
+ if (!L.DomEvent._checkMouse(obj, e)) { return; }
+ return originalHandler(e);
+ };
+
+ obj.addEventListener(newType, handler, false);
+
+ } else if (type === 'click' && L.Browser.android) {
+ originalHandler = handler;
+ handler = function (e) {
+ return L.DomEvent._filterClick(e, originalHandler);
+ };
+
+ obj.addEventListener(type, handler, false);
+ } else {
+ obj.addEventListener(type, handler, false);
+ }
+
+ } else if ('attachEvent' in obj) {
+ obj.attachEvent('on' + type, handler);
+ }
+
+ obj[key] = handler;
+
+ return this;
+ },
+
+ removeListener: function (obj, type, fn) { // (HTMLElement, String, Function)
+
+ var id = L.stamp(fn),
+ key = '_leaflet_' + type + id,
+ handler = obj[key];
+
+ if (!handler) { return this; }
+
+ if (L.Browser.msTouch && type.indexOf('touch') === 0) {
+ this.removeMsTouchListener(obj, type, id);
+ } else if (L.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
+ this.removeDoubleTapListener(obj, id);
+
+ } else if ('removeEventListener' in obj) {
+
+ if (type === 'mousewheel') {
+ obj.removeEventListener('DOMMouseScroll', handler, false);
+ obj.removeEventListener(type, handler, false);
+
+ } else if ((type === 'mouseenter') || (type === 'mouseleave')) {
+ obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
+ } else {
+ obj.removeEventListener(type, handler, false);
+ }
+ } else if ('detachEvent' in obj) {
+ obj.detachEvent('on' + type, handler);
+ }
+
+ obj[key] = null;
+
+ return this;
+ },
+
+ stopPropagation: function (e) {
+
+ if (e.stopPropagation) {
+ e.stopPropagation();
+ } else {
+ e.cancelBubble = true;
+ }
+ return this;
+ },
+
+ disableClickPropagation: function (el) {
+ var stop = L.DomEvent.stopPropagation;
+
+ for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
+ L.DomEvent.addListener(el, L.Draggable.START[i], stop);
+ }
+
+ return L.DomEvent
+ .addListener(el, 'click', L.DomEvent._fakeStop)
+ .addListener(el, 'dblclick', stop);
+ },
+
+ preventDefault: function (e) {
+
+ if (e.preventDefault) {
+ e.preventDefault();
+ } else {
+ e.returnValue = false;
+ }
+ return this;
+ },
+
+ stop: function (e) {
+ return L.DomEvent.preventDefault(e).stopPropagation(e);
+ },
+
+ getMousePosition: function (e, container) {
+
+ var ie7 = L.Browser.ie7,
+ body = document.body,
+ docEl = document.documentElement,
+ x = e.pageX ? e.pageX - body.scrollLeft - docEl.scrollLeft: e.clientX,
+ y = e.pageY ? e.pageY - body.scrollTop - docEl.scrollTop: e.clientY,
+ pos = new L.Point(x, y),
+ rect = container.getBoundingClientRect(),
+ left = rect.left - container.clientLeft,
+ top = rect.top - container.clientTop;
+
+ // webkit (and ie <= 7) handles RTL scrollLeft different to everyone else
+ // https://code.google.com/p/closure-library/source/browse/trunk/closure/goog/…
+ if (!L.DomUtil.documentIsLtr() && (L.Browser.webkit || ie7)) {
+ left += container.scrollWidth - container.clientWidth;
+
+ // ie7 shows the scrollbar by default and provides clientWidth counting it, so we
+ // need to add it back in if it is visible; scrollbar is on the left as we are RTL
+ if (ie7 && L.DomUtil.getStyle(container, 'overflow-y') !== 'hidden' &&
+ L.DomUtil.getStyle(container, 'overflow') !== 'hidden') {
+ left += 17;
+ }
+ }
+
+ return pos._subtract(new L.Point(left, top));
+ },
+
+ getWheelDelta: function (e) {
+
+ var delta = 0;
+
+ if (e.wheelDelta) {
+ delta = e.wheelDelta / 120;
+ }
+ if (e.detail) {
+ delta = -e.detail / 3;
+ }
+ return delta;
+ },
+
+ _skipEvents: {},
+
+ _fakeStop: function (e) {
+ // fakes stopPropagation by setting a special event flag, checked/reset with L.DomEvent._skipped(e)
+ L.DomEvent._skipEvents[e.type] = true;
+ },
+
+ _skipped: function (e) {
+ var skipped = this._skipEvents[e.type];
+ // reset when checking, as it's only used in map container and propagates outside of the map
+ this._skipEvents[e.type] = false;
+ return skipped;
+ },
+
+ // check if element really left/entered the event target (for mouseenter/mouseleave)
+ _checkMouse: function (el, e) {
+
+ var related = e.relatedTarget;
+
+ if (!related) { return true; }
+
+ try {
+ while (related && (related !== el)) {
+ related = related.parentNode;
+ }
+ } catch (err) {
+ return false;
+ }
+ return (related !== el);
+ },
+
+ _getEvent: function () { // evil magic for IE
+ /*jshint noarg:false */
+ var e = window.event;
+ if (!e) {
+ var caller = arguments.callee.caller;
+ while (caller) {
+ e = caller['arguments'][0];
+ if (e && window.Event === e.constructor) {
+ break;
+ }
+ caller = caller.caller;
+ }
+ }
+ return e;
+ },
+
+ // this is a horrible workaround for a bug in Android where a single touch triggers two click events
+ _filterClick: function (e, handler) {
+ var timeStamp = (e.timeStamp || e.originalEvent.timeStamp),
+ elapsed = L.DomEvent._lastClick && (timeStamp - L.DomEvent._lastClick);
+
+ // are they closer together than 1000ms yet more than 100ms?
+ // Android typically triggers them ~300ms apart while multiple listeners
+ // on the same event should be triggered far faster;
+ // or check if click is simulated on the element, and if it is, reject any non-simulated events
+
+ if ((elapsed && elapsed > 100 && elapsed < 1000) || (e.target._simulatedClick && !e._simulated)) {
+ L.DomEvent.stop(e);
+ return;
+ }
+ L.DomEvent._lastClick = timeStamp;
+
+ return handler(e);
+ }
+};
+
+L.DomEvent.on = L.DomEvent.addListener;
+L.DomEvent.off = L.DomEvent.removeListener;
+
+
+/*
+ * L.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
+ */
+
+L.Draggable = L.Class.extend({
+ includes: L.Mixin.Events,
+
+ statics: {
+ START: L.Browser.touch ? ['touchstart', 'mousedown'] : ['mousedown'],
+ END: {
+ mousedown: 'mouseup',
+ touchstart: 'touchend',
+ MSPointerDown: 'touchend'
+ },
+ MOVE: {
+ mousedown: 'mousemove',
+ touchstart: 'touchmove',
+ MSPointerDown: 'touchmove'
+ }
+ },
+
+ initialize: function (element, dragStartTarget) {
+ this._element = element;
+ this._dragStartTarget = dragStartTarget || element;
+ },
+
+ enable: function () {
+ if (this._enabled) { return; }
+
+ for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
+ L.DomEvent.on(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
+ }
+
+ this._enabled = true;
+ },
+
+ disable: function () {
+ if (!this._enabled) { return; }
+
+ for (var i = L.Draggable.START.length - 1; i >= 0; i--) {
+ L.DomEvent.off(this._dragStartTarget, L.Draggable.START[i], this._onDown, this);
+ }
+
+ this._enabled = false;
+ this._moved = false;
+ },
+
+ _onDown: function (e) {
+ if (e.shiftKey || ((e.which !== 1) && (e.button !== 1) && !e.touches)) { return; }
+
+ L.DomEvent
+ .stopPropagation(e);
+
+ if (L.Draggable._disabled) { return; }
+
+ L.DomUtil.disableImageDrag();
+ L.DomUtil.disableTextSelection();
+
+ var first = e.touches ? e.touches[0] : e,
+ el = first.target;
+
+ // if touching a link, highlight it
+ if (L.Browser.touch && el.tagName.toLowerCase() === 'a') {
+ L.DomUtil.addClass(el, 'leaflet-active');
+ }
+
+ this._moved = false;
+
+ if (this._moving) { return; }
+
+ this._startPoint = new L.Point(first.clientX, first.clientY);
+ this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
+
+ L.DomEvent
+ .on(document, L.Draggable.MOVE[e.type], this._onMove, this)
+ .on(document, L.Draggable.END[e.type], this._onUp, this);
+ },
+
+ _onMove: function (e) {
+ if (e.touches && e.touches.length > 1) { return; }
+
+ var first = (e.touches && e.touches.length === 1 ? e.touches[0] : e),
+ newPoint = new L.Point(first.clientX, first.clientY),
+ offset = newPoint.subtract(this._startPoint);
+
+ if (!offset.x && !offset.y) { return; }
+
+ L.DomEvent.preventDefault(e);
+
+ if (!this._moved) {
+ this.fire('dragstart');
+
+ this._moved = true;
+ this._startPos = L.DomUtil.getPosition(this._element).subtract(offset);
+
+ if (!L.Browser.touch) {
+ L.DomUtil.addClass(document.body, 'leaflet-dragging');
+ }
+ }
+
+ this._newPos = this._startPos.add(offset);
+ this._moving = true;
+
+ L.Util.cancelAnimFrame(this._animRequest);
+ this._animRequest = L.Util.requestAnimFrame(this._updatePosition, this, true, this._dragStartTarget);
+ },
+
+ _updatePosition: function () {
+ this.fire('predrag');
+ L.DomUtil.setPosition(this._element, this._newPos);
+ this.fire('drag');
+ },
+
+ _onUp: function () {
+ if (!L.Browser.touch) {
+ L.DomUtil.removeClass(document.body, 'leaflet-dragging');
+ }
+
+ for (var i in L.Draggable.MOVE) {
+ L.DomEvent
+ .off(document, L.Draggable.MOVE[i], this._onMove)
+ .off(document, L.Draggable.END[i], this._onUp);
+ }
+
+ L.DomUtil.enableImageDrag();
+ L.DomUtil.enableTextSelection();
+
+ if (this._moved) {
+ // ensure drag is not fired after dragend
+ L.Util.cancelAnimFrame(this._animRequest);
+
+ this.fire('dragend');
+ }
+
+ this._moving = false;
+ }
+});
+
+
+/*
+ L.Handler is a base class for handler classes that are used internally to inject
+ interaction features like dragging to classes like Map and Marker.
+*/
+
+L.Handler = L.Class.extend({
+ initialize: function (map) {
+ this._map = map;
+ },
+
+ enable: function () {
+ if (this._enabled) { return; }
+
+ this._enabled = true;
+ this.addHooks();
+ },
+
+ disable: function () {
+ if (!this._enabled) { return; }
+
+ this._enabled = false;
+ this.removeHooks();
+ },
+
+ enabled: function () {
+ return !!this._enabled;
+ }
+});
+
+
+/*
+ * L.Handler.MapDrag is used to make the map draggable (with panning inertia), enabled by default.
+ */
+
+L.Map.mergeOptions({
+ dragging: true,
+
+ inertia: !L.Browser.android23,
+ inertiaDeceleration: 3400, // px/s^2
+ inertiaMaxSpeed: Infinity, // px/s
+ inertiaThreshold: L.Browser.touch ? 32 : 18, // ms
+ easeLinearity: 0.25,
+
+ // TODO refactor, move to CRS
+ worldCopyJump: false
+});
+
+L.Map.Drag = L.Handler.extend({
+ addHooks: function () {
+ if (!this._draggable) {
+ var map = this._map;
+
+ this._draggable = new L.Draggable(map._mapPane, map._container);
+
+ this._draggable.on({
+ 'dragstart': this._onDragStart,
+ 'drag': this._onDrag,
+ 'dragend': this._onDragEnd
+ }, this);
+
+ if (map.options.worldCopyJump) {
+ this._draggable.on('predrag', this._onPreDrag, this);
+ map.on('viewreset', this._onViewReset, this);
+
+ this._onViewReset();
+ }
+ }
+ this._draggable.enable();
+ },
+
+ removeHooks: function () {
+ this._draggable.disable();
+ },
+
+ moved: function () {
+ return this._draggable && this._draggable._moved;
+ },
+
+ _onDragStart: function () {
+ var map = this._map;
+
+ if (map._panAnim) {
+ map._panAnim.stop();
+ }
+
+ map
+ .fire('movestart')
+ .fire('dragstart');
+
+ if (map.options.inertia) {
+ this._positions = [];
+ this._times = [];
+ }
+ },
+
+ _onDrag: function () {
+ if (this._map.options.inertia) {
+ var time = this._lastTime = +new Date(),
+ pos = this._lastPos = this._draggable._newPos;
+
+ this._positions.push(pos);
+ this._times.push(time);
+
+ if (time - this._times[0] > 200) {
+ this._positions.shift();
+ this._times.shift();
+ }
+ }
+
+ this._map
+ .fire('move')
+ .fire('drag');
+ },
+
+ _onViewReset: function () {
+ // TODO fix hardcoded Earth values
+ var pxCenter = this._map.getSize()._divideBy(2),
+ pxWorldCenter = this._map.latLngToLayerPoint([0, 0]);
+
+ this._initialWorldOffset = pxWorldCenter.subtract(pxCenter).x;
+ this._worldWidth = this._map.project([0, 180]).x;
+ },
+
+ _onPreDrag: function () {
+ // TODO refactor to be able to adjust map pane position after zoom
+ var worldWidth = this._worldWidth,
+ halfWidth = Math.round(worldWidth / 2),
+ dx = this._initialWorldOffset,
+ x = this._draggable._newPos.x,
+ newX1 = (x - halfWidth + dx) % worldWidth + halfWidth - dx,
+ newX2 = (x + halfWidth + dx) % worldWidth - halfWidth - dx,
+ newX = Math.abs(newX1 + dx) < Math.abs(newX2 + dx) ? newX1 : newX2;
+
+ this._draggable._newPos.x = newX;
+ },
+
+ _onDragEnd: function () {
+ var map = this._map,
+ options = map.options,
+ delay = +new Date() - this._lastTime,
+
+ noInertia = !options.inertia || delay > options.inertiaThreshold || !this._positions[0];
+
+ map.fire('dragend');
+
+ if (noInertia) {
+ map.fire('moveend');
+
+ } else {
+
+ var direction = this._lastPos.subtract(this._positions[0]),
+ duration = (this._lastTime + delay - this._times[0]) / 1000,
+ ease = options.easeLinearity,
+
+ speedVector = direction.multiplyBy(ease / duration),
+ speed = speedVector.distanceTo([0, 0]),
+
+ limitedSpeed = Math.min(options.inertiaMaxSpeed, speed),
+ limitedSpeedVector = speedVector.multiplyBy(limitedSpeed / speed),
+
+ decelerationDuration = limitedSpeed / (options.inertiaDeceleration * ease),
+ offset = limitedSpeedVector.multiplyBy(-decelerationDuration / 2).round();
+
+ if (!offset.x || !offset.y) {
+ map.fire('moveend');
+
+ } else {
+ L.Util.requestAnimFrame(function () {
+ map.panBy(offset, {
+ duration: decelerationDuration,
+ easeLinearity: ease,
+ noMoveStart: true
+ });
+ });
+ }
+ }
+ }
+});
+
+L.Map.addInitHook('addHandler', 'dragging', L.Map.Drag);
+
+
+/*
+ * L.Handler.DoubleClickZoom is used to handle double-click zoom on the map, enabled by default.
+ */
+
+L.Map.mergeOptions({
+ doubleClickZoom: true
+});
+
+L.Map.DoubleClickZoom = L.Handler.extend({
+ addHooks: function () {
+ this._map.on('dblclick', this._onDoubleClick);
+ },
+
+ removeHooks: function () {
+ this._map.off('dblclick', this._onDoubleClick);
+ },
+
+ _onDoubleClick: function (e) {
+ this.setZoomAround(e.containerPoint, this._zoom + 1);
+ }
+});
+
+L.Map.addInitHook('addHandler', 'doubleClickZoom', L.Map.DoubleClickZoom);
+
+
+/*
+ * L.Handler.ScrollWheelZoom is used by L.Map to enable mouse scroll wheel zoom on the map.
+ */
+
+L.Map.mergeOptions({
+ scrollWheelZoom: true
+});
+
+L.Map.ScrollWheelZoom = L.Handler.extend({
+ addHooks: function () {
+ L.DomEvent.on(this._map._container, 'mousewheel', this._onWheelScroll, this);
+ L.DomEvent.on(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
+ this._delta = 0;
+ },
+
+ removeHooks: function () {
+ L.DomEvent.off(this._map._container, 'mousewheel', this._onWheelScroll);
+ L.DomEvent.off(this._map._container, 'MozMousePixelScroll', L.DomEvent.preventDefault);
+ },
+
+ _onWheelScroll: function (e) {
+ var delta = L.DomEvent.getWheelDelta(e);
+
+ this._delta += delta;
+ this._lastMousePos = this._map.mouseEventToContainerPoint(e);
+
+ if (!this._startTime) {
+ this._startTime = +new Date();
+ }
+
+ var left = Math.max(40 - (+new Date() - this._startTime), 0);
+
+ clearTimeout(this._timer);
+ this._timer = setTimeout(L.bind(this._performZoom, this), left);
+
+ L.DomEvent.preventDefault(e);
+ L.DomEvent.stopPropagation(e);
+ },
+
+ _performZoom: function () {
+ var map = this._map,
+ delta = this._delta,
+ zoom = map.getZoom();
+
+ delta = delta > 0 ? Math.ceil(delta) : Math.floor(delta);
+ delta = Math.max(Math.min(delta, 4), -4);
+ delta = map._limitZoom(zoom + delta) - zoom;
+
+ this._delta = 0;
+ this._startTime = null;
+
+ if (!delta) { return; }
+
+ map.setZoomAround(this._lastMousePos, zoom + delta);
+ }
+});
+
+L.Map.addInitHook('addHandler', 'scrollWheelZoom', L.Map.ScrollWheelZoom);
+
+
+/*
+ * Extends the event handling code with double tap support for mobile browsers.
+ */
+
+L.extend(L.DomEvent, {
+
+ _touchstart: L.Browser.msTouch ? 'MSPointerDown' : 'touchstart',
+ _touchend: L.Browser.msTouch ? 'MSPointerUp' : 'touchend',
+
+ // inspired by Zepto touch code by Thomas Fuchs
+ addDoubleTapListener: function (obj, handler, id) {
+ var last,
+ doubleTap = false,
+ delay = 250,
+ touch,
+ pre = '_leaflet_',
+ touchstart = this._touchstart,
+ touchend = this._touchend,
+ trackedTouches = [];
+
+ function onTouchStart(e) {
+ var count;
+
+ if (L.Browser.msTouch) {
+ trackedTouches.push(e.pointerId);
+ count = trackedTouches.length;
+ } else {
+ count = e.touches.length;
+ }
+ if (count > 1) {
+ return;
+ }
+
+ var now = Date.now(),
+ delta = now - (last || now);
+
+ touch = e.touches ? e.touches[0] : e;
+ doubleTap = (delta > 0 && delta <= delay);
+ last = now;
+ }
+
+ function onTouchEnd(e) {
+ if (L.Browser.msTouch) {
+ var idx = trackedTouches.indexOf(e.pointerId);
+ if (idx === -1) {
+ return;
+ }
+ trackedTouches.splice(idx, 1);
+ }
+
+ if (doubleTap) {
+ if (L.Browser.msTouch) {
+ // work around .type being readonly with MSPointer* events
+ var newTouch = { },
+ prop;
+
+ // jshint forin:false
+ for (var i in touch) {
+ prop = touch[i];
+ if (typeof prop === 'function') {
+ newTouch[i] = prop.bind(touch);
+ } else {
+ newTouch[i] = prop;
+ }
+ }
+ touch = newTouch;
+ }
+ touch.type = 'dblclick';
+ handler(touch);
+ last = null;
+ }
+ }
+ obj[pre + touchstart + id] = onTouchStart;
+ obj[pre + touchend + id] = onTouchEnd;
+
+ // on msTouch we need to listen on the document, otherwise a drag starting on the map and moving off screen
+ // will not come through to us, so we will lose track of how many touches are ongoing
+ var endElement = L.Browser.msTouch ? document.documentElement : obj;
+
+ obj.addEventListener(touchstart, onTouchStart, false);
+ endElement.addEventListener(touchend, onTouchEnd, false);
+
+ if (L.Browser.msTouch) {
+ endElement.addEventListener('MSPointerCancel', onTouchEnd, false);
+ }
+
+ return this;
+ },
+
+ removeDoubleTapListener: function (obj, id) {
+ var pre = '_leaflet_';
+
+ obj.removeEventListener(this._touchstart, obj[pre + this._touchstart + id], false);
+ (L.Browser.msTouch ? document.documentElement : obj).removeEventListener(
+ this._touchend, obj[pre + this._touchend + id], false);
+
+ if (L.Browser.msTouch) {
+ document.documentElement.removeEventListener('MSPointerCancel', obj[pre + this._touchend + id], false);
+ }
+
+ return this;
+ }
+});
+
+
+/*
+ * Extends L.DomEvent to provide touch support for Internet Explorer and Windows-based devices.
+ */
+
+L.extend(L.DomEvent, {
+
+ _msTouches: [],
+ _msDocumentListener: false,
+
+ // Provides a touch events wrapper for msPointer events.
+ // Based on changes by veproza https://github.com/CloudMade/Leaflet/pull/1019
+
+ addMsTouchListener: function (obj, type, handler, id) {
+
+ switch (type) {
+ case 'touchstart':
+ return this.addMsTouchListenerStart(obj, type, handler, id);
+ case 'touchend':
+ return this.addMsTouchListenerEnd(obj, type, handler, id);
+ case 'touchmove':
+ return this.addMsTouchListenerMove(obj, type, handler, id);
+ default:
+ throw 'Unknown touch event type';
+ }
+ },
+
+ addMsTouchListenerStart: function (obj, type, handler, id) {
+ var pre = '_leaflet_',
+ touches = this._msTouches;
+
+ var cb = function (e) {
+
+ var alreadyInArray = false;
+ for (var i = 0; i < touches.length; i++) {
+ if (touches[i].pointerId === e.pointerId) {
+ alreadyInArray = true;
+ break;
+ }
+ }
+ if (!alreadyInArray) {
+ touches.push(e);
+ }
+
+ e.touches = touches.slice();
+ e.changedTouches = [e];
+
+ handler(e);
+ };
+
+ obj[pre + 'touchstart' + id] = cb;
+ obj.addEventListener('MSPointerDown', cb, false);
+
+ // need to also listen for end events to keep the _msTouches list accurate
+ // this needs to be on the body and never go away
+ if (!this._msDocumentListener) {
+ var internalCb = function (e) {
+ for (var i = 0; i < touches.length; i++) {
+ if (touches[i].pointerId === e.pointerId) {
+ touches.splice(i, 1);
+ break;
+ }
+ }
+ };
+ //We listen on the documentElement as any drags that end by moving the touch off the screen get fired there
+ document.documentElement.addEventListener('MSPointerUp', internalCb, false);
+ document.documentElement.addEventListener('MSPointerCancel', internalCb, false);
+
+ this._msDocumentListener = true;
+ }
+
+ return this;
+ },
+
+ addMsTouchListenerMove: function (obj, type, handler, id) {
+ var pre = '_leaflet_',
+ touches = this._msTouches;
+
+ function cb(e) {
+
+ // don't fire touch moves when mouse isn't down
+ if (e.pointerType === e.MSPOINTER_TYPE_MOUSE && e.buttons === 0) { return; }
+
+ for (var i = 0; i < touches.length; i++) {
+ if (touches[i].pointerId === e.pointerId) {
+ touches[i] = e;
+ break;
+ }
+ }
+
+ e.touches = touches.slice();
+ e.changedTouches = [e];
+
+ handler(e);
+ }
+
+ obj[pre + 'touchmove' + id] = cb;
+ obj.addEventListener('MSPointerMove', cb, false);
+
+ return this;
+ },
+
+ addMsTouchListenerEnd: function (obj, type, handler, id) {
+ var pre = '_leaflet_',
+ touches = this._msTouches;
+
+ var cb = function (e) {
+ for (var i = 0; i < touches.length; i++) {
+ if (touches[i].pointerId === e.pointerId) {
+ touches.splice(i, 1);
+ break;
+ }
+ }
+
+ e.touches = touches.slice();
+ e.changedTouches = [e];
+
+ handler(e);
+ };
+
+ obj[pre + 'touchend' + id] = cb;
+ obj.addEventListener('MSPointerUp', cb, false);
+ obj.addEventListener('MSPointerCancel', cb, false);
+
+ return this;
+ },
+
+ removeMsTouchListener: function (obj, type, id) {
+ var pre = '_leaflet_',
+ cb = obj[pre + type + id];
+
+ switch (type) {
+ case 'touchstart':
+ obj.removeEventListener('MSPointerDown', cb, false);
+ break;
+ case 'touchmove':
+ obj.removeEventListener('MSPointerMove', cb, false);
+ break;
+ case 'touchend':
+ obj.removeEventListener('MSPointerUp', cb, false);
+ obj.removeEventListener('MSPointerCancel', cb, false);
+ break;
+ }
+
+ return this;
+ }
+});
+
+
+/*
+ * L.Handler.TouchZoom is used by L.Map to add pinch zoom on supported mobile browsers.
+ */
+
+L.Map.mergeOptions({
+ touchZoom: L.Browser.touch && !L.Browser.android23
+});
+
+L.Map.TouchZoom = L.Handler.extend({
+ addHooks: function () {
+ L.DomEvent.on(this._map._container, 'touchstart', this._onTouchStart, this);
+ },
+
+ removeHooks: function () {
+ L.DomEvent.off(this._map._container, 'touchstart', this._onTouchStart, this);
+ },
+
+ _onTouchStart: function (e) {
+ var map = this._map;
+
+ if (!e.touches || e.touches.length !== 2 || map._animatingZoom || this._zooming) { return; }
+
+ var p1 = map.mouseEventToLayerPoint(e.touches[0]),
+ p2 = map.mouseEventToLayerPoint(e.touches[1]),
+ viewCenter = map._getCenterLayerPoint();
+
+ this._startCenter = p1.add(p2)._divideBy(2);
+ this._startDist = p1.distanceTo(p2);
+
+ this._moved = false;
+ this._zooming = true;
+
+ this._centerOffset = viewCenter.subtract(this._startCenter);
+
+ if (map._panAnim) {
+ map._panAnim.stop();
+ }
+
+ L.DomEvent
+ .on(document, 'touchmove', this._onTouchMove, this)
+ .on(document, 'touchend', this._onTouchEnd, this);
+
+ L.DomEvent.preventDefault(e);
+ },
+
+ _onTouchMove: function (e) {
+ var map = this._map;
+
+ if (!e.touches || e.touches.length !== 2 || !this._zooming) { return; }
+
+ var p1 = map.mouseEventToLayerPoint(e.touches[0]),
+ p2 = map.mouseEventToLayerPoint(e.touches[1]);
+
+ this._scale = p1.distanceTo(p2) / this._startDist;
+ this._delta = p1._add(p2)._divideBy(2)._subtract(this._startCenter);
+
+ if (this._scale === 1) { return; }
+
+ if (!this._moved) {
+ L.DomUtil.addClass(map._mapPane, 'leaflet-touching');
+
+ map
+ .fire('movestart')
+ .fire('zoomstart');
+
+ this._moved = true;
+ }
+
+ L.Util.cancelAnimFrame(this._animRequest);
+ this._animRequest = L.Util.requestAnimFrame(
+ this._updateOnMove, this, true, this._map._container);
+
+ L.DomEvent.preventDefault(e);
+ },
+
+ _updateOnMove: function () {
+ var map = this._map,
+ origin = this._getScaleOrigin(),
+ center = map.layerPointToLatLng(origin),
+ zoom = map.getScaleZoom(this._scale);
+
+ map._animateZoom(center, zoom, this._startCenter, this._scale, this._delta);
+ },
+
+ _onTouchEnd: function () {
+ if (!this._moved || !this._zooming) {
+ this._zooming = false;
+ return;
+ }
+
+ var map = this._map;
+
+ this._zooming = false;
+ L.DomUtil.removeClass(map._mapPane, 'leaflet-touching');
+ L.Util.cancelAnimFrame(this._animRequest);
+
+ L.DomEvent
+ .off(document, 'touchmove', this._onTouchMove)
+ .off(document, 'touchend', this._onTouchEnd);
+
+ var origin = this._getScaleOrigin(),
+ center = map.layerPointToLatLng(origin),
+
+ oldZoom = map.getZoom(),
+ floatZoomDelta = map.getScaleZoom(this._scale) - oldZoom,
+ roundZoomDelta = (floatZoomDelta > 0 ?
+ Math.ceil(floatZoomDelta) : Math.floor(floatZoomDelta)),
+
+ zoom = map._limitZoom(oldZoom + roundZoomDelta),
+ scale = map.getZoomScale(zoom) / this._scale;
+
+ map._animateZoom(center, zoom, origin, scale);
+ },
+
+ _getScaleOrigin: function () {
+ var centerOffset = this._centerOffset.subtract(this._delta).divideBy(this._scale);
+ return this._startCenter.add(centerOffset);
+ }
+});
+
+L.Map.addInitHook('addHandler', 'touchZoom', L.Map.TouchZoom);
+
+
+/*
+ * L.Map.Tap is used to enable mobile hacks like quick taps and long hold.
+ */
+
+L.Map.mergeOptions({
+ tap: true,
+ tapTolerance: 15
+});
+
+L.Map.Tap = L.Handler.extend({
+ addHooks: function () {
+ L.DomEvent.on(this._map._container, 'touchstart', this._onDown, this);
+ },
+
+ removeHooks: function () {
+ L.DomEvent.off(this._map._container, 'touchstart', this._onDown, this);
+ },
+
+ _onDown: function (e) {
+ if (!e.touches) { return; }
+
+ L.DomEvent.preventDefault(e);
+
+ this._fireClick = true;
+
+ // don't simulate click or track longpress if more than 1 touch
+ if (e.touches.length > 1) {
+ this._fireClick = false;
+ clearTimeout(this._holdTimeout);
+ return;
+ }
+
+ var first = e.touches[0],
+ el = first.target;
+
+ this._startPos = this._newPos = new L.Point(first.clientX, first.clientY);
+
+ // if touching a link, highlight it
+ if (el.tagName.toLowerCase() === 'a') {
+ L.DomUtil.addClass(el, 'leaflet-active');
+ }
+
+ // simulate long hold but setting a timeout
+ this._holdTimeout = setTimeout(L.bind(function () {
+ if (this._isTapValid()) {
+ this._fireClick = false;
+ this._onUp();
+ this._simulateEvent('contextmenu', first);
+ }
+ }, this), 1000);
+
+ L.DomEvent
+ .on(document, 'touchmove', this._onMove, this)
+ .on(document, 'touchend', this._onUp, this);
+ },
+
+ _onUp: function (e) {
+ clearTimeout(this._holdTimeout);
+
+ L.DomEvent
+ .off(document, 'touchmove', this._onMove, this)
+ .off(document, 'touchend', this._onUp, this);
+
+ if (this._fireClick && e && e.changedTouches) {
+
+ var first = e.changedTouches[0],
+ el = first.target;
+
+ if (el.tagName.toLowerCase() === 'a') {
+ L.DomUtil.removeClass(el, 'leaflet-active');
+ }
+
+ // simulate click if the touch didn't move too much
+ if (this._isTapValid()) {
+ this._simulateEvent('click', first);
+ }
+ }
+ },
+
+ _isTapValid: function () {
+ return this._newPos.distanceTo(this._startPos) <= this._map.options.tapTolerance;
+ },
+
+ _onMove: function (e) {
+ var first = e.touches[0];
+ this._newPos = new L.Point(first.clientX, first.clientY);
+ },
+
+ _simulateEvent: function (type, e) {
+ var simulatedEvent = document.createEvent('MouseEvents');
+
+ simulatedEvent._simulated = true;
+ e.target._simulatedClick = true;
+
+ simulatedEvent.initMouseEvent(
+ type, true, true, window, 1,
+ e.screenX, e.screenY,
+ e.clientX, e.clientY,
+ false, false, false, false, 0, null);
+
+ e.target.dispatchEvent(simulatedEvent);
+ }
+});
+
+if (L.Browser.touch && !L.Browser.msTouch) {
+ L.Map.addInitHook('addHandler', 'tap', L.Map.Tap);
+}
+
+
+/*
+ * L.Handler.ShiftDragZoom is used to add shift-drag zoom interaction to the map
+ * (zoom to a selected bounding box), enabled by default.
+ */
+
+L.Map.mergeOptions({
+ boxZoom: true
+});
+
+L.Map.BoxZoom = L.Handler.extend({
+ initialize: function (map) {
+ this._map = map;
+ this._container = map._container;
+ this._pane = map._panes.overlayPane;
+ },
+
+ addHooks: function () {
+ L.DomEvent.on(this._container, 'mousedown', this._onMouseDown, this);
+ },
+
+ removeHooks: function () {
+ L.DomEvent.off(this._container, 'mousedown', this._onMouseDown);
+ },
+
+ _onMouseDown: function (e) {
+ if (!e.shiftKey || ((e.which !== 1) && (e.button !== 1))) { return false; }
+
+ L.DomUtil.disableTextSelection();
+ L.DomUtil.disableImageDrag();
+
+ this._startLayerPoint = this._map.mouseEventToLayerPoint(e);
+
+ this._box = L.DomUtil.create('div', 'leaflet-zoom-box', this._pane);
+ L.DomUtil.setPosition(this._box, this._startLayerPoint);
+
+ //TODO refactor: move cursor to styles
+ this._container.style.cursor = 'crosshair';
+
+ L.DomEvent
+ .on(document, 'mousemove', this._onMouseMove, this)
+ .on(document, 'mouseup', this._onMouseUp, this)
+ .on(document, 'keydown', this._onKeyDown, this);
+
+ this._map.fire('boxzoomstart');
+ },
+
+ _onMouseMove: function (e) {
+ var startPoint = this._startLayerPoint,
+ box = this._box,
+
+ layerPoint = this._map.mouseEventToLayerPoint(e),
+ offset = layerPoint.subtract(startPoint),
+
+ newPos = new L.Point(
+ Math.min(layerPoint.x, startPoint.x),
+ Math.min(layerPoint.y, startPoint.y));
+
+ L.DomUtil.setPosition(box, newPos);
+
+ // TODO refactor: remove hardcoded 4 pixels
+ box.style.width = (Math.max(0, Math.abs(offset.x) - 4)) + 'px';
+ box.style.height = (Math.max(0, Math.abs(offset.y) - 4)) + 'px';
+ },
+
+ _finish: function () {
+ this._pane.removeChild(this._box);
+ this._container.style.cursor = '';
+
+ L.DomUtil.enableTextSelection();
+ L.DomUtil.enableImageDrag();
+
+ L.DomEvent
+ .off(document, 'mousemove', this._onMouseMove)
+ .off(document, 'mouseup', this._onMouseUp)
+ .off(document, 'keydown', this._onKeyDown);
+ },
+
+ _onMouseUp: function (e) {
+
+ this._finish();
+
+ var map = this._map,
+ layerPoint = map.mouseEventToLayerPoint(e);
+
+ if (this._startLayerPoint.equals(layerPoint)) { return; }
+
+ var bounds = new L.LatLngBounds(
+ map.layerPointToLatLng(this._startLayerPoint),
+ map.layerPointToLatLng(layerPoint));
+
+ map.fitBounds(bounds);
+
+ map.fire('boxzoomend', {
+ boxZoomBounds: bounds
+ });
+ },
+
+ _onKeyDown: function (e) {
+ if (e.keyCode === 27) {
+ this._finish();
+ }
+ }
+});
+
+L.Map.addInitHook('addHandler', 'boxZoom', L.Map.BoxZoom);
+
+
+/*
+ * L.Map.Keyboard is handling keyboard interaction with the map, enabled by default.
+ */
+
+L.Map.mergeOptions({
+ keyboard: true,
+ keyboardPanOffset: 80,
+ keyboardZoomOffset: 1
+});
+
+L.Map.Keyboard = L.Handler.extend({
+
+ keyCodes: {
+ left: [37],
+ right: [39],
+ down: [40],
+ up: [38],
+ zoomIn: [187, 107, 61],
+ zoomOut: [189, 109, 173]
+ },
+
+ initialize: function (map) {
+ this._map = map;
+
+ this._setPanOffset(map.options.keyboardPanOffset);
+ this._setZoomOffset(map.options.keyboardZoomOffset);
+ },
+
+ addHooks: function () {
+ var container = this._map._container;
+
+ // make the container focusable by tabbing
+ if (container.tabIndex === -1) {
+ container.tabIndex = '0';
+ }
+
+ L.DomEvent
+ .on(container, 'focus', this._onFocus, this)
+ .on(container, 'blur', this._onBlur, this)
+ .on(container, 'mousedown', this._onMouseDown, this);
+
+ this._map
+ .on('focus', this._addHooks, this)
+ .on('blur', this._removeHooks, this);
+ },
+
+ removeHooks: function () {
+ this._removeHooks();
+
+ var container = this._map._container;
+
+ L.DomEvent
+ .off(container, 'focus', this._onFocus, this)
+ .off(container, 'blur', this._onBlur, this)
+ .off(container, 'mousedown', this._onMouseDown, this);
+
+ this._map
+ .off('focus', this._addHooks, this)
+ .off('blur', this._removeHooks, this);
+ },
+
+ _onMouseDown: function () {
+ if (this._focused) { return; }
+
+ var body = document.body,
+ docEl = document.documentElement,
+ top = body.scrollTop || docEl.scrollTop,
+ left = body.scrollLeft || docEl.scrollLeft;
+
+ this._map._container.focus();
+
+ window.scrollTo(left, top);
+ },
+
+ _onFocus: function () {
+ this._focused = true;
+ this._map.fire('focus');
+ },
+
+ _onBlur: function () {
+ this._focused = false;
+ this._map.fire('blur');
+ },
+
+ _setPanOffset: function (pan) {
+ var keys = this._panKeys = {},
+ codes = this.keyCodes,
+ i, len;
+
+ for (i = 0, len = codes.left.length; i < len; i++) {
+ keys[codes.left[i]] = [-1 * pan, 0];
+ }
+ for (i = 0, len = codes.right.length; i < len; i++) {
+ keys[codes.right[i]] = [pan, 0];
+ }
+ for (i = 0, len = codes.down.length; i < len; i++) {
+ keys[codes.down[i]] = [0, pan];
+ }
+ for (i = 0, len = codes.up.length; i < len; i++) {
+ keys[codes.up[i]] = [0, -1 * pan];
+ }
+ },
+
+ _setZoomOffset: function (zoom) {
+ var keys = this._zoomKeys = {},
+ codes = this.keyCodes,
+ i, len;
+
+ for (i = 0, len = codes.zoomIn.length; i < len; i++) {
+ keys[codes.zoomIn[i]] = zoom;
+ }
+ for (i = 0, len = codes.zoomOut.length; i < len; i++) {
+ keys[codes.zoomOut[i]] = -zoom;
+ }
+ },
+
+ _addHooks: function () {
+ L.DomEvent.on(document, 'keydown', this._onKeyDown, this);
+ },
+
+ _removeHooks: function () {
+ L.DomEvent.off(document, 'keydown', this._onKeyDown, this);
+ },
+
+ _onKeyDown: function (e) {
+ var key = e.keyCode,
+ map = this._map;
+
+ if (key in this._panKeys) {
+
+ if (map._panAnim && map._panAnim._inProgress) { return; }
+
+ map.panBy(this._panKeys[key]);
+
+ if (map.options.maxBounds) {
+ map.panInsideBounds(map.options.maxBounds);
+ }
+
+ } else if (key in this._zoomKeys) {
+ map.setZoom(map.getZoom() + this._zoomKeys[key]);
+
+ } else {
+ return;
+ }
+
+ L.DomEvent.stop(e);
+ }
+});
+
+L.Map.addInitHook('addHandler', 'keyboard', L.Map.Keyboard);
+
+
+/*
+ * L.Handler.MarkerDrag is used internally by L.Marker to make the markers draggable.
+ */
+
+L.Handler.MarkerDrag = L.Handler.extend({
+ initialize: function (marker) {
+ this._marker = marker;
+ },
+
+ addHooks: function () {
+ var icon = this._marker._icon;
+ if (!this._draggable) {
+ this._draggable = new L.Draggable(icon, icon);
+ }
+
+ this._draggable
+ .on('dragstart', this._onDragStart, this)
+ .on('drag', this._onDrag, this)
+ .on('dragend', this._onDragEnd, this);
+ this._draggable.enable();
+ },
+
+ removeHooks: function () {
+ this._draggable
+ .off('dragstart', this._onDragStart, this)
+ .off('drag', this._onDrag, this)
+ .off('dragend', this._onDragEnd, this);
+
+ this._draggable.disable();
+ },
+
+ moved: function () {
+ return this._draggable && this._draggable._moved;
+ },
+
+ _onDragStart: function () {
+ this._marker
+ .closePopup()
+ .fire('movestart')
+ .fire('dragstart');
+ },
+
+ _onDrag: function () {
+ var marker = this._marker,
+ shadow = marker._shadow,
+ iconPos = L.DomUtil.getPosition(marker._icon),
+ latlng = marker._map.layerPointToLatLng(iconPos);
+
+ // update shadow position
+ if (shadow) {
+ L.DomUtil.setPosition(shadow, iconPos);
+ }
+
+ marker._latlng = latlng;
+
+ marker
+ .fire('move', {latlng: latlng})
+ .fire('drag');
+ },
+
+ _onDragEnd: function () {
+ this._marker
+ .fire('moveend')
+ .fire('dragend');
+ }
+});
+
+
+/*
+ * L.Control is a base class for implementing map controls. Handles positioning.
+ * All other controls extend from this class.
+ */
+
+L.Control = L.Class.extend({
+ options: {
+ position: 'topright'
+ },
+
+ initialize: function (options) {
+ L.setOptions(this, options);
+ },
+
+ getPosition: function () {
+ return this.options.position;
+ },
+
+ setPosition: function (position) {
+ var map = this._map;
+
+ if (map) {
+ map.removeControl(this);
+ }
+
+ this.options.position = position;
+
+ if (map) {
+ map.addControl(this);
+ }
+
+ return this;
+ },
+
+ getContainer: function () {
+ return this._container;
+ },
+
+ addTo: function (map) {
+ this._map = map;
+
+ var container = this._container = this.onAdd(map),
+ pos = this.getPosition(),
+ corner = map._controlCorners[pos];
+
+ L.DomUtil.addClass(container, 'leaflet-control');
+
+ if (pos.indexOf('bottom') !== -1) {
+ corner.insertBefore(container, corner.firstChild);
+ } else {
+ corner.appendChild(container);
+ }
+
+ return this;
+ },
+
+ removeFrom: function (map) {
+ var pos = this.getPosition(),
+ corner = map._controlCorners[pos];
+
+ corner.removeChild(this._container);
+ this._map = null;
+
+ if (this.onRemove) {
+ this.onRemove(map);
+ }
+
+ return this;
+ }
+});
+
+L.control = function (options) {
+ return new L.Control(options);
+};
+
+
+// adds control-related methods to L.Map
+
+L.Map.include({
+ addControl: function (control) {
+ control.addTo(this);
+ return this;
+ },
+
+ removeControl: function (control) {
+ control.removeFrom(this);
+ return this;
+ },
+
+ _initControlPos: function () {
+ var corners = this._controlCorners = {},
+ l = 'leaflet-',
+ container = this._controlContainer =
+ L.DomUtil.create('div', l + 'control-container', this._container);
+
+ function createCorner(vSide, hSide) {
+ var className = l + vSide + ' ' + l + hSide;
+
+ corners[vSide + hSide] = L.DomUtil.create('div', className, container);
+ }
+
+ createCorner('top', 'left');
+ createCorner('top', 'right');
+ createCorner('bottom', 'left');
+ createCorner('bottom', 'right');
+ },
+
+ _clearControlPos: function () {
+ this._container.removeChild(this._controlContainer);
+ }
+});
+
+
+/*
+ * L.Control.Zoom is used for the default zoom buttons on the map.
+ */
+
+L.Control.Zoom = L.Control.extend({
+ options: {
+ position: 'topleft'
+ },
+
+ onAdd: function (map) {
+ var zoomName = 'leaflet-control-zoom',
+ container = L.DomUtil.create('div', zoomName + ' leaflet-bar');
+
+ this._map = map;
+
+ this._zoomInButton = this._createButton(
+ '+', 'Zoom in', zoomName + '-in', container, this._zoomIn, this);
+ this._zoomOutButton = this._createButton(
+ '-', 'Zoom out', zoomName + '-out', container, this._zoomOut, this);
+
+ map.on('zoomend zoomlevelschange', this._updateDisabled, this);
+
+ return container;
+ },
+
+ onRemove: function (map) {
+ map.off('zoomend zoomlevelschange', this._updateDisabled, this);
+ },
+
+ _zoomIn: function (e) {
+ this._map.zoomIn(e.shiftKey ? 3 : 1);
+ },
+
+ _zoomOut: function (e) {
+ this._map.zoomOut(e.shiftKey ? 3 : 1);
+ },
+
+ _createButton: function (html, title, className, container, fn, context) {
+ var link = L.DomUtil.create('a', className, container);
+ link.innerHTML = html;
+ link.href = '#';
+ link.title = title;
+
+ var stop = L.DomEvent.stopPropagation;
+
+ L.DomEvent
+ .on(link, 'click', stop)
+ .on(link, 'mousedown', stop)
+ .on(link, 'dblclick', stop)
+ .on(link, 'click', L.DomEvent.preventDefault)
+ .on(link, 'click', fn, context);
+
+ return link;
+ },
+
+ _updateDisabled: function () {
+ var map = this._map,
+ className = 'leaflet-disabled';
+
+ L.DomUtil.removeClass(this._zoomInButton, className);
+ L.DomUtil.removeClass(this._zoomOutButton, className);
+
+ if (map._zoom === map.getMinZoom()) {
+ L.DomUtil.addClass(this._zoomOutButton, className);
+ }
+ if (map._zoom === map.getMaxZoom()) {
+ L.DomUtil.addClass(this._zoomInButton, className);
+ }
+ }
+});
+
+L.Map.mergeOptions({
+ zoomControl: true
+});
+
+L.Map.addInitHook(function () {
+ if (this.options.zoomControl) {
+ this.zoomControl = new L.Control.Zoom();
+ this.addControl(this.zoomControl);
+ }
+});
+
+L.control.zoom = function (options) {
+ return new L.Control.Zoom(options);
+};
+
+
+
+/*
+ * L.Control.Attribution is used for displaying attribution on the map (added by default).
+ */
+
+L.Control.Attribution = L.Control.extend({
+ options: {
+ position: 'bottomright',
+ prefix: '<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>'
+ },
+
+ initialize: function (options) {
+ L.setOptions(this, options);
+
+ this._attributions = {};
+ },
+
+ onAdd: function (map) {
+ this._container = L.DomUtil.create('div', 'leaflet-control-attribution');
+ L.DomEvent.disableClickPropagation(this._container);
+
+ map
+ .on('layeradd', this._onLayerAdd, this)
+ .on('layerremove', this._onLayerRemove, this);
+
+ this._update();
+
+ return this._container;
+ },
+
+ onRemove: function (map) {
+ map
+ .off('layeradd', this._onLayerAdd)
+ .off('layerremove', this._onLayerRemove);
+
+ },
+
+ setPrefix: function (prefix) {
+ this.options.prefix = prefix;
+ this._update();
+ return this;
+ },
+
+ addAttribution: function (text) {
+ if (!text) { return; }
+
+ if (!this._attributions[text]) {
+ this._attributions[text] = 0;
+ }
+ this._attributions[text]++;
+
+ this._update();
+
+ return this;
+ },
+
+ removeAttribution: function (text) {
+ if (!text) { return; }
+
+ if (this._attributions[text]) {
+ this._attributions[text]--;
+ this._update();
+ }
+
+ return this;
+ },
+
+ _update: function () {
+ if (!this._map) { return; }
+
+ var attribs = [];
+
+ for (var i in this._attributions) {
+ if (this._attributions[i]) {
+ attribs.push(i);
+ }
+ }
+
+ var prefixAndAttribs = [];
+
+ if (this.options.prefix) {
+ prefixAndAttribs.push(this.options.prefix);
+ }
+ if (attribs.length) {
+ prefixAndAttribs.push(attribs.join(', '));
+ }
+
+ this._container.innerHTML = prefixAndAttribs.join(' | ');
+ },
+
+ _onLayerAdd: function (e) {
+ if (e.layer.getAttribution) {
+ this.addAttribution(e.layer.getAttribution());
+ }
+ },
+
+ _onLayerRemove: function (e) {
+ if (e.layer.getAttribution) {
+ this.removeAttribution(e.layer.getAttribution());
+ }
+ }
+});
+
+L.Map.mergeOptions({
+ attributionControl: true
+});
+
+L.Map.addInitHook(function () {
+ if (this.options.attributionControl) {
+ this.attributionControl = (new L.Control.Attribution()).addTo(this);
+ }
+});
+
+L.control.attribution = function (options) {
+ return new L.Control.Attribution(options);
+};
+
+
+/*
+ * L.Control.Scale is used for displaying metric/imperial scale on the map.
+ */
+
+L.Control.Scale = L.Control.extend({
+ options: {
+ position: 'bottomleft',
+ maxWidth: 100,
+ metric: true,
+ imperial: true,
+ updateWhenIdle: false
+ },
+
+ onAdd: function (map) {
+ this._map = map;
+
+ var className = 'leaflet-control-scale',
+ container = L.DomUtil.create('div', className),
+ options = this.options;
+
+ this._addScales(options, className, container);
+
+ map.on(options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
+ map.whenReady(this._update, this);
+
+ return container;
+ },
+
+ onRemove: function (map) {
+ map.off(this.options.updateWhenIdle ? 'moveend' : 'move', this._update, this);
+ },
+
+ _addScales: function (options, className, container) {
+ if (options.metric) {
+ this._mScale = L.DomUtil.create('div', className + '-line', container);
+ }
+ if (options.imperial) {
+ this._iScale = L.DomUtil.create('div', className + '-line', container);
+ }
+ },
+
+ _update: function () {
+ var bounds = this._map.getBounds(),
+ centerLat = bounds.getCenter().lat,
+ halfWorldMeters = 6378137 * Math.PI * Math.cos(centerLat * Math.PI / 180),
+ dist = halfWorldMeters * (bounds.getNorthEast().lng - bounds.getSouthWest().lng) / 180,
+
+ size = this._map.getSize(),
+ options = this.options,
+ maxMeters = 0;
+
+ if (size.x > 0) {
+ maxMeters = dist * (options.maxWidth / size.x);
+ }
+
+ this._updateScales(options, maxMeters);
+ },
+
+ _updateScales: function (options, maxMeters) {
+ if (options.metric && maxMeters) {
+ this._updateMetric(maxMeters);
+ }
+
+ if (options.imperial && maxMeters) {
+ this._updateImperial(maxMeters);
+ }
+ },
+
+ _updateMetric: function (maxMeters) {
+ var meters = this._getRoundNum(maxMeters);
+
+ this._mScale.style.width = this._getScaleWidth(meters / maxMeters) + 'px';
+ this._mScale.innerHTML = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';
+ },
+
+ _updateImperial: function (maxMeters) {
+ var maxFeet = maxMeters * 3.2808399,
+ scale = this._iScale,
+ maxMiles, miles, feet;
+
+ if (maxFeet > 5280) {
+ maxMiles = maxFeet / 5280;
+ miles = this._getRoundNum(maxMiles);
+
+ scale.style.width = this._getScaleWidth(miles / maxMiles) + 'px';
+ scale.innerHTML = miles + ' mi';
+
+ } else {
+ feet = this._getRoundNum(maxFeet);
+
+ scale.style.width = this._getScaleWidth(feet / maxFeet) + 'px';
+ scale.innerHTML = feet + ' ft';
+ }
+ },
+
+ _getScaleWidth: function (ratio) {
+ return Math.round(this.options.maxWidth * ratio) - 10;
+ },
+
+ _getRoundNum: function (num) {
+ var pow10 = Math.pow(10, (Math.floor(num) + '').length - 1),
+ d = num / pow10;
+
+ d = d >= 10 ? 10 : d >= 5 ? 5 : d >= 3 ? 3 : d >= 2 ? 2 : 1;
+
+ return pow10 * d;
+ }
+});
+
+L.control.scale = function (options) {
+ return new L.Control.Scale(options);
+};
+
+
+/*
+ * L.Control.Layers is a control to allow users to switch between different layers on the map.
+ */
+
+L.Control.Layers = L.Control.extend({
+ options: {
+ collapsed: true,
+ position: 'topright',
+ autoZIndex: true
+ },
+
+ initialize: function (baseLayers, overlays, options) {
+ L.setOptions(this, options);
+
+ this._layers = {};
+ this._lastZIndex = 0;
+ this._handlingClick = false;
+
+ for (var i in baseLayers) {
+ this._addLayer(baseLayers[i], i);
+ }
+
+ for (i in overlays) {
+ this._addLayer(overlays[i], i, true);
+ }
+ },
+
+ onAdd: function (map) {
+ this._initLayout();
+ this._update();
+
+ map
+ .on('layeradd', this._onLayerChange, this)
+ .on('layerremove', this._onLayerChange, this);
+
+ return this._container;
+ },
+
+ onRemove: function (map) {
+ map
+ .off('layeradd', this._onLayerChange)
+ .off('layerremove', this._onLayerChange);
+ },
+
+ addBaseLayer: function (layer, name) {
+ this._addLayer(layer, name);
+ this._update();
+ return this;
+ },
+
+ addOverlay: function (layer, name) {
+ this._addLayer(layer, name, true);
+ this._update();
+ return this;
+ },
+
+ removeLayer: function (layer) {
+ var id = L.stamp(layer);
+ delete this._layers[id];
+ this._update();
+ return this;
+ },
+
+ _initLayout: function () {
+ var className = 'leaflet-control-layers',
+ container = this._container = L.DomUtil.create('div', className);
+
+ //Makes this work on IE10 Touch devices by stopping it from firing a mouseout event when the touch is released
+ container.setAttribute('aria-haspopup', true);
+
+ if (!L.Browser.touch) {
+ L.DomEvent.disableClickPropagation(container);
+ L.DomEvent.on(container, 'mousewheel', L.DomEvent.stopPropagation);
+ } else {
+ L.DomEvent.on(container, 'click', L.DomEvent.stopPropagation);
+ }
+
+ var form = this._form = L.DomUtil.create('form', className + '-list');
+
+ if (this.options.collapsed) {
+ if (!L.Browser.android) {
+ L.DomEvent
+ .on(container, 'mouseover', this._expand, this)
+ .on(container, 'mouseout', this._collapse, this);
+ }
+ var link = this._layersLink = L.DomUtil.create('a', className + '-toggle', container);
+ link.href = '#';
+ link.title = 'Layers';
+
+ if (L.Browser.touch) {
+ L.DomEvent
+ .on(link, 'click', L.DomEvent.stop)
+ .on(link, 'click', this._expand, this);
+ }
+ else {
+ L.DomEvent.on(link, 'focus', this._expand, this);
+ }
+
+ this._map.on('click', this._collapse, this);
+ // TODO keyboard accessibility
+ } else {
+ this._expand();
+ }
+
+ this._baseLayersList = L.DomUtil.create('div', className + '-base', form);
+ this._separator = L.DomUtil.create('div', className + '-separator', form);
+ this._overlaysList = L.DomUtil.create('div', className + '-overlays', form);
+
+ container.appendChild(form);
+ },
+
+ _addLayer: function (layer, name, overlay) {
+ var id = L.stamp(layer);
+
+ this._layers[id] = {
+ layer: layer,
+ name: name,
+ overlay: overlay
+ };
+
+ if (this.options.autoZIndex && layer.setZIndex) {
+ this._lastZIndex++;
+ layer.setZIndex(this._lastZIndex);
+ }
+ },
+
+ _update: function () {
+ if (!this._container) {
+ return;
+ }
+
+ this._baseLayersList.innerHTML = '';
+ this._overlaysList.innerHTML = '';
+
+ var baseLayersPresent = false,
+ overlaysPresent = false,
+ i, obj;
+
+ for (i in this._layers) {
+ obj = this._layers[i];
+ this._addItem(obj);
+ overlaysPresent = overlaysPresent || obj.overlay;
+ baseLayersPresent = baseLayersPresent || !obj.overlay;
+ }
+
+ this._separator.style.display = overlaysPresent && baseLayersPresent ? '' : 'none';
+ },
+
+ _onLayerChange: function (e) {
+ var obj = this._layers[L.stamp(e.layer)];
+
+ if (!obj) { return; }
+
+ if (!this._handlingClick) {
+ this._update();
+ }
+
+ var type = obj.overlay ?
+ (e.type === 'layeradd' ? 'overlayadd' : 'overlayremove') :
+ (e.type === 'layeradd' ? 'baselayerchange' : null);
+
+ if (type) {
+ this._map.fire(type, obj);
+ }
+ },
+
+ // IE7 bugs out if you create a radio dynamically, so you have to do it this hacky way (see http://bit.ly/PqYLBe)
+ _createRadioElement: function (name, checked) {
+
+ var radioHtml = '<input type="radio" class="leaflet-control-layers-selector" name="' + name + '"';
+ if (checked) {
+ radioHtml += ' checked="checked"';
+ }
+ radioHtml += '/>';
+
+ var radioFragment = document.createElement('div');
+ radioFragment.innerHTML = radioHtml;
+
+ return radioFragment.firstChild;
+ },
+
+ _addItem: function (obj) {
+ var label = document.createElement('label'),
+ input,
+ checked = this._map.hasLayer(obj.layer);
+
+ if (obj.overlay) {
+ input = document.createElement('input');
+ input.type = 'checkbox';
+ input.className = 'leaflet-control-layers-selector';
+ input.defaultChecked = checked;
+ } else {
+ input = this._createRadioElement('leaflet-base-layers', checked);
+ }
+
+ input.layerId = L.stamp(obj.layer);
+
+ L.DomEvent.on(input, 'click', this._onInputClick, this);
+
+ var name = document.createElement('span');
+ name.innerHTML = ' ' + obj.name;
+
+ label.appendChild(input);
+ label.appendChild(name);
+
+ var container = obj.overlay ? this._overlaysList : this._baseLayersList;
+ container.appendChild(label);
+
+ return label;
+ },
+
+ _onInputClick: function () {
+ var i, input, obj,
+ inputs = this._form.getElementsByTagName('input'),
+ inputsLen = inputs.length;
+
+ this._handlingClick = true;
+
+ for (i = 0; i < inputsLen; i++) {
+ input = inputs[i];
+ obj = this._layers[input.layerId];
+
+ if (input.checked && !this._map.hasLayer(obj.layer)) {
+ this._map.addLayer(obj.layer);
+
+ } else if (!input.checked && this._map.hasLayer(obj.layer)) {
+ this._map.removeLayer(obj.layer);
+ }
+ }
+
+ this._handlingClick = false;
+ },
+
+ _expand: function () {
+ L.DomUtil.addClass(this._container, 'leaflet-control-layers-expanded');
+ },
+
+ _collapse: function () {
+ this._container.className = this._container.className.replace(' leaflet-control-layers-expanded', '');
+ }
+});
+
+L.control.layers = function (baseLayers, overlays, options) {
+ return new L.Control.Layers(baseLayers, overlays, options);
+};
+
+
+/*
+ * L.PosAnimation is used by Leaflet internally for pan animations.
+ */
+
+L.PosAnimation = L.Class.extend({
+ includes: L.Mixin.Events,
+
+ run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
+ this.stop();
+
+ this._el = el;
+ this._inProgress = true;
+ this._newPos = newPos;
+
+ this.fire('start');
+
+ el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) +
+ 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)';
+
+ L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
+ L.DomUtil.setPosition(el, newPos);
+
+ // toggle reflow, Chrome flickers for some reason if you don't do this
+ L.Util.falseFn(el.offsetWidth);
+
+ // there's no native way to track value updates of transitioned properties, so we imitate this
+ this._stepTimer = setInterval(L.bind(this._onStep, this), 50);
+ },
+
+ stop: function () {
+ if (!this._inProgress) { return; }
+
+ // if we just removed the transition property, the element would jump to its final position,
+ // so we need to make it stay at the current position
+
+ L.DomUtil.setPosition(this._el, this._getPos());
+ this._onTransitionEnd();
+ L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation
+ },
+
+ _onStep: function () {
+ var stepPos = this._getPos();
+ if (!stepPos) {
+ this._onTransitionEnd();
+ return;
+ }
+ // jshint camelcase: false
+ // make L.DomUtil.getPosition return intermediate position value during animation
+ this._el._leaflet_pos = stepPos;
+
+ this.fire('step');
+ },
+
+ // you can't easily get intermediate values of properties animated with CSS3 Transitions,
+ // we need to parse computed style (in case of transform it returns matrix string)
+
+ _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/,
+
+ _getPos: function () {
+ var left, top, matches,
+ el = this._el,
+ style = window.getComputedStyle(el);
+
+ if (L.Browser.any3d) {
+ matches = style[L.DomUtil.TRANSFORM].match(this._transformRe);
+ if (!matches) { return; }
+ left = parseFloat(matches[1]);
+ top = parseFloat(matches[2]);
+ } else {
+ left = parseFloat(style.left);
+ top = parseFloat(style.top);
+ }
+
+ return new L.Point(left, top, true);
+ },
+
+ _onTransitionEnd: function () {
+ L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this);
+
+ if (!this._inProgress) { return; }
+ this._inProgress = false;
+
+ this._el.style[L.DomUtil.TRANSITION] = '';
+
+ // jshint camelcase: false
+ // make sure L.DomUtil.getPosition returns the final position value after animation
+ this._el._leaflet_pos = this._newPos;
+
+ clearInterval(this._stepTimer);
+
+ this.fire('step').fire('end');
+ }
+
+});
+
+
+/*
+ * Extends L.Map to handle panning animations.
+ */
+
+L.Map.include({
+
+ setView: function (center, zoom, options) {
+
+ zoom = this._limitZoom(zoom);
+ center = L.latLng(center);
+ options = options || {};
+
+ if (this._panAnim) {
+ this._panAnim.stop();
+ }
+
+ if (this._loaded && !options.reset && options !== true) {
+
+ if (options.animate !== undefined) {
+ options.zoom = L.extend({animate: options.animate}, options.zoom);
+ options.pan = L.extend({animate: options.animate}, options.pan);
+ }
+
+ // try animating pan or zoom
+ var animated = (this._zoom !== zoom) ?
+ this._tryAnimatedZoom && this._tryAnimatedZoom(center, zoom, options.zoom) :
+ this._tryAnimatedPan(center, options.pan);
+
+ if (animated) {
+ // prevent resize handler call, the view will refresh after animation anyway
+ clearTimeout(this._sizeTimer);
+ return this;
+ }
+ }
+
+ // animation didn't start, just reset the map view
+ this._resetView(center, zoom);
+
+ return this;
+ },
+
+ panBy: function (offset, options) {
+ offset = L.point(offset).round();
+ options = options || {};
+
+ if (!offset.x && !offset.y) {
+ return this;
+ }
+
+ if (!this._panAnim) {
+ this._panAnim = new L.PosAnimation();
+
+ this._panAnim.on({
+ 'step': this._onPanTransitionStep,
+ 'end': this._onPanTransitionEnd
+ }, this);
+ }
+
+ // don't fire movestart if animating inertia
+ if (!options.noMoveStart) {
+ this.fire('movestart');
+ }
+
+ // animate pan unless animate: false specified
+ if (options.animate !== false) {
+ L.DomUtil.addClass(this._mapPane, 'leaflet-pan-anim');
+
+ var newPos = this._getMapPanePos().subtract(offset);
+ this._panAnim.run(this._mapPane, newPos, options.duration || 0.25, options.easeLinearity);
+ } else {
+ this._rawPanBy(offset);
+ this.fire('move').fire('moveend');
+ }
+
+ return this;
+ },
+
+ _onPanTransitionStep: function () {
+ this.fire('move');
+ },
+
+ _onPanTransitionEnd: function () {
+ L.DomUtil.removeClass(this._mapPane, 'leaflet-pan-anim');
+ this.fire('moveend');
+ },
+
+ _tryAnimatedPan: function (center, options) {
+ // difference between the new and current centers in pixels
+ var offset = this._getCenterOffset(center)._floor();
+
+ // don't animate too far unless animate: true specified in options
+ if ((options && options.animate) !== true && !this.getSize().contains(offset)) { return false; }
+
+ this.panBy(offset, options);
+
+ return true;
+ }
+});
+
+
+/*
+ * L.PosAnimation fallback implementation that powers Leaflet pan animations
+ * in browsers that don't support CSS3 Transitions.
+ */
+
+L.PosAnimation = L.DomUtil.TRANSITION ? L.PosAnimation : L.PosAnimation.extend({
+
+ run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number])
+ this.stop();
+
+ this._el = el;
+ this._inProgress = true;
+ this._duration = duration || 0.25;
+ this._easeOutPower = 1 / Math.max(easeLinearity || 0.5, 0.2);
+
+ this._startPos = L.DomUtil.getPosition(el);
+ this._offset = newPos.subtract(this._startPos);
+ this._startTime = +new Date();
+
+ this.fire('start');
+
+ this._animate();
+ },
+
+ stop: function () {
+ if (!this._inProgress) { return; }
+
+ this._step();
+ this._complete();
+ },
+
+ _animate: function () {
+ // animation loop
+ this._animId = L.Util.requestAnimFrame(this._animate, this);
+ this._step();
+ },
+
+ _step: function () {
+ var elapsed = (+new Date()) - this._startTime,
+ duration = this._duration * 1000;
+
+ if (elapsed < duration) {
+ this._runFrame(this._easeOut(elapsed / duration));
+ } else {
+ this._runFrame(1);
+ this._complete();
+ }
+ },
+
+ _runFrame: function (progress) {
+ var pos = this._startPos.add(this._offset.multiplyBy(progress));
+ L.DomUtil.setPosition(this._el, pos);
+
+ this.fire('step');
+ },
+
+ _complete: function () {
+ L.Util.cancelAnimFrame(this._animId);
+
+ this._inProgress = false;
+ this.fire('end');
+ },
+
+ _easeOut: function (t) {
+ return 1 - Math.pow(1 - t, this._easeOutPower);
+ }
+});
+
+
+/*
+ * Extends L.Map to handle zoom animations.
+ */
+
+L.Map.mergeOptions({
+ zoomAnimation: true,
+ zoomAnimationThreshold: 4
+});
+
+if (L.DomUtil.TRANSITION) {
+
+ L.Map.addInitHook(function () {
+ // don't animate on browsers without hardware-accelerated transitions or old Android/Opera
+ this._zoomAnimated = this.options.zoomAnimation && L.DomUtil.TRANSITION &&
+ L.Browser.any3d && !L.Browser.android23 && !L.Browser.mobileOpera;
+
+ // zoom transitions run with the same duration for all layers, so if one of transitionend events
+ // happens after starting zoom animation (propagating to the map pane), we know that it ended globally
+ if (this._zoomAnimated) {
+ L.DomEvent.on(this._mapPane, L.DomUtil.TRANSITION_END, this._catchTransitionEnd, this);
+ }
+ });
+}
+
+L.Map.include(!L.DomUtil.TRANSITION ? {} : {
+
+ _catchTransitionEnd: function () {
+ if (this._animatingZoom) {
+ this._onZoomTransitionEnd();
+ }
+ },
+
+ _nothingToAnimate: function () {
+ return !this._container.getElementsByClassName('leaflet-zoom-animated').length;
+ },
+
+ _tryAnimatedZoom: function (center, zoom, options) {
+
+ if (this._animatingZoom) { return true; }
+
+ options = options || {};
+
+ // don't animate if disabled, not supported or zoom difference is too large
+ if (!this._zoomAnimated || options.animate === false || this._nothingToAnimate() ||
+ Math.abs(zoom - this._zoom) > this.options.zoomAnimationThreshold) { return false; }
+
+ // offset is the pixel coords of the zoom origin relative to the current center
+ var scale = this.getZoomScale(zoom),
+ offset = this._getCenterOffset(center)._divideBy(1 - 1 / scale),
+ origin = this._getCenterLayerPoint()._add(offset);
+
+ // don't animate if the zoom origin isn't within one screen from the current center, unless forced
+ if (options.animate !== true && !this.getSize().contains(offset)) { return false; }
+
+ this
+ .fire('movestart')
+ .fire('zoomstart');
+
+ this._animateZoom(center, zoom, origin, scale, null, true);
+
+ return true;
+ },
+
+ _animateZoom: function (center, zoom, origin, scale, delta, backwards) {
+
+ this._animatingZoom = true;
+
+ // put transform transition on all layers with leaflet-zoom-animated class
+ L.DomUtil.addClass(this._mapPane, 'leaflet-zoom-anim');
+
+ // remember what center/zoom to set after animation
+ this._animateToCenter = center;
+ this._animateToZoom = zoom;
+
+ // disable any dragging during animation
+ if (L.Draggable) {
+ L.Draggable._disabled = true;
+ }
+
+ this.fire('zoomanim', {
+ center: center,
+ zoom: zoom,
+ origin: origin,
+ scale: scale,
+ delta: delta,
+ backwards: backwards
+ });
+ },
+
+ _onZoomTransitionEnd: function () {
+
+ this._animatingZoom = false;
+
+ L.DomUtil.removeClass(this._mapPane, 'leaflet-zoom-anim');
+
+ this._resetView(this._animateToCenter, this._animateToZoom, true, true);
+
+ if (L.Draggable) {
+ L.Draggable._disabled = false;
+ }
+ }
+});
+
+
+/*
+ Zoom animation logic for L.TileLayer.
+*/
+
+L.TileLayer.include({
+ _animateZoom: function (e) {
+ if (!this._animating) {
+ this._animating = true;
+ this._prepareBgBuffer();
+ }
+
+ var bg = this._bgBuffer,
+ transform = L.DomUtil.TRANSFORM,
+ initialTransform = e.delta ? L.DomUtil.getTranslateString(e.delta) : bg.style[transform],
+ scaleStr = L.DomUtil.getScaleString(e.scale, e.origin);
+
+ bg.style[transform] = e.backwards ?
+ scaleStr + ' ' + initialTransform :
+ initialTransform + ' ' + scaleStr;
+ },
+
+ _endZoomAnim: function () {
+ var front = this._tileContainer,
+ bg = this._bgBuffer;
+
+ front.style.visibility = '';
+ front.parentNode.appendChild(front); // Bring to fore
+
+ // force reflow
+ L.Util.falseFn(bg.offsetWidth);
+
+ this._animating = false;
+ },
+
+ _clearBgBuffer: function () {
+ var map = this._map;
+
+ if (map && !map._animatingZoom && !map.touchZoom._zooming) {
+ this._bgBuffer.innerHTML = '';
+ this._bgBuffer.style[L.DomUtil.TRANSFORM] = '';
+ }
+ },
+
+ _prepareBgBuffer: function () {
+
+ var front = this._tileContainer,
+ bg = this._bgBuffer;
+
+ // if foreground layer doesn't have many tiles but bg layer does,
+ // keep the existing bg layer and just zoom it some more
+
+ var bgLoaded = this._getLoadedTilesPercentage(bg),
+ frontLoaded = this._getLoadedTilesPercentage(front);
+
+ if (bg && bgLoaded > 0.5 && frontLoaded < 0.5) {
+
+ front.style.visibility = 'hidden';
+ this._stopLoadingImages(front);
+ return;
+ }
+
+ // prepare the buffer to become the front tile pane
+ bg.style.visibility = 'hidden';
+ bg.style[L.DomUtil.TRANSFORM] = '';
+
+ // switch out the current layer to be the new bg layer (and vice-versa)
+ this._tileContainer = bg;
+ bg = this._bgBuffer = front;
+
+ this._stopLoadingImages(bg);
+
+ //prevent bg buffer from clearing right after zoom
+ clearTimeout(this._clearBgBufferTimer);
+ },
+
+ _getLoadedTilesPercentage: function (container) {
+ var tiles = container.getElementsByTagName('img'),
+ i, len, count = 0;
+
+ for (i = 0, len = tiles.length; i < len; i++) {
+ if (tiles[i].complete) {
+ count++;
+ }
+ }
+ return count / len;
+ },
+
+ // stops loading all tiles in the background layer
+ _stopLoadingImages: function (container) {
+ var tiles = Array.prototype.slice.call(container.getElementsByTagName('img')),
+ i, len, tile;
+
+ for (i = 0, len = tiles.length; i < len; i++) {
+ tile = tiles[i];
+
+ if (!tile.complete) {
+ tile.onload = L.Util.falseFn;
+ tile.onerror = L.Util.falseFn;
+ tile.src = L.Util.emptyImageUrl;
+
+ tile.parentNode.removeChild(tile);
+ }
+ }
+ }
+});
+
+
+/*
+ * Provides L.Map with convenient shortcuts for using browser geolocation features.
+ */
+
+L.Map.include({
+ _defaultLocateOptions: {
+ watch: false,
+ setView: false,
+ maxZoom: Infinity,
+ timeout: 10000,
+ maximumAge: 0,
+ enableHighAccuracy: false
+ },
+
+ locate: function (/*Object*/ options) {
+
+ options = this._locateOptions = L.extend(this._defaultLocateOptions, options);
+
+ if (!navigator.geolocation) {
+ this._handleGeolocationError({
+ code: 0,
+ message: 'Geolocation not supported.'
+ });
+ return this;
+ }
+
+ var onResponse = L.bind(this._handleGeolocationResponse, this),
+ onError = L.bind(this._handleGeolocationError, this);
+
+ if (options.watch) {
+ this._locationWatchId =
+ navigator.geolocation.watchPosition(onResponse, onError, options);
+ } else {
+ navigator.geolocation.getCurrentPosition(onResponse, onError, options);
+ }
+ return this;
+ },
+
+ stopLocate: function () {
+ if (navigator.geolocation) {
+ navigator.geolocation.clearWatch(this._locationWatchId);
+ }
+ if (this._locateOptions) {
+ this._locateOptions.setView = false;
+ }
+ return this;
+ },
+
+ _handleGeolocationError: function (error) {
+ var c = error.code,
+ message = error.message ||
+ (c === 1 ? 'permission denied' :
+ (c === 2 ? 'position unavailable' : 'timeout'));
+
+ if (this._locateOptions.setView && !this._loaded) {
+ this.fitWorld();
+ }
+
+ this.fire('locationerror', {
+ code: c,
+ message: 'Geolocation error: ' + message + '.'
+ });
+ },
+
+ _handleGeolocationResponse: function (pos) {
+ var lat = pos.coords.latitude,
+ lng = pos.coords.longitude,
+ latlng = new L.LatLng(lat, lng),
+
+ latAccuracy = 180 * pos.coords.accuracy / 40075017,
+ lngAccuracy = latAccuracy / Math.cos(L.LatLng.DEG_TO_RAD * lat),
+
+ bounds = L.latLngBounds(
+ [lat - latAccuracy, lng - lngAccuracy],
+ [lat + latAccuracy, lng + lngAccuracy]),
+
+ options = this._locateOptions;
+
+ if (options.setView) {
+ var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
+ this.setView(latlng, zoom);
+ }
+
+ var data = {
+ latlng: latlng,
+ bounds: bounds
+ };
+
+ for (var i in pos.coords) {
+ if (typeof pos.coords[i] === 'number') {
+ data[i] = pos.coords[i];
+ }
+ }
+
+ this.fire('locationfound', data);
+ }
+});
+
+
+}(window, document));
Property changes on: trunk/echobase-ui/src/main/webapp/js/leaflet-src.js
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/webapp/js/spatial.js
===================================================================
--- trunk/echobase-ui/src/main/webapp/js/spatial.js (rev 0)
+++ trunk/echobase-ui/src/main/webapp/js/spatial.js 2013-08-20 06:07:41 UTC (rev 843)
@@ -0,0 +1,25 @@
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+/**
+ * Created by tchemit on 8/19/13.
+ */
Property changes on: trunk/echobase-ui/src/main/webapp/js/spatial.js
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/webapp/js/test.js
===================================================================
--- trunk/echobase-ui/src/main/webapp/js/test.js (rev 0)
+++ trunk/echobase-ui/src/main/webapp/js/test.js 2013-08-20 06:07:41 UTC (rev 843)
@@ -0,0 +1,67 @@
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+var statesData = {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "id": "01",
+ "properties": {"name": "Alabama", "density": 94.65},
+ "geometry": {"type": "Polygon", "coordinates": [
+ [
+ [-87.359296, 35.00118],
+ [-85.606675, 34.984749],
+ [-85.431413, 34.124869],
+ [-85.184951, 32.859696],
+ [-85.069935, 32.580372],
+ [-84.960397, 32.421541],
+ [-85.004212, 32.322956],
+ [-84.889196, 32.262709],
+ [-85.058981, 32.13674],
+ [-85.053504, 32.01077],
+ [-85.141136, 31.840985],
+ [-85.042551, 31.539753],
+ [-85.113751, 31.27686],
+ [-85.004212, 31.003013],
+ [-85.497137, 30.997536],
+ [-87.600282, 30.997536],
+ [-87.633143, 30.86609],
+ [-87.408589, 30.674397],
+ [-87.446927, 30.510088],
+ [-87.37025, 30.427934],
+ [-87.518128, 30.280057],
+ [-87.655051, 30.247195],
+ [-87.90699, 30.411504],
+ [-87.934375, 30.657966],
+ [-88.011052, 30.685351],
+ [-88.10416, 30.499135],
+ [-88.137022, 30.318396],
+ [-88.394438, 30.367688],
+ [-88.471115, 31.895754],
+ [-88.241084, 33.796253],
+ [-88.098683, 34.891641],
+ [-88.202745, 34.995703],
+ [-87.359296, 35.00118]
+ ]
+ ]}}
+ ]};
\ No newline at end of file
Property changes on: trunk/echobase-ui/src/main/webapp/js/test.js
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
1
0
15 Aug '13
Author: tchemit
Date: 2013-08-15 12:53:16 +0200 (Thu, 15 Aug 2013)
New Revision: 842
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/842
Log:
- use last topia api
- add spatialDataCache
- improve projet design
Added:
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseApplicationConfigProvider.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfiguration.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfigurationOption.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/data/CellDAOImpl.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/CellPoint.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/DbChangedEvent.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/VoyageChangedEvent.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/WorkingDbChangeListener.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/ProgressModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DbEditorService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DecoratorService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/UserService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbMode.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryCsvModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryInvalidNameException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNameAlreadyExistException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNotFoundException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/GenericSQLQuery.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/DecoratorServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/embeddedapplication/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportdb/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportdb/ExportDbServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportquery/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AcousticImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CatchesImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/OperationImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdb/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdb/ImportDbServiceTest.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/AbstractGetVoyage.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageDataMetadata.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageEchotype.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageSpecies.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java
trunk/echobase-ui/src/main/resources/config/struts-spatial.xml
trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/
trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp
Removed:
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseApplicationConfigProvider.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfiguration.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfigurationOption.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ProgressModel.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ServiceFactoryAware.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DbEditorService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DecoratorService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/UserService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbMode.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryCsvModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryInvalidNameException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNameAlreadyExistException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNotFoundException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/GenericSQLQuery.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/workingDb/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/DecoratorServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationServiceIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportdb/ExportDbServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportquery/ExportQueryServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdb/
Modified:
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseFunctions.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBasePredicates.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/DriverType.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchoBasePersistenceHelper.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchobaseTopiaContexts.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/JdbcConfiguration.java
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java
trunk/echobase-domain/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider
trunk/echobase-domain/src/main/xmi/echobase.zargo
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AbstractImportConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AcousticImportConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AcousticImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CatchesImportConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CatchesImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CellPositionReference.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonImportConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/EchoBaseCsvFileImportResult.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ImportException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/MissionNameAlreadyExistException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/OperationImportConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/OperationImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsImportConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/AcousticImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/AcousticImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/BiometrySampleImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/BiometrySampleImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EchotypeImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EchotypeImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/GearMetadataValueImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/GearMetadataValueImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthAgeKeyImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthAgeKeyImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthWeightKeyImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthWeightKeyImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/MapCellImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/MapCellImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationMetadataValueImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationMetadataValueImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellAssociationImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellAssociationImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellResultImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellResultImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/SubSampleImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/SubSampleImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TotalSampleImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TotalSampleImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransectImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransectImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransitImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransitImportRow.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/VoyageImportModel.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/EchoBaseImportModelFactory.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbMode.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/AbstractImportDbStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/EchoBaseImportStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/FreeImportDbStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/ReferentialImportDbStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/RemoveDataConfiguration.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/RemoveDataService.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/AbstractRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/AcousticRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CatchesRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonAllRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonTransectRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonTransitRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonVoyageRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/LegacyVoyageRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/OperationRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultEsduRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultMapFishRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultMapOtherRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultRegionRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultVoyageRemoveDataStrategy.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationAlreadyExistException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationNotFoundException.java
trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationService.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/EchoBaseTestServiceSupport.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FakeEchoBaseServiceContext.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FixCellsIT.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AbstractRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AcousticRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CatchesRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonAllRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransectRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransitRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonVoyageRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/OperationRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultEsduRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveFishDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveOtherDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultRegionRemoveDataServiceTest.java
trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultVoyageRemoveDataServiceTest.java
trunk/echobase-services/update-import-data-db.sh
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/CellLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/DataMetadataLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/EntityLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/GearMetadataLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationMetadataLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/ReferenceDatumLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SampleLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SpeciesCategoryLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/StrataLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VesselLoader.java
trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VoyageLoader.java
trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/AbstractToolTest.java
trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/AbstractLoaderIT.java
trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/CellLoaderIT.java
trunk/echobase-ui/pom.xml
trunk/echobase-ui/src/main/assembly/dist/help.sql
trunk/echobase-ui/src/main/assembly/dist/postgis-structure.sql
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationContext.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseInternalDbTransactionFilter.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractConfigureAction.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractWaitAndExecAction.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/EchoBaseActionSupport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/Home.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/AbstractLoadPage.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ExportTable.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntities.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntity.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetForeignEntities.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ImportTable.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/SaveEntity.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Build.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Configure.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Download.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Configure.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Download.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Export.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/DownloadExportQueryResult.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ExportQueryResult.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/GetExportQueryResult.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ManageExportQuery.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/NewLibreOfficeQuery.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractConfigureImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractLaunchImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureAcousticImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCatchesImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCommonImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureOperationImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureResultsImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/CreateMission.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetDataProcessingsForVoyage.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetVesselsForVoyage.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchAcousticImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCatchesImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCommonImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchOperationImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchResultsImport.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/SelectImportType.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Configure.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Import.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ConfirmDelete.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/Delete.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ImportLogs.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Create.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Delete.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/GetUsers.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Login.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Logout.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Update.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/AbstractWorkingDbAction.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Create.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Delete.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/DownloadDriver.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetImportLogDetail.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetVoyage.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Information.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckLogguedInterceptor.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckUserIsAdmin.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckWorkingDbSelected.java
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/validators/LoginValidator.java
trunk/echobase-ui/src/main/resources/config/struts-user.xml
trunk/echobase-ui/src/main/resources/i18n/echobase-ui_en_GB.properties
trunk/echobase-ui/src/main/resources/i18n/echobase-ui_fr_FR.properties
trunk/echobase-ui/src/main/resources/struts.xml
trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml
trunk/echobase-ui/src/main/webapp/WEB-INF/decorators/layout-default.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/includes/footer.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/includes/header.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Create.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Delete.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Update.jsp
trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/workingDb/manage.jsp
trunk/echobase-ui/src/main/webapp/js/gridHelper.js
trunk/pom.xml
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseApplicationConfigProvider.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseApplicationConfigProvider.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseApplicationConfigProvider.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,61 +0,0 @@
-package fr.ifremer.echobase;
-
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-import org.nuiton.config.ApplicationConfigProvider;
-import org.nuiton.config.ConfigActionDef;
-import org.nuiton.config.ConfigOptionDef;
-
-import java.util.Locale;
-
-import static org.nuiton.i18n.I18n.l_;
-
-/**
- * To generate configuration report.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.1
- */
-public class EchoBaseApplicationConfigProvider implements ApplicationConfigProvider {
-
- @Override
- public String getName() {
- return "echobase";
- }
-
- @Override
- public String getDescription(Locale locale) {
- return l_(locale, "echobase.configuration.description");
- }
-
- @Override
- public ConfigOptionDef[] getOptions() {
- return EchoBaseConfigurationOption.values();
- }
-
- @Override
- public ConfigActionDef[] getActions() {
- return new ConfigActionDef[0];
- }
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfiguration.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfiguration.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,239 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase;
-
-import com.google.common.base.Preconditions;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.config.ApplicationConfig;
-import org.nuiton.config.ArgumentsParserException;
-import org.nuiton.util.FileUtil;
-import org.nuiton.util.Version;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * EchoBase configuration.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public class EchoBaseConfiguration {
-
- /** Logger. */
- protected static final Log log =
- LogFactory.getLog(EchoBaseConfiguration.class);
-
- public static final String OPTION_UPDATE_SCHEMA = "updateSchema";
-
- public static final String OPTION_AUTO_LOGIN = "autoLogin";
-
- /** Delegate application config object containing configuration. */
- protected ApplicationConfig applicationConfig;
-
- public EchoBaseConfiguration() {
- this(null);
- }
-
- public EchoBaseConfiguration(Properties propos) {
-
- EchoBaseDateConverter.initDateConverter();
-
- applicationConfig = new ApplicationConfig();
- applicationConfig.setConfigFileName("echobase.properties");
-
- if (log.isInfoEnabled()) {
- log.info(this + " is initializing...");
- }
- try {
- applicationConfig.loadDefaultOptions(
- EchoBaseConfigurationOption.values());
- if (propos != null) {
- for (Map.Entry<Object, Object> entry : propos.entrySet()) {
-
- applicationConfig.setDefaultOption(
- String.valueOf(entry.getKey()),
- String.valueOf(entry.getValue())
- );
- }
- }
- applicationConfig.parse();
-
- File dataDirectory = getDataDirectory();
- String dataDirectoryPath = dataDirectory.getAbsolutePath();
- if (log.isInfoEnabled()) {
- log.info("Data directory = " + dataDirectoryPath);
- }
- if (dataDirectoryPath.endsWith(".")) {
- dataDirectoryPath = dataDirectory.getParentFile().getAbsolutePath();
- if (log.isInfoEnabled()) {
- log.info("Not absolute data directory " + dataDirectory + " will use " + dataDirectoryPath);
- }
-
- // always use the absolue path (in cas of embedded db,
- // we wants to have it.
- applicationConfig.setOption(
- EchoBaseConfigurationOption.DATA_DIRECTORY.key,
- dataDirectoryPath
- );
- }
-
- } catch (ArgumentsParserException e) {
- throw new EchoBaseTechnicalException(
- "Could not parse configuration", e);
- }
-
- createDirectory(EchoBaseConfigurationOption.DATA_DIRECTORY);
- try {
-// FileUtils.forceMkdir(getWarDirectory());
- FileUtils.forceMkdir(getLibDirectory());
- } catch (IOException e) {
- throw new EchoBaseTechnicalException(e);
- }
-
- if (log.isDebugEnabled()) {
- log.debug("parsed options in config file" +
- applicationConfig.getOptions());
- }
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.toString(this);
- }
-
- public Properties getProperties() {
- Properties result = applicationConfig.getFlatOptions();
- return result;
- }
-
- public File getDataDirectory() {
- File file = applicationConfig.getOptionAsFile(
- EchoBaseConfigurationOption.DATA_DIRECTORY.key);
- Preconditions.checkNotNull(file);
- return file;
- }
-
- public File getInternalDbDirectory() {
- File file = applicationConfig.getOptionAsFile(
- EchoBaseConfigurationOption.INTERNAL_DB_DIRECTORY.key);
- Preconditions.checkNotNull(file);
- return file;
- }
-
- public File getLibDirectory() {
- File file = new File(getDataDirectory(), "lib");
- Preconditions.checkNotNull(file);
- return file;
- }
-
- public File getWarLocation() {
- File file = applicationConfig.getOptionAsFile(
- EchoBaseConfigurationOption.WAR_LOCATION.key);
- Preconditions.checkNotNull(file);
- return file;
- }
-
- public char getCsvSeparator() {
- char csvSeparator = applicationConfig.getOption(
- char.class, EchoBaseConfigurationOption.CSV_SEPARATOR.key);
- Preconditions.checkNotNull(csvSeparator);
- return csvSeparator;
- }
-
- public Version getApplicationVersion() {
- Version v = applicationConfig.getOptionAsVersion(
- EchoBaseConfigurationOption.VERSION.key);
- Preconditions.checkNotNull(v);
- return v;
- }
-
- public String getH2Version() {
- String v = applicationConfig.getOption(
- EchoBaseConfigurationOption.H2_VERSION.key);
- Preconditions.checkNotNull(v);
- return v;
- }
-
- public String getPostgresqlVersion() {
- String v = applicationConfig.getOption(
- EchoBaseConfigurationOption.POSTGRESQL_VERSION.key);
- Preconditions.checkNotNull(v);
- return v;
- }
-
- public boolean isEmbedded() {
- Boolean result = applicationConfig.getOptionAsBoolean(
- EchoBaseConfigurationOption.EMBEDDED.key);
- return result != null && result;
- }
-
- public URL getDocumentationUrl() {
- URL result = applicationConfig.getOptionAsURL(
- EchoBaseConfigurationOption.DOCUMENTATION_URL.key);
- return result;
- }
-
- public boolean getOptionAsBoolean(String propertyName) {
- Boolean result = applicationConfig.getOptionAsBoolean(propertyName);
- return result != null && result;
- }
-
- public boolean isUpdateSchema() {
- Boolean result = applicationConfig.getOptionAsBoolean(OPTION_UPDATE_SCHEMA);
- return result != null && result;
- }
-
- /**
- * Creates a directory given the configuration given key.
- *
- * @param key the configuration option key which contains the location of
- * the directory to create
- */
- private void createDirectory(EchoBaseConfigurationOption key) {
-
- File directory = applicationConfig.getOptionAsFile(key.getKey());
-
- Preconditions.checkNotNull(
- directory,
- "Could not find directory " + directory + " (key " +
- key +
- "in your configuration file named echobase.properties)"
- );
- if (log.isInfoEnabled()) {
- log.info(key + " = " + directory);
- }
- try {
- FileUtil.createDirectoryIfNecessary(directory);
- } catch (IOException e) {
- throw new EchoBaseTechnicalException(
- "Could not create directory " + directory, e);
- }
- }
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfigurationOption.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfigurationOption.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfigurationOption.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,140 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase;
-
-import org.nuiton.util.Version;
-import org.nuiton.config.ConfigOptionDef;
-
-import java.io.File;
-import java.net.URL;
-
-import static org.nuiton.i18n.I18n.n_;
-
-/**
- * All EchoBase configuration options.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public enum EchoBaseConfigurationOption implements ConfigOptionDef {
-
- /** Main directory where to put echobase data (logs, and others...). */
- DATA_DIRECTORY("echobase.data.directory",
- n_("echobase.config.data.directory.description"),
- "/var/local/echobase",
- File.class),
- INTERNAL_DB_DIRECTORY(
- "echobase.internal.db.directory",
- n_("echobase.config.internal.db.directory.description"),
- "${echobase.data.directory}/internaldb", File.class),
- EMBEDDED("echobase.embedded",
- n_("echobase.config.embedded.description"),
- "false", boolean.class),
- VERSION("echobase.version",
- n_("echobase.config.version.description"),
- "", Version.class),
- H2_VERSION("echobase.h2Version",
- n_("echobase.config.h2Version.description"),
- "", String.class),
- POSTGRESQL_VERSION("echobase.postgresqlVersion",
- n_("echobase.config.postgresqlVersion.description"),
- "", String.class),
- CSV_SEPARATOR("echobase.csv.separator",
- n_("echobase.config.csv.separator.description"),
- ";", char.class),
- WAR_LOCATION("echobase.war.location",
- n_("echobase.config.war.location.description"),
- "${echobase.data.directory}/war/echobase-ui-${echobase.version}-embedded.war",
- File.class),
- DOCUMENTATION_URL("echobase.documentationUrl",
- n_("echobase.config.documentationUrl.description"),
- "http://maven-site.forge.codelutin.com/echobase",
- URL.class);
-
- /** Configuration key. */
- protected final String key;
-
- /** I18n key of option description */
- protected final String description;
-
- /** Type of option */
- protected final Class<?> type;
-
- /** Default value of option. */
- protected String defaultValue;
-
- EchoBaseConfigurationOption(String key,
- String description,
- String defaultValue,
- Class<?> type) {
- this.key = key;
- this.description = description;
- this.defaultValue = defaultValue;
- this.type = type;
- }
-
- @Override
- public String getKey() {
- return key;
- }
-
- @Override
- public Class<?> getType() {
- return type;
- }
-
- @Override
- public String getDescription() {
- return description;
- }
-
- @Override
- public String getDefaultValue() {
- return defaultValue;
- }
-
- @Override
- public boolean isTransient() {
- return true;
- }
-
- @Override
- public boolean isFinal() {
- return true;
- }
-
- @Override
- public void setDefaultValue(String defaultValue) {
- this.defaultValue = defaultValue;
- }
-
- @Override
- public void setTransient(boolean newValue) {
- // not used
- }
-
- @Override
- public void setFinal(boolean newValue) {
- // not used
- }
-}
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseFunctions.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseFunctions.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseFunctions.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,9 +26,11 @@
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.spatial.CellPoint;
import fr.ifremer.echobase.entities.data.DataProcessing;
import fr.ifremer.echobase.entities.data.Echotype;
import fr.ifremer.echobase.entities.data.Operation;
+import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.Transect;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.AcousticInstrument;
@@ -139,6 +141,13 @@
}
};
+ public static final Function<Result, Cell> RESULT_CELL = new Function<Result, Cell>() {
+ @Override
+ public Cell apply(Result input) {
+ return input.getCell();
+ }
+ };
+
public static final Function<Mission, String> MISSION_NAME = new Function<Mission, String>() {
@Override
public String apply(Mission input) {
@@ -324,6 +333,13 @@
}
};
+ public static final Function<CellPoint,String> CELL_POINT_CELL_ID_FUNCTION = new Function<CellPoint, String>() {
+ @Override
+ public String apply(CellPoint input) {
+ return input.getCellId();
+ }
+ };
+
public static String getSpeciesCategoryKey(Species species, SizeCategory sizeCategory, SexCategory sexCategory) {
String key = species.getBaracoudaCode();
if (sizeCategory != null) {
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBasePredicates.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBasePredicates.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBasePredicates.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,6 +23,7 @@
package fr.ifremer.echobase;
import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
import com.google.common.collect.Sets;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.Echotype;
@@ -72,6 +73,24 @@
}
};
+ public static final Predicate<CellType> IS_ESDU_CELL_TYPE = new Predicate<CellType>() {
+
+ @Override
+ public boolean apply(CellType input) {
+ boolean result = "esdu".equals(input.getId().toLowerCase());
+ return result;
+ }
+ };
+
+ public static final Predicate<CellType> IS_ELEMENTARY_CELL_TYPE = new Predicate<CellType>() {
+
+ @Override
+ public boolean apply(CellType input) {
+ boolean result = "elementary".equals(input.getId().toLowerCase());
+ return result;
+ }
+ };
+
public static final Predicate<CellType> IS_MAP_CELL_TYPE = new Predicate<CellType>() {
public final Set<String> acceptedNames = Sets.newHashSet(
@@ -105,6 +124,28 @@
}
};
+ public static final Predicate<Cell> IS_ELEMENTARY_CELL = new Predicate<Cell>() {
+ @Override
+ public boolean apply(Cell input) {
+ CellType cellType = input.getCellType();
+ boolean result = cellType != null &&
+ IS_ELEMENTARY_CELL_TYPE.apply(cellType);
+ return result;
+ }
+ };
+
+ public static final Predicate<Cell> IS_ESDU_CELL = new Predicate<Cell>() {
+ @Override
+ public boolean apply(Cell input) {
+ CellType cellType = input.getCellType();
+ boolean result = cellType != null &&
+ IS_ESDU_CELL_TYPE.apply(cellType);
+ return result;
+ }
+ };
+
+ public static final Predicate<Cell> IS_POINT_CELL = Predicates.or(IS_ELEMENTARY_CELL, IS_ESDU_CELL);
+
public static final Predicate<Operation> OPERATION_WITH_TOTAL_OR_UNSORTED_SAMPLE = new Predicate<Operation>() {
@Override
public boolean apply(Operation input) {
Copied: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseApplicationConfigProvider.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseApplicationConfigProvider.java)
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseApplicationConfigProvider.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseApplicationConfigProvider.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,61 @@
+package fr.ifremer.echobase.config;
+
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import org.nuiton.config.ApplicationConfigProvider;
+import org.nuiton.config.ConfigActionDef;
+import org.nuiton.config.ConfigOptionDef;
+
+import java.util.Locale;
+
+import static org.nuiton.i18n.I18n.l_;
+
+/**
+ * To generate configuration report.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.1
+ */
+public class EchoBaseApplicationConfigProvider implements ApplicationConfigProvider {
+
+ @Override
+ public String getName() {
+ return "echobase";
+ }
+
+ @Override
+ public String getDescription(Locale locale) {
+ return l_(locale, "echobase.configuration.description");
+ }
+
+ @Override
+ public ConfigOptionDef[] getOptions() {
+ return EchoBaseConfigurationOption.values();
+ }
+
+ @Override
+ public ConfigActionDef[] getActions() {
+ return new ConfigActionDef[0];
+ }
+}
Copied: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfiguration.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfiguration.java)
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfiguration.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,241 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.config;
+
+import com.google.common.base.Preconditions;
+import fr.ifremer.echobase.EchoBaseDateConverter;
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.config.ApplicationConfig;
+import org.nuiton.config.ArgumentsParserException;
+import org.nuiton.util.FileUtil;
+import org.nuiton.util.Version;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * EchoBase configuration.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public class EchoBaseConfiguration {
+
+ /** Logger. */
+ protected static final Log log =
+ LogFactory.getLog(EchoBaseConfiguration.class);
+
+ public static final String OPTION_UPDATE_SCHEMA = "updateSchema";
+
+ public static final String OPTION_AUTO_LOGIN = "autoLogin";
+
+ /** Delegate application config object containing configuration. */
+ protected ApplicationConfig applicationConfig;
+
+ public EchoBaseConfiguration() {
+ this(null);
+ }
+
+ public EchoBaseConfiguration(Properties propos) {
+
+ EchoBaseDateConverter.initDateConverter();
+
+ applicationConfig = new ApplicationConfig();
+ applicationConfig.setConfigFileName("echobase.properties");
+
+ if (log.isInfoEnabled()) {
+ log.info(this + " is initializing...");
+ }
+ try {
+ applicationConfig.loadDefaultOptions(
+ EchoBaseConfigurationOption.values());
+ if (propos != null) {
+ for (Map.Entry<Object, Object> entry : propos.entrySet()) {
+
+ applicationConfig.setDefaultOption(
+ String.valueOf(entry.getKey()),
+ String.valueOf(entry.getValue())
+ );
+ }
+ }
+ applicationConfig.parse();
+
+ File dataDirectory = getDataDirectory();
+ String dataDirectoryPath = dataDirectory.getAbsolutePath();
+ if (log.isInfoEnabled()) {
+ log.info("Data directory = " + dataDirectoryPath);
+ }
+ if (dataDirectoryPath.endsWith(".")) {
+ dataDirectoryPath = dataDirectory.getParentFile().getAbsolutePath();
+ if (log.isInfoEnabled()) {
+ log.info("Not absolute data directory " + dataDirectory + " will use " + dataDirectoryPath);
+ }
+
+ // always use the absolue path (in cas of embedded db,
+ // we wants to have it.
+ applicationConfig.setOption(
+ EchoBaseConfigurationOption.DATA_DIRECTORY.key,
+ dataDirectoryPath
+ );
+ }
+
+ } catch (ArgumentsParserException e) {
+ throw new EchoBaseTechnicalException(
+ "Could not parse configuration", e);
+ }
+
+ createDirectory(EchoBaseConfigurationOption.DATA_DIRECTORY);
+ try {
+// FileUtils.forceMkdir(getWarDirectory());
+ FileUtils.forceMkdir(getLibDirectory());
+ } catch (IOException e) {
+ throw new EchoBaseTechnicalException(e);
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("parsed options in config file" +
+ applicationConfig.getOptions());
+ }
+ }
+
+ @Override
+ public String toString() {
+ return ReflectionToStringBuilder.toString(this);
+ }
+
+ public Properties getProperties() {
+ Properties result = applicationConfig.getFlatOptions();
+ return result;
+ }
+
+ public File getDataDirectory() {
+ File file = applicationConfig.getOptionAsFile(
+ EchoBaseConfigurationOption.DATA_DIRECTORY.key);
+ Preconditions.checkNotNull(file);
+ return file;
+ }
+
+ public File getInternalDbDirectory() {
+ File file = applicationConfig.getOptionAsFile(
+ EchoBaseConfigurationOption.INTERNAL_DB_DIRECTORY.key);
+ Preconditions.checkNotNull(file);
+ return file;
+ }
+
+ public File getLibDirectory() {
+ File file = new File(getDataDirectory(), "lib");
+ Preconditions.checkNotNull(file);
+ return file;
+ }
+
+ public File getWarLocation() {
+ File file = applicationConfig.getOptionAsFile(
+ EchoBaseConfigurationOption.WAR_LOCATION.key);
+ Preconditions.checkNotNull(file);
+ return file;
+ }
+
+ public char getCsvSeparator() {
+ char csvSeparator = applicationConfig.getOption(
+ char.class, EchoBaseConfigurationOption.CSV_SEPARATOR.key);
+ Preconditions.checkNotNull(csvSeparator);
+ return csvSeparator;
+ }
+
+ public Version getApplicationVersion() {
+ Version v = applicationConfig.getOptionAsVersion(
+ EchoBaseConfigurationOption.VERSION.key);
+ Preconditions.checkNotNull(v);
+ return v;
+ }
+
+ public String getH2Version() {
+ String v = applicationConfig.getOption(
+ EchoBaseConfigurationOption.H2_VERSION.key);
+ Preconditions.checkNotNull(v);
+ return v;
+ }
+
+ public String getPostgresqlVersion() {
+ String v = applicationConfig.getOption(
+ EchoBaseConfigurationOption.POSTGRESQL_VERSION.key);
+ Preconditions.checkNotNull(v);
+ return v;
+ }
+
+ public boolean isEmbedded() {
+ Boolean result = applicationConfig.getOptionAsBoolean(
+ EchoBaseConfigurationOption.EMBEDDED.key);
+ return result != null && result;
+ }
+
+ public URL getDocumentationUrl() {
+ URL result = applicationConfig.getOptionAsURL(
+ EchoBaseConfigurationOption.DOCUMENTATION_URL.key);
+ return result;
+ }
+
+ public boolean getOptionAsBoolean(String propertyName) {
+ Boolean result = applicationConfig.getOptionAsBoolean(propertyName);
+ return result != null && result;
+ }
+
+ public boolean isUpdateSchema() {
+ Boolean result = applicationConfig.getOptionAsBoolean(OPTION_UPDATE_SCHEMA);
+ return result != null && result;
+ }
+
+ /**
+ * Creates a directory given the configuration given key.
+ *
+ * @param key the configuration option key which contains the location of
+ * the directory to create
+ */
+ private void createDirectory(EchoBaseConfigurationOption key) {
+
+ File directory = applicationConfig.getOptionAsFile(key.getKey());
+
+ Preconditions.checkNotNull(
+ directory,
+ "Could not find directory " + directory + " (key " +
+ key +
+ "in your configuration file named echobase.properties)"
+ );
+ if (log.isInfoEnabled()) {
+ log.info(key + " = " + directory);
+ }
+ try {
+ FileUtil.createDirectoryIfNecessary(directory);
+ } catch (IOException e) {
+ throw new EchoBaseTechnicalException(
+ "Could not create directory " + directory, e);
+ }
+ }
+}
Copied: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfigurationOption.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/EchoBaseConfigurationOption.java)
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfigurationOption.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/config/EchoBaseConfigurationOption.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,140 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.config;
+
+import org.nuiton.util.Version;
+import org.nuiton.config.ConfigOptionDef;
+
+import java.io.File;
+import java.net.URL;
+
+import static org.nuiton.i18n.I18n.n_;
+
+/**
+ * All EchoBase configuration options.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public enum EchoBaseConfigurationOption implements ConfigOptionDef {
+
+ /** Main directory where to put echobase data (logs, and others...). */
+ DATA_DIRECTORY("echobase.data.directory",
+ n_("echobase.config.data.directory.description"),
+ "/var/local/echobase",
+ File.class),
+ INTERNAL_DB_DIRECTORY(
+ "echobase.internal.db.directory",
+ n_("echobase.config.internal.db.directory.description"),
+ "${echobase.data.directory}/internaldb", File.class),
+ EMBEDDED("echobase.embedded",
+ n_("echobase.config.embedded.description"),
+ "false", boolean.class),
+ VERSION("echobase.version",
+ n_("echobase.config.version.description"),
+ "", Version.class),
+ H2_VERSION("echobase.h2Version",
+ n_("echobase.config.h2Version.description"),
+ "", String.class),
+ POSTGRESQL_VERSION("echobase.postgresqlVersion",
+ n_("echobase.config.postgresqlVersion.description"),
+ "", String.class),
+ CSV_SEPARATOR("echobase.csv.separator",
+ n_("echobase.config.csv.separator.description"),
+ ";", char.class),
+ WAR_LOCATION("echobase.war.location",
+ n_("echobase.config.war.location.description"),
+ "${echobase.data.directory}/war/echobase-ui-${echobase.version}-embedded.war",
+ File.class),
+ DOCUMENTATION_URL("echobase.documentationUrl",
+ n_("echobase.config.documentationUrl.description"),
+ "http://maven-site.forge.codelutin.com/echobase",
+ URL.class);
+
+ /** Configuration key. */
+ protected final String key;
+
+ /** I18n key of option description */
+ protected final String description;
+
+ /** Type of option */
+ protected final Class<?> type;
+
+ /** Default value of option. */
+ protected String defaultValue;
+
+ EchoBaseConfigurationOption(String key,
+ String description,
+ String defaultValue,
+ Class<?> type) {
+ this.key = key;
+ this.description = description;
+ this.defaultValue = defaultValue;
+ this.type = type;
+ }
+
+ @Override
+ public String getKey() {
+ return key;
+ }
+
+ @Override
+ public Class<?> getType() {
+ return type;
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+ @Override
+ public String getDefaultValue() {
+ return defaultValue;
+ }
+
+ @Override
+ public boolean isTransient() {
+ return true;
+ }
+
+ @Override
+ public boolean isFinal() {
+ return true;
+ }
+
+ @Override
+ public void setDefaultValue(String defaultValue) {
+ this.defaultValue = defaultValue;
+ }
+
+ @Override
+ public void setTransient(boolean newValue) {
+ // not used
+ }
+
+ @Override
+ public void setFinal(boolean newValue) {
+ // not used
+ }
+}
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/DriverType.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/DriverType.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/DriverType.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
* #L%
*/
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
import fr.ifremer.echobase.I18nAble;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.PostgreSQL82Dialect;
@@ -91,4 +91,15 @@
return i18nKey;
}
+ public static DriverType valueOfDriverName(String driverName) {
+ DriverType result = null;
+ for (DriverType driverType : values()) {
+ if (driverName.equals(driverType.getDriverClass().getName())) {
+ result = driverType;
+ break;
+ }
+ }
+ return result;
+ }
+
}
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,14 @@
+package fr.ifremer.echobase.entities;
+
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaReplicationSupport;
+import org.nuiton.topia.TopiaTransaction;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public interface EchoBaseInternalPersistenceContext extends TopiaTransaction, TopiaPersistenceContext, TopiaReplicationSupport {
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBaseInternalPersistenceContext.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,17 @@
+package fr.ifremer.echobase.entities;
+
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaSqlSupport;
+import org.nuiton.topia.TopiaTransaction;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public interface EchoBasePersistenceContext extends TopiaTransaction, TopiaPersistenceContext, TopiaSqlSupport {
+
+ TopiaContext getContext();
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/EchoBasePersistenceContext.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,150 @@
+package fr.ifremer.echobase.entities;
+
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaReplicationSupport;
+import org.nuiton.topia.TopiaTransaction;
+import org.nuiton.topia.framework.TopiaSQLQuery;
+import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaIdFactory;
+
+import java.util.List;
+import java.util.Properties;
+
+public class TopiaEchoBaseInternalPersistenceContext extends AbstractTopiaEchoBaseInternalPersistenceContext {
+
+ public TopiaEchoBaseInternalPersistenceContext(TopiaContext context) {
+ super(context);
+ }
+
+ @Override
+ public void commitTransaction() {
+ getTransaction().commitTransaction();
+ }
+
+ @Override
+ public void rollbackTransaction() {
+ getTransaction().rollbackTransaction();
+ }
+
+ @Override
+ public void closeContext() {
+ getTransaction().closeContext();
+ }
+
+ @Override
+ public boolean isClosed() {
+ return getTransaction().isClosed();
+ }
+
+ @Override
+ public <E extends TopiaEntity> E findByTopiaId(java.lang.String topiaId) {
+ return getPersistenceContext().findByTopiaId(topiaId);
+ }
+
+ @Override
+ public void update(TopiaEntity entity) {
+ getPersistenceContext().update(entity);
+ }
+
+ @Override
+ public TopiaIdFactory getTopiaIdFactory() {
+ return getPersistenceContext().getTopiaIdFactory();
+ }
+
+ @Override
+ public List<Class<?>> getPersistenceClasses() {
+ return getPersistenceContext().getPersistenceClasses();
+ }
+
+ @Override
+ public void setUseFlushMode(boolean useFlushMode) {
+ getPersistenceContext().setUseFlushMode(useFlushMode);
+ }
+
+ @Override
+ public Properties getConfig() {
+ return getPersistenceContext().getConfig();
+ }
+
+ @Override
+ public <E extends TopiaEntity> TopiaDAO<E> getDAO(Class<E> entityClass) {
+ return getPersistenceContext().getDAO(entityClass);
+ }
+
+ @Override
+ public <E extends TopiaEntity, D extends TopiaDAO<E>> D getDAO(Class<E> entityClass, Class<D> daoClass) {
+ return getPersistenceContext().getDAO(entityClass, daoClass);
+ }
+
+ @Override
+ public boolean isSchemaEmpty() {
+ return getPersistenceContext().isSchemaEmpty();
+ }
+
+ @Override
+ public boolean isTableExists(Class<?> clazz) {
+ return getPersistenceContext().isTableExists(clazz);
+ }
+
+ @Override
+ public java.lang.String getSchemaName() {
+ return getPersistenceContext().getSchemaName();
+ }
+
+ @Override
+ public void createSchema() {
+ getPersistenceContext().createSchema();
+ }
+
+ @Override
+ public void showCreateSchema() {
+ getPersistenceContext().showCreateSchema();
+ }
+
+ @Override
+ public void updateSchema() {
+ getPersistenceContext().updateSchema();
+ }
+
+ @Override
+ public void dropSchema() {
+ getPersistenceContext().dropSchema();
+ }
+
+ @Override
+ public void replicate(TopiaContext destinationContext, Object... entityAndCondition) throws IllegalArgumentException {
+ getReplicationSupport().replicate(destinationContext, entityAndCondition);
+ }
+
+ @Override
+ public <T extends TopiaEntity> void replicateEntity(TopiaContext destinationContext, T entity) throws IllegalArgumentException {
+ getReplicationSupport().replicateEntity(destinationContext, entity);
+ }
+
+ @Override
+ public <T extends TopiaEntity> void replicateEntities(TopiaContext destinationContext, List<T> entities) throws IllegalArgumentException {
+ getReplicationSupport().replicateEntities(destinationContext, entities);
+ }
+
+ public <R> R findSingleResult(TopiaSQLQuery<R> sqlQuery) {
+ return sqlQuery.findSingleResult(context);
+ }
+
+ public <R> List<R> findMultipleResult(TopiaSQLQuery<R> sqlQuery) {
+ return sqlQuery.findMultipleResult(context);
+ }
+
+ protected TopiaTransaction getTransaction() {
+ return context;
+ }
+
+ protected TopiaPersistenceContext getPersistenceContext() {
+ return context;
+ }
+
+ protected TopiaReplicationSupport getReplicationSupport() {
+ return context;
+ }
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBaseInternalPersistenceContext.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,205 @@
+package fr.ifremer.echobase.entities;
+
+import com.google.common.base.Preconditions;
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import org.apache.commons.lang3.StringUtils;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaSqlSupport;
+import org.nuiton.topia.TopiaTransaction;
+import org.nuiton.topia.framework.TopiaSQLQuery;
+import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaIdFactory;
+
+import java.util.List;
+import java.util.Properties;
+
+public class TopiaEchoBasePersistenceContext extends AbstractTopiaEchoBasePersistenceContext {
+
+ public TopiaEchoBasePersistenceContext(TopiaContext context) {
+ super(context);
+ }
+
+ @Override
+ public void commitTransaction() {
+ getTransaction().commitTransaction();
+ }
+
+ @Override
+ public void rollbackTransaction() {
+ getTransaction().rollbackTransaction();
+ }
+
+ @Override
+ public void closeContext() {
+ getTransaction().closeContext();
+ }
+
+ @Override
+ public boolean isClosed() {
+ return getTransaction().isClosed();
+ }
+
+ @Override
+ public <E extends TopiaEntity> E findByTopiaId(java.lang.String topiaId) {
+ return getPersistenceContext().findByTopiaId(topiaId);
+ }
+
+ @Override
+ public void update(TopiaEntity entity) {
+ getPersistenceContext().update(entity);
+ }
+
+ @Override
+ public TopiaIdFactory getTopiaIdFactory() {
+ return getPersistenceContext().getTopiaIdFactory();
+ }
+
+ @Override
+ public List<Class<?>> getPersistenceClasses() {
+ return getPersistenceContext().getPersistenceClasses();
+ }
+
+ @Override
+ public void setUseFlushMode(boolean useFlushMode) {
+ getPersistenceContext().setUseFlushMode(useFlushMode);
+ }
+
+ @Override
+ public Properties getConfig() {
+ return getPersistenceContext().getConfig();
+ }
+
+ @Override
+ public <E extends TopiaEntity> TopiaDAO<E> getDAO(Class<E> entityClass) {
+ return getPersistenceContext().getDAO(entityClass);
+ }
+
+ @Override
+ public <E extends TopiaEntity, D extends TopiaDAO<E>> D getDAO(Class<E> entityClass, Class<D> daoClass) {
+ return getPersistenceContext().getDAO(entityClass, daoClass);
+ }
+
+ @Override
+ public boolean isSchemaEmpty() {
+ return getPersistenceContext().isSchemaEmpty();
+ }
+
+ @Override
+ public boolean isTableExists(Class<?> clazz) {
+ return getPersistenceContext().isTableExists(clazz);
+ }
+
+ @Override
+ public java.lang.String getSchemaName() {
+ return getPersistenceContext().getSchemaName();
+ }
+
+ @Override
+ public void createSchema() {
+ getPersistenceContext().createSchema();
+ }
+
+ @Override
+ public void showCreateSchema() {
+ getPersistenceContext().showCreateSchema();
+ }
+
+ @Override
+ public void updateSchema() {
+ getPersistenceContext().updateSchema();
+ }
+
+ @Override
+ public void dropSchema() {
+ getPersistenceContext().dropSchema();
+ }
+
+ @Override
+ public void executeSQL(String sqlScript) {
+ getTopiaSqlSupport().executeSQL(sqlScript);
+ }
+
+ public final <E extends TopiaEntity> E getEntityById(Class<E> entityType, String id) {
+ Preconditions.checkNotNull(entityType);
+ Preconditions.checkArgument(StringUtils.isNotEmpty(id));
+ try {
+ E result = getDAO(entityType).findByTopiaId(id);
+ return result;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not obtain data of id [" + id + "] for type " +
+ entityType, eee);
+ }
+ }
+
+ public final <E extends TopiaEntity> E getEntityOrNullById(Class<E> entityType, String id) {
+ Preconditions.checkNotNull(entityType);
+ if (StringUtils.isBlank(id)) {
+ return null;
+ }
+ return getEntityById(entityType, id);
+ }
+
+ public void flush() {
+ context.getHibernateSession().flush();
+ }
+
+ public void clear() {
+ context.getHibernateSession().clear();
+ }
+
+ protected TopiaTransaction getTransaction() {
+ return context;
+ }
+
+ protected TopiaSqlSupport getTopiaSqlSupport() {
+ return context;
+ }
+
+ protected TopiaPersistenceContext getPersistenceContext() {
+ return context;
+ }
+
+ @Override
+ public TopiaContext getContext() {
+ return context;
+ }
+
+ public <R> R findSingleResult(TopiaSQLQuery<R> sqlQuery) {
+ return sqlQuery.findSingleResult(context);
+ }
+
+ public <R> List<R> findMultipleResult(TopiaSQLQuery<R> sqlQuery) {
+ return sqlQuery.findMultipleResult(context);
+ }
+
+
+ public boolean canUpdatePostgis() {
+ String dialect = context.getHibernateConfiguration().getProperty(TopiaContextFactory.CONFIG_DIALECT);
+
+ return DriverType.POSTGRESQL.getDialectClass().getName().equals(dialect);
+ }
+
+ public boolean isSpatialAware() {
+ boolean result = canUpdatePostgis();
+
+ if (result) {
+
+ // on pg db, check there is now a echobase_spatial_cell
+ try {
+ executeSQL("select count(*) from echobase_cell_spatial;");
+ } catch (Exception e) {
+ // table not found (or other, ...)
+ result = false;
+ // rollback (otherwise transaction will stay dirty)
+ rollbackTransaction();
+ }
+ }
+ return result;
+ }
+
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/TopiaEchoBasePersistenceContext.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/data/CellDAOImpl.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/data/CellDAOImpl.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/data/CellDAOImpl.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,104 @@
+package fr.ifremer.echobase.entities.data;
+
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import com.google.common.collect.Lists;
+import fr.ifremer.echobase.EchoBasePredicates;
+import fr.ifremer.echobase.entities.spatial.CellPoint;
+import org.nuiton.topia.framework.TopiaSQLQuery;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+public class CellDAOImpl<E extends Cell> extends CellDAOAbstract<E> {
+
+ public List<CellPoint> getVoyageCellPoints(Voyage voyage) {
+
+ List<CellPoint> result = Lists.newArrayList();
+
+ TopiaSQLQuery<CellPoint> queryPoint = newLatLongSqlQuery(voyage.getTopiaId());
+ TopiaSQLQuery<CellPoint> queryPoint3D = newLatLongDepthSqlQuery(voyage.getTopiaId());
+
+ result.addAll(queryPoint.findMultipleResult(context));
+ result.addAll(queryPoint3D.findMultipleResult(context));
+ return result;
+ }
+
+ public CellPoint getPoint(E cell) {
+
+ TopiaSQLQuery<CellPoint> query = null;
+ if (EchoBasePredicates.IS_ESDU_CELL.apply(cell)) {
+
+ query = newLatLongSqlQuery(cell.getTopiaId());
+ } else if (EchoBasePredicates.IS_ELEMENTARY_CELL.apply(cell)) {
+ query = newLatLongDepthSqlQuery(cell.getTopiaId());
+ }
+ CellPoint result = query == null ? null : query.findSingleResult(context);
+ return result;
+ }
+
+ protected TopiaSQLQuery<CellPoint> newLatLongSqlQuery(final String voyageId) {
+ return new TopiaSQLQuery<CellPoint>() {
+ @Override
+ protected PreparedStatement prepareQuery(Connection connection) throws SQLException {
+
+ PreparedStatement ps = connection.prepareStatement("SELECT cellId, ST_Y(ST_ASTEXT(coordinate)), ST_X(ST_ASTEXT(coordinate)) FROM echobase_cell_spatial WHERE coordinate IS NOT NULL AND voyageId = ?");
+ ps.setString(1, voyageId);
+ return ps;
+ }
+
+ @Override
+ protected CellPoint prepareResult(ResultSet set) throws SQLException {
+ String cellId = set.getString(1);
+ Double latitude = set.getDouble(2);
+ Double longitude = set.getDouble(3);
+ return new CellPoint(cellId, latitude, longitude, 0d);
+ }
+ };
+ }
+
+ protected TopiaSQLQuery<CellPoint> newLatLongDepthSqlQuery(final String voyageId) {
+ return new TopiaSQLQuery<CellPoint>() {
+ @Override
+ protected PreparedStatement prepareQuery(Connection connection) throws SQLException {
+
+ PreparedStatement ps = connection.prepareStatement("SELECT cellId, ST_Y(ST_ASTEXT(coordinate3D)), ST_X(ST_ASTEXT(coordinate3D)) , ST_Y(ST_ASTEXT(coordinate3D)) FROM echobase_cell_spatial WHERE coordinate3D IS NOT NULL AND voyageId = ?");
+ ps.setString(1, voyageId);
+ return ps;
+ }
+
+ @Override
+ protected CellPoint prepareResult(ResultSet set) throws SQLException {
+ String cellId = set.getString(1);
+ Double latitude = set.getDouble(2);
+ Double longitude = set.getDouble(3);
+ Double depth = set.getDouble(4);
+ return new CellPoint(cellId, latitude, longitude, depth);
+ }
+ };
+ }
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/data/CellDAOImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/CellPoint.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/CellPoint.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/CellPoint.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,64 @@
+package fr.ifremer.echobase.entities.spatial;
+
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import java.io.Serializable;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class CellPoint implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ protected final String cellId;
+
+ protected final double x, y, z;
+
+ public CellPoint(String cellId, double x, double y, double z) {
+ this.cellId = cellId;
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ public String getCellId() {
+ return cellId;
+ }
+
+ public double getX() {
+ return x;
+ }
+
+ public double getY() {
+ return y;
+ }
+
+ public double getZ() {
+ return z;
+ }
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/CellPoint.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,116 @@
+package fr.ifremer.echobase.entities.spatial;
+
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL:$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import java.io.Serializable;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class SpatialConfiguration implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** Selected jdbc url (can't be null). */
+ protected String jdbcUrl;
+
+ /** Selected voyage id (can't be null). */
+ protected String voyageId;
+
+ /** Selected data metadata id (can't be null). */
+ protected String dataMetadataId;
+
+ /** Selected species id (can be null). */
+ protected String speciesId;
+
+ /** Selected echotype id (can be null). */
+ protected String echotypeId;
+
+ public String getJdbcUrl() {
+ return jdbcUrl;
+ }
+
+ public void setJdbcUrl(String jdbcUrl) {
+ this.jdbcUrl = jdbcUrl;
+ }
+
+ public String getVoyageId() {
+ return voyageId;
+ }
+
+ public void setVoyageId(String voyageId) {
+ this.voyageId = voyageId;
+ }
+
+ public String getDataMetadataId() {
+ return dataMetadataId;
+ }
+
+ public void setDataMetadataId(String dataMetadataId) {
+ this.dataMetadataId = dataMetadataId;
+ }
+
+ public String getSpeciesId() {
+ return speciesId;
+ }
+
+ public void setSpeciesId(String speciesId) {
+ this.speciesId = speciesId;
+ }
+
+ public String getEchotypeId() {
+ return echotypeId;
+ }
+
+ public void setEchotypeId(String echotypeId) {
+ this.echotypeId = echotypeId;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof SpatialConfiguration)) return false;
+
+ SpatialConfiguration that = (SpatialConfiguration) o;
+
+ return !(jdbcUrl != null ? !jdbcUrl.equals(that.jdbcUrl) : that.jdbcUrl != null) &&
+ !(dataMetadataId != null ? !dataMetadataId.equals(that.dataMetadataId) : that.dataMetadataId != null) &&
+ !(echotypeId != null ? !echotypeId.equals(that.echotypeId) : that.echotypeId != null) &&
+ !(speciesId != null ? !speciesId.equals(that.speciesId) : that.speciesId != null) &&
+ !(voyageId != null ? !voyageId.equals(that.voyageId) : that.voyageId != null);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = jdbcUrl == null ? 0 : jdbcUrl.hashCode();
+ result = 31 * result + (voyageId == null ? 0 : voyageId.hashCode());
+ result = 31 * result + (dataMetadataId == null ? 0 : dataMetadataId.hashCode());
+ result = 31 * result + (speciesId == null ? 0 : speciesId.hashCode());
+ result = 31 * result + (echotypeId == null ? 0 : echotypeId.hashCode());
+ return result;
+ }
+}
\ No newline at end of file
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialConfiguration.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,73 @@
+package fr.ifremer.echobase.entities.spatial;
+
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.references.DataMetadata;
+
+import java.io.Serializable;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class SpatialData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ protected CellPoint point;
+
+ protected Result result;
+
+ public void setPoint(CellPoint point) {
+ this.point = point;
+ }
+
+ public void setResult(Result result) {
+ this.result = result;
+ }
+
+ public double getLatitude() {
+ return point.getY();
+ }
+
+ public double getLongitude() {
+ return point.getX();
+ }
+
+ public double getDepth() {
+ return point.getZ();
+ }
+
+ public DataMetadata getDataMetadata() {
+ return result.getDataMetadata();
+ }
+
+ public Serializable getDataValue() {
+ return result.getResultValue();
+ }
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialData.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,72 @@
+package fr.ifremer.echobase.entities.spatial;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.Serializable;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class SpatialDataCache implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(SpatialDataCache.class);
+
+ protected final Map<SpatialConfiguration, Set<SpatialData>> cache =
+ Maps.newHashMap();
+
+
+ public Set<SpatialData> get(SpatialConfiguration configuration) {
+ return cache.get(configuration);
+ }
+
+ public void put(SpatialConfiguration configuration, Set<SpatialData> data) {
+ cache.put(configuration, Collections.unmodifiableSet(data));
+ }
+
+ public void onDbChanged(String jdbcUrl) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Revoking spatial data cache for db: " + jdbcUrl);
+ }
+
+ Set<SpatialConfiguration> keys = Sets.newHashSet(cache.keySet());
+ for (SpatialConfiguration key : keys) {
+ if (jdbcUrl.equals(key.getJdbcUrl())) {
+ cache.remove(key);
+ }
+ }
+ }
+
+ public void onVoyageChanged(String jdbcUrl, String voyageId) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Revoking spatial data cache for db/voyage: " + jdbcUrl +
+ "/" + voyageId);
+ }
+
+ Set<SpatialConfiguration> keys = Sets.newHashSet(cache.keySet());
+ for (SpatialConfiguration key : keys) {
+ if (jdbcUrl.equals(key.getJdbcUrl()) &&
+ voyageId.equals(key.getVoyageId())) {
+ cache.remove(key);
+ }
+ }
+ }
+
+ public void clear() {
+ cache.clear();
+ }
+
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/entities/spatial/SpatialDataCache.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchoBasePersistenceHelper.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchoBasePersistenceHelper.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchoBasePersistenceHelper.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,11 +23,9 @@
* #L%
*/
-import fr.ifremer.echobase.EchoBaseTechnicalException;
import fr.ifremer.echobase.entities.EchoBaseDAOHelper;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaPersistenceHelper;
@@ -56,12 +54,36 @@
return (TopiaDAO<E>) getDAO(tx, type.getContract());
}
- public final void flushTransaction(TopiaContext tx, String errorMessage) {
- try {
- tx.getHibernateSession().flush();
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException(errorMessage, e);
- }
- }
+// public final void flushTransaction(TopiaContext tx, String errorMessage) {
+// try {
+// tx.getHibernateSession().flush();
+// } catch (TopiaException e) {
+// throw new EchoBaseTechnicalException(errorMessage, e);
+// }
+// }
+// public boolean canUpdatePostgis(TopiaContext tx) {
+// String dialect = tx.getHibernateConfiguration().getProperty(TopiaContextFactory.CONFIG_DIALECT);
+//
+// return DriverType.POSTGRESQL.getDialectClass().getName().equals(dialect);
+// }
+
+// public boolean isSpatialAware(TopiaContext tx) {
+// boolean result = canUpdatePostgis(tx);
+//
+// if (result) {
+//
+// // on pg db, check there is now a echobase_spatial_cell
+// try {
+// ((TopiaSqlSupport) tx).executeSQL("select count(*) from echobase_cell_spatial;");
+// } catch (Exception e) {
+// // table not found (or other, ...)
+// result = false;
+// // rollback (otherwise transaction will stay dirty)
+// ((TopiaTransaction) tx).rollbackTransaction();
+// }
+// }
+// return result;
+// }
+
}
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchobaseTopiaContexts.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchobaseTopiaContexts.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/EchobaseTopiaContexts.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
*/
import com.google.common.base.Charsets;
-import fr.ifremer.echobase.EchoBaseConfigurationOption;
+import fr.ifremer.echobase.config.EchoBaseConfigurationOption;
import fr.ifremer.echobase.EchoBaseTechnicalException;
import fr.ifremer.echobase.entities.DriverType;
import fr.ifremer.echobase.entities.EchoBaseDAOHelper;
@@ -197,17 +197,11 @@
return result;
}
- public static void reloadProperty(Properties properties,
+ private static void reloadProperty(Properties properties,
String propertyName,
String propertyNameToRemove) {
Object o = properties.getProperty(propertyName);
properties.put(propertyName, o);
properties.remove(propertyNameToRemove);
}
-
- public static boolean canUpdatePostgis(TopiaContext tx) {
- String dialect = tx.getHibernateConfiguration().getProperty(TopiaContextFactory.CONFIG_DIALECT);
-
- return DriverType.POSTGRESQL.getDialectClass().getName().equals(dialect);
- }
}
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/JdbcConfiguration.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/JdbcConfiguration.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/JdbcConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,12 +23,25 @@
package fr.ifremer.echobase.persistence;
import fr.ifremer.echobase.entities.DriverType;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaContextFactory;
import java.io.File;
import java.io.Serializable;
+import java.util.Properties;
public class JdbcConfiguration implements Serializable {
+ public static JdbcConfiguration newConfig(TopiaContext context) {
+ Properties config = context.getConfig();
+ JdbcConfiguration result = new JdbcConfiguration();
+ result.setDriverType(DriverType.valueOfDriverName(config.getProperty(TopiaContextFactory.CONFIG_DRIVER)));
+ result.setUrl(config.getProperty(TopiaContextFactory.CONFIG_URL));
+ result.setLogin(config.getProperty(TopiaContextFactory.CONFIG_USER));
+ result.setPassword(config.getProperty(TopiaContextFactory.CONFIG_PASS));
+ return result;
+ }
+
public static JdbcConfiguration newConfig(DriverType driverType,
String url,
String login,
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/DbChangedEvent.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/DbChangedEvent.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/DbChangedEvent.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,24 @@
+package fr.ifremer.echobase.persistence.event;
+
+import java.util.EventObject;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class DbChangedEvent extends EventObject {
+
+ private static final long serialVersionUID = 1L;
+
+ public DbChangedEvent(String jdbcUrl) {
+ super(jdbcUrl);
+ }
+
+
+ @Override
+ public String getSource() {
+ return (String) super.getSource();
+ }
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/DbChangedEvent.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/VoyageChangedEvent.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/VoyageChangedEvent.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/VoyageChangedEvent.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,35 @@
+package fr.ifremer.echobase.persistence.event;
+
+import java.util.EventObject;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class VoyageChangedEvent extends EventObject {
+
+ private static final long serialVersionUID = 1L;
+
+ protected String voyageId;
+
+ /**
+ * Constructs a prototypical Event.
+ *
+ * @param voyageId id of the voyage changed .
+ */
+ public VoyageChangedEvent(String jdbcUrl, String voyageId) {
+ super(jdbcUrl);
+ this.voyageId = voyageId;
+ }
+
+ public String getVoyageId() {
+ return voyageId;
+ }
+
+ @Override
+ public String getSource() {
+ return (String) super.getSource();
+ }
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/VoyageChangedEvent.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/WorkingDbChangeListener.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/WorkingDbChangeListener.java (rev 0)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/WorkingDbChangeListener.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,26 @@
+package fr.ifremer.echobase.persistence.event;
+
+import java.util.EventListener;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public interface WorkingDbChangeListener extends EventListener {
+
+ /**
+ * When a db changed (import db)
+ *
+ * @param event event
+ */
+ void onDbChanged(DbChangedEvent event);
+
+ /**
+ * When a voyage changed (by import / remove import).
+ *
+ * @param event event
+ */
+ void onVoyageChanged(VoyageChangedEvent event);
+}
Property changes on: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/event/WorkingDbChangeListener.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
* #L%
*/
-import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.topia.TopiaContext;
@@ -59,26 +59,40 @@
// remove result category NotNull Constrainst (http://forge.codelutin.com/issues/3029)
removeResultCategoryNotNullConstrainst(queries);
+ // migrate import type id (http://forge.codelutin.com/issues/3028)
+ migrateImportTypeId(queries);
+
// compute all spatial data (http://forge.codelutin.com/issues/3037)
updatePostgis(tx);
}
+ protected void migrateImportTypeId(List<String> queries) {
+ queries.add("UPDATE ImportLog SET importType = importType + 2 WHERE importType BETWEEN 2 AND 9;");
+ }
+
protected void removeResultCategoryNotNullConstrainst(List<String> queries) {
queries.add("ALTER TABLE Result ALTER COLUMN category DROP NOT NULL;");
}
protected void updatePostgis(TopiaContext tx) {
- boolean updatePostgis = EchobaseTopiaContexts.canUpdatePostgis(tx);
+ TopiaEchoBasePersistenceContext persistenceContext =
+ new TopiaEchoBasePersistenceContext(tx);
+ boolean spatialAware =
+ persistenceContext.isSpatialAware();
- if (updatePostgis) {
- try {
- // compute all spatial data
- ((TopiaSqlSupport) tx).executeSQL("SELECT echobase_compute_all_spatial_data();");
- } catch (Exception e) {
- if (log.isErrorEnabled()) {
- log.error("Could not update spatial datas", e);
+ try {
+ if (spatialAware) {
+ try {
+ // compute all spatial data
+ ((TopiaSqlSupport) tx).executeSQL("SELECT echobase_compute_all_spatial_data();");
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("Could not update spatial datas", e);
+ }
}
}
+ } finally {
+ persistenceContext.rollbackTransaction();
}
}
}
\ No newline at end of file
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,209 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import org.nuiton.util.StringUtil;
-
-import java.io.IOException;
-import java.io.Serializable;
-
-/**
- * Abstract long action configuration.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public abstract class AbstractEchobaseActionConfiguration implements Serializable, ProgressModel {
-
- private static final long serialVersionUID = 1L;
-
- private final ProgressModel progressModel;
-
- private Exception error;
-
- private String resultMessage;
-
- protected AbstractEchobaseActionConfiguration() {
- progressModel = new DefaultProgressModel();
- }
-
- protected AbstractEchobaseActionConfiguration(ProgressModel progressModel) {
- this.progressModel = progressModel;
- }
-
- @Override
- public final long getNbSteps() {
- return progressModel.getNbSteps();
- }
-
- @Override
- public final float getProgress() {
- return progressModel.getProgress();
- }
-
- @Override
- public final void setProgress(float progress) {
- progressModel.setProgress(progress);
- }
-
- @Override
- public final void incrementsProgress() {
- progressModel.incrementsProgress();
- }
-
- @Override
- public final void setNbSteps(long nbSteps) {
- progressModel.setNbSteps(nbSteps);
- }
-
- @Override
- public final long getStartTime() {
- return progressModel.getStartTime();
- }
-
- @Override
- public final void setStartTime(long startTime) {
- progressModel.setStartTime(startTime);
- }
-
- @Override
- public final long getEndTime() {
- return progressModel.getEndTime();
- }
-
- @Override
- public final void setEndTime(long endTime) {
- progressModel.setEndTime(endTime);
- }
-
- public Exception getError() {
- return error;
- }
-
- public void setError(Exception error) {
- this.error = error;
- }
-
- public boolean hasError() {
- return error != null;
- }
-
- public String getResultMessage() {
- return resultMessage;
- }
-
- public void setResultMessage(String resultMessage) {
- this.resultMessage = resultMessage;
- }
-
- @Override
- public String getActionTime() {
- return progressModel.getActionTime();
- }
-
- public void beginAction() {
- setStartTime(System.nanoTime());
- }
-
- public void endAction() {
- setEndTime(System.nanoTime());
- }
-
- public void destroy() throws IOException {
- }
-
- /**
- * Default progression model implementation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
- public static class DefaultProgressModel implements ProgressModel {
-
- private static final long serialVersionUID = 1L;
-
- private long nbSteps;
-
- private float stepIncrement;
-
- private float progression;
-
- private long startTime;
-
- private long endTime;
-
- @Override
- public long getNbSteps() {
- return nbSteps;
- }
-
- @Override
- public float getProgress() {
- return progression;
- }
-
- @Override
- public void setProgress(float progress) {
- this.progression = progress;
- }
-
- @Override
- public long getStartTime() {
- return startTime;
- }
-
- @Override
- public void setStartTime(long startTime) {
- this.startTime = startTime;
- }
-
- @Override
- public long getEndTime() {
- return endTime;
- }
-
- @Override
- public void setEndTime(long endTime) {
- this.endTime = endTime;
- }
-
- @Override
- public final void incrementsProgress() {
- setProgress(progression + stepIncrement);
- }
-
- @Override
- public final void setNbSteps(long nbSteps) {
-
- this.nbSteps = nbSteps;
- this.stepIncrement = 100f / nbSteps;
- }
-
- @Override
- public String getActionTime() {
- long sTime = getStartTime();
- long eTime = getEndTime();
- return StringUtil.convertTime(eTime - sTime);
- }
- }
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,173 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import fr.ifremer.echobase.EchoBaseConfiguration;
-import fr.ifremer.echobase.EchoBaseTechnicalException;
-import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
-import org.apache.commons.lang3.time.DateUtils;
-import org.nuiton.topia.TopiaContext;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Date;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * Instances of this class will be given to service factory.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public class DefaultEchoBaseServiceContext implements EchoBaseServiceContext {
-
- protected TopiaContext internalTransaction;
-
- protected TopiaContext transaction;
-
- protected ServiceFactory serviceFactory;
-
- protected EchoBaseConfiguration configuration;
-
- protected Locale locale;
-
- protected EchoBaseDbMeta dbMeta;
-
- public static EchoBaseServiceContext newContext(
- Locale locale,
- TopiaContext internalTransaction,
- TopiaContext transaction,
- EchoBaseConfiguration configuration,
- EchoBaseDbMeta dbMeta) {
- return new DefaultEchoBaseServiceContext(locale,
- internalTransaction,
- transaction,
- configuration,
- dbMeta
- );
- }
-
- protected DefaultEchoBaseServiceContext(Locale locale,
- TopiaContext internalTransaction,
- TopiaContext transaction,
- EchoBaseConfiguration configuration,
- EchoBaseDbMeta dbMeta) {
- this.locale = locale;
- this.internalTransaction = internalTransaction;
- this.transaction = transaction;
- this.configuration = configuration;
- this.dbMeta = dbMeta;
- this.serviceFactory = new ServiceFactory();
- }
-
- @Override
- public TopiaContext getInternalTransaction() {
- return internalTransaction;
- }
-
- @Override
- public void setInternalTransaction(TopiaContext internalTransaction) {
- this.internalTransaction = internalTransaction;
- }
-
- @Override
- public TopiaContext getTransaction() {
- Preconditions.checkNotNull(transaction);
- return transaction;
- }
-
- @Override
- public void setTransaction(TopiaContext transaction) {
- this.transaction = transaction;
- }
-
- @Override
- public Locale getLocale() {
- return locale;
- }
-
- @Override
- public Date newDate() {
- Date result = new Date();
- DateUtils.setMilliseconds(result, 0);
- return result;
- }
-
- @Override
- public EchoBaseConfiguration getConfiguration() {
- return configuration;
- }
-
- @Override
- public EchoBaseDbMeta getDbMeta() {
- return dbMeta;
- }
-
- @Override
- public final <E extends EchoBaseService> E getService(Class<E> serviceClass) {
- return serviceFactory.getService(serviceClass, this);
- }
-
- public static class ServiceFactory {
-
- protected Map<Class<?>, EchoBaseService> services;
-
- public final <E extends EchoBaseService> E getService(Class<E> serviceClass,
- EchoBaseServiceContext serviceContext) {
- if (services == null) {
- services = Maps.newHashMap();
- }
- E service = (E) services.get(serviceClass);
- if (service == null) {
- service = newService(serviceClass, serviceContext);
- services.put(serviceClass, service);
- }
- return service;
- }
-
- public <E extends EchoBaseService> E newService(Class<E> clazz,
- EchoBaseServiceContext serviceContext) {
- // instantiate service using empty constructor
- E service;
- try {
- service = clazz.getConstructor().newInstance();
- } catch (InstantiationException e) {
- throw new EchoBaseTechnicalException(e);
- } catch (IllegalAccessException e) {
- throw new EchoBaseTechnicalException(e);
- } catch (InvocationTargetException e) {
- throw new EchoBaseTechnicalException(e);
- } catch (NoSuchMethodException e) {
- throw new EchoBaseTechnicalException(e);
- }
-
- service.setServiceContext(serviceContext);
-
- return service;
- }
-
- }
-
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,38 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-package fr.ifremer.echobase.services;
-
-/**
- * Contract to place on each EchoBase service to push the {@code serviceContext}
- * inside the service.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @see EchoBaseServiceContext
- * @since 0.1
- */
-public interface EchoBaseService {
-
- void setServiceContext(EchoBaseServiceContext serviceContext);
-
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,87 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-package fr.ifremer.echobase.services;
-
-import fr.ifremer.echobase.EchoBaseConfiguration;
-import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
-import org.nuiton.topia.TopiaContext;
-
-import java.util.Date;
-import java.util.Locale;
-
-/**
- * This contract represents objects you must provide when asking for a service.
- * Objects provided may be injected in services returned by
- * {@link ServiceFactoryAware#getService(Class)}
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public interface EchoBaseServiceContext extends ServiceFactoryAware {
-
- /**
- * Get the internal db current transaction.
- * <p/>
- * Internal db is the db with everything but not any echobase data
- * (security, db connexion, sql queries ?).
- *
- * @return current internal db transaction
- */
- TopiaContext getInternalTransaction();
-
- /**
- * Set the internal db current transaction.
- *
- * @param transaction internal db transaction to set
- */
- void setInternalTransaction(TopiaContext transaction);
-
- /**
- * Get the working db transaction.
- * <p/>
- * Working db contains echobase data, but nothing about technical
- * stuff (security, connexon,...).
- * <p/>
- * This transaction can be {@code null} if no working db is used.
- *
- * @return the current working db transaction (or {@code null} if not setted)
- */
- TopiaContext getTransaction();
-
- /**
- * Set the working db transaction.
- *
- * @param transaction working db transaction to set
- */
- void setTransaction(TopiaContext transaction);
-
- Locale getLocale();
-
- EchoBaseConfiguration getConfiguration();
-
- EchoBaseDbMeta getDbMeta();
-
- Date newDate();
-
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,273 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import com.google.common.base.Preconditions;
-import fr.ifremer.echobase.EchoBaseConfiguration;
-import fr.ifremer.echobase.EchoBaseTechnicalException;
-import fr.ifremer.echobase.entities.EchoBaseDAOHelper;
-import fr.ifremer.echobase.entities.EchoBaseInternalDAOHelper;
-import fr.ifremer.echobase.entities.EchobaseInternalEntity;
-import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
-import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaSqlSupport;
-import org.nuiton.topia.TopiaTransaction;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.TopiaEntity;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * @author sletellier <letellier(a)codelutin.com>
- * @since 0.1
- */
-public class EchoBaseServiceSupport implements EchoBaseService {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(EchoBaseServiceSupport.class);
-
- protected EchoBaseServiceContext serviceContext;
-
- @Override
- public void setServiceContext(EchoBaseServiceContext serviceContext) {
- this.serviceContext = serviceContext;
- }
-
- public final <E extends TopiaEntity> List<E> getEntities(Class<E> entityType) {
- Preconditions.checkNotNull(entityType);
- try {
- List<E> result = getDAO(entityType).findAll();
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not obtain data for type " + entityType, eee);
- }
- }
-
- public final <E extends TopiaEntity> long countEntities(Class<E> entityType) {
- Preconditions.checkNotNull(entityType);
- try {
- long result = getDAO(entityType).count();
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not count data for type " + entityType, eee);
- }
- }
-
- public final <E extends TopiaEntity> E getEntityById(Class<E> entityType, String id) {
- Preconditions.checkNotNull(entityType);
- Preconditions.checkArgument(StringUtils.isNotEmpty(id));
- try {
- E result = getDAO(entityType).findByTopiaId(id);
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not obtain data of id [" + id + "] for type " +
- entityType, eee);
- }
- }
-
- public final <E extends TopiaEntity> E getEntityByProperty(Class<E> entityType,
- String propertyId,
- Object propertyValue) {
- Preconditions.checkNotNull(entityType);
- Preconditions.checkArgument(StringUtils.isNotEmpty(propertyId));
- try {
- E result = getDAO(entityType).findByProperty(propertyId, propertyValue);
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not obtain data of property [" + propertyId + "] for type " +
- entityType, eee);
- }
- }
-
- public TopiaContext getInternalTransaction() {
- return serviceContext.getInternalTransaction();
- }
-
- public final EchoBaseConfiguration getConfiguration() {
- return serviceContext.getConfiguration();
- }
-
- protected final TopiaContext getTransaction() {
- return serviceContext.getTransaction();
- }
-
- protected final Locale getLocale() {
- return serviceContext.getLocale();
- }
-
- protected final EchoBaseDbMeta getDbMeta() {
- return serviceContext.getDbMeta();
- }
-
- protected final Date newDate() {
- return serviceContext.newDate();
- }
-
- protected char getCsvSeparator() {
- return getConfiguration().getCsvSeparator();
- }
-
- public final <E extends EchoBaseService> E getService(Class<E> serviceClass) {
- E result = serviceContext.getService(serviceClass);
- return result;
- }
-
-// protected final <E extends TopiaEntity> TopiaDAO<E> getDAO(EchoBaseEntityEnum entityEnum) {
-// TopiaDAO<E> dao = getDAO((Class<E>) entityEnum.getContract());
-// return dao;
-// }
-
- protected final <E extends TopiaEntity> TopiaDAO<E> getDAO(Class<E> entityType) {
- try {
- TopiaContext tx = getTransaction(entityType);
- TopiaDAO<E> dao;
- if (EchobaseInternalEntity.class.isAssignableFrom(entityType)) {
- dao = EchoBaseInternalDAOHelper.<E, TopiaDAO<E>>getDAO(tx, entityType);
- } else {
- dao = EchoBaseDAOHelper.<E, TopiaDAO<E>>getDAO(tx, entityType);
- }
-
- return dao;
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not obtain dao for type " + entityType, e);
- }
- }
-
- protected <E extends TopiaEntity> E create(TopiaDAO<E> dao,
- Object... properties) {
- try {
- E result = dao.create(properties);
- return result;
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not create entity", e);
- }
- }
-
- protected final <E extends TopiaEntity> void delete(TopiaDAO<E> dao, E entity) {
-
- try {
- dao.delete(entity);
- } catch (TopiaException e) {
-
- throw new EchoBaseTechnicalException("Could not delete entity " + entity, e);
- }
- }
-
- protected <E extends TopiaEntity> E findByProperties(TopiaDAO<E> dao,
- String propertyName,
- Object value,
- Object... others) {
- try {
- E result = dao.findByProperties(propertyName, value, others);
- return result;
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not obtain query db", e);
- }
- }
-
- protected final <E extends TopiaEntity, D extends TopiaDAO<E>> D getDAO(Class<E> entityType, Class<D> daoType) {
- TopiaDAO<E> dao = getDAO(entityType);
- Preconditions.checkState(daoType.isAssignableFrom(dao.getClass()));
- return (D) dao;
- }
-
- public final void commitTransaction(String errorMessage) {
- try {
- ((TopiaTransaction) getTransaction()).commitTransaction();
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(errorMessage, eee);
- }
- }
-
- public final void commitInternalTransaction(String errorMessage) {
- try {
- ((TopiaTransaction) getInternalTransaction()).commitTransaction();
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(errorMessage, eee);
- }
- }
-
- protected final void flushTransaction(String errorMessage) {
- try {
- getTransaction().getHibernateSession().flush();
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException(errorMessage, e);
- }
- }
-
- protected final void clearCache() {
- try {
- getTransaction().getHibernateSession().clear();
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not clear hibernate cache", e);
- }
- }
-
- protected <E extends TopiaEntity> TopiaContext getTransaction(Class<E> entitytype) {
- TopiaContext result;
- if (EchobaseInternalEntity.class.isAssignableFrom(entitytype)) {
- result = getInternalTransaction();
- } else {
- result = getTransaction();
- }
- return result;
- }
-
- /**
- * To update the {@code echobase_cell_spatial} table from the filled
- * table {@code echobase_cell_sptaial_temp}.
- *
- * @since 2.2
- */
- public void updatePostgisTable() {
-
- if (EchobaseTopiaContexts.canUpdatePostgis(getTransaction())) {
-
- // try the update only for postgresql
- try {
- if (log.isInfoEnabled()) {
- log.info("Will try to compute spatial data from temp table...");
- }
- ((TopiaSqlSupport) getTransaction()).executeSQL("SELECT echobase_fill_cell_spatial_table();");
- commitTransaction("Could not compute spatial data");
- } catch (Exception e) {
- if (log.isErrorEnabled()) {
- log.error("Could not compute spatial data", e);
- }
- }
- }
- }
-
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ProgressModel.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ProgressModel.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ProgressModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,46 +0,0 @@
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import org.nuiton.topia.persistence.csv.CsvProgressModel;
-
-import java.io.Serializable;
-
-/**
- * Contract for a progression model while long service actions.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
-public interface ProgressModel extends CsvProgressModel, Serializable {
-
- long getStartTime();
-
- void setStartTime(long startTime);
-
- long getEndTime();
-
- void setEndTime(long endTime);
-
- String getActionTime();
-}
Deleted: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ServiceFactoryAware.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ServiceFactoryAware.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ServiceFactoryAware.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,36 +0,0 @@
-package fr.ifremer.echobase.services;
-
-/*
- * #%L
- * EchoBase :: Domain
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-/**
- * Contract to provide some services.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.1
- */
-public interface ServiceFactoryAware {
-
- <S extends EchoBaseService> S getService(Class<S> serviceClass);
-
-}
Modified: trunk/echobase-domain/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider
===================================================================
--- trunk/echobase-domain/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-domain/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider 2013-08-15 10:53:16 UTC (rev 842)
@@ -1 +1 @@
-fr.ifremer.echobase.EchoBaseApplicationConfigProvider
\ No newline at end of file
+fr.ifremer.echobase.config.EchoBaseApplicationConfigProvider
\ No newline at end of file
Modified: trunk/echobase-domain/src/main/xmi/echobase.zargo
===================================================================
(Binary files differ)
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/AbstractEchobaseActionConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,209 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services;
+
+import org.nuiton.util.StringUtil;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+/**
+ * Abstract long action configuration.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public abstract class AbstractEchobaseActionConfiguration implements Serializable, ProgressModel {
+
+ private static final long serialVersionUID = 1L;
+
+ private final ProgressModel progressModel;
+
+ private Exception error;
+
+ private String resultMessage;
+
+ protected AbstractEchobaseActionConfiguration() {
+ progressModel = new DefaultProgressModel();
+ }
+
+ protected AbstractEchobaseActionConfiguration(ProgressModel progressModel) {
+ this.progressModel = progressModel;
+ }
+
+ @Override
+ public final long getNbSteps() {
+ return progressModel.getNbSteps();
+ }
+
+ @Override
+ public final float getProgress() {
+ return progressModel.getProgress();
+ }
+
+ @Override
+ public final void setProgress(float progress) {
+ progressModel.setProgress(progress);
+ }
+
+ @Override
+ public final void incrementsProgress() {
+ progressModel.incrementsProgress();
+ }
+
+ @Override
+ public final void setNbSteps(long nbSteps) {
+ progressModel.setNbSteps(nbSteps);
+ }
+
+ @Override
+ public final long getStartTime() {
+ return progressModel.getStartTime();
+ }
+
+ @Override
+ public final void setStartTime(long startTime) {
+ progressModel.setStartTime(startTime);
+ }
+
+ @Override
+ public final long getEndTime() {
+ return progressModel.getEndTime();
+ }
+
+ @Override
+ public final void setEndTime(long endTime) {
+ progressModel.setEndTime(endTime);
+ }
+
+ public Exception getError() {
+ return error;
+ }
+
+ public void setError(Exception error) {
+ this.error = error;
+ }
+
+ public boolean hasError() {
+ return error != null;
+ }
+
+ public String getResultMessage() {
+ return resultMessage;
+ }
+
+ public void setResultMessage(String resultMessage) {
+ this.resultMessage = resultMessage;
+ }
+
+ @Override
+ public String getActionTime() {
+ return progressModel.getActionTime();
+ }
+
+ public void beginAction() {
+ setStartTime(System.nanoTime());
+ }
+
+ public void endAction() {
+ setEndTime(System.nanoTime());
+ }
+
+ public void destroy() throws IOException {
+ }
+
+ /**
+ * Default progression model implementation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+ public static class DefaultProgressModel implements ProgressModel {
+
+ private static final long serialVersionUID = 1L;
+
+ private long nbSteps;
+
+ private float stepIncrement;
+
+ private float progression;
+
+ private long startTime;
+
+ private long endTime;
+
+ @Override
+ public long getNbSteps() {
+ return nbSteps;
+ }
+
+ @Override
+ public float getProgress() {
+ return progression;
+ }
+
+ @Override
+ public void setProgress(float progress) {
+ this.progression = progress;
+ }
+
+ @Override
+ public long getStartTime() {
+ return startTime;
+ }
+
+ @Override
+ public void setStartTime(long startTime) {
+ this.startTime = startTime;
+ }
+
+ @Override
+ public long getEndTime() {
+ return endTime;
+ }
+
+ @Override
+ public void setEndTime(long endTime) {
+ this.endTime = endTime;
+ }
+
+ @Override
+ public final void incrementsProgress() {
+ setProgress(progression + stepIncrement);
+ }
+
+ @Override
+ public final void setNbSteps(long nbSteps) {
+
+ this.nbSteps = nbSteps;
+ this.stepIncrement = 100f / nbSteps;
+ }
+
+ @Override
+ public String getActionTime() {
+ long sTime = getStartTime();
+ long eTime = getEndTime();
+ return StringUtil.convertTime(eTime - sTime);
+ }
+ }
+}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DbEditorService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DbEditorService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DbEditorService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,787 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import fr.ifremer.echobase.EchoBaseTechnicalException;
-import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
-import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.entities.EntityModificationLog;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.csv.EntityCsvModel;
-import org.nuiton.topia.persistence.metadata.ColumnMeta;
-import org.nuiton.topia.persistence.metadata.DbMeta;
-import org.nuiton.topia.persistence.metadata.TableMeta;
-import org.nuiton.topia.persistence.pager.FilterRule;
-import org.nuiton.topia.persistence.pager.FilterRuleGroupOperator;
-import org.nuiton.topia.persistence.pager.FilterRuleOperator;
-import org.nuiton.topia.persistence.pager.TopiaPagerBean;
-import org.nuiton.util.PagerBeanUtil;
-import org.nuiton.util.beans.BeanMonitor;
-import org.nuiton.util.beans.PropertyDiff;
-import org.nuiton.csv.ExportModel;
-import org.nuiton.csv.ExportableColumn;
-import org.nuiton.csv.ImportExportModel;
-import org.nuiton.csv.ImportableColumn;
-import org.nuiton.decorator.Decorator;
-import org.nuiton.decorator.JXPathDecorator;
-
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import static org.nuiton.i18n.I18n.l_;
-
-/**
- * Service to edit the database.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public class DbEditorService extends EchoBaseServiceSupport {
-
- /** Logger. */
- private static final Log log = LogFactory.getLog(DbEditorService.class);
-
- protected DecoratorService getDecoratorService() {
- return getService(DecoratorService.class);
- }
-
- public <E extends TopiaEntity> List<E> getForeignData(Class<E> entityType) {
- Preconditions.checkNotNull(entityType);
- try {
- TopiaDAO<E> dao = getDAO(entityType);
-
- List<E> result = dao.findAll();
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException("Could not obtain data", eee);
- }
- }
-
- public TableMeta<EchoBaseEntityEnum> getTableMeta(EchoBaseEntityEnum tableName) {
- DbMeta<EchoBaseEntityEnum> dbMeta = getDbMeta();
- TableMeta<EchoBaseEntityEnum> result = dbMeta.getTable(tableName);
- return result;
- }
-
- public Map<?, ?>[] getData(EchoBaseEntityEnum type, TopiaPagerBean pager) {
-
- TableMeta<EchoBaseEntityEnum> meta = getTableMeta(type);
-
- List<TopiaEntity> entities = getEntities(meta, pager);
-
- Map<?, ?>[] rows = new Map[entities.size()];
-
- ExportModel<TopiaEntity> model = buildForLoad(meta, "id", true);
-
- int i = 0;
- for (Object o : entities) {
- TopiaEntity entity = (TopiaEntity) o;
- Map<String, Object> row = loadRow(entity, model);
- rows[i++] = row;
- }
- return rows;
- }
-
- public <E extends TopiaEntity> List<E> getEntities(TableMeta<EchoBaseEntityEnum> tableMeta,
- TopiaPagerBean pager) {
-
- EchoBaseEntityEnum entityEnum = tableMeta.getSource();
- try {
- TopiaDAO<E> dao = (TopiaDAO<E>) getDAO(entityEnum.getContract());
-
- List<Object> paramsList = Lists.newArrayList();
-
- String hql = dao.createSimpleQuery("e");
-
- if (pager != null && pager.canFilter()) {
- String filterHql = getFilterHql(tableMeta, pager, paramsList);
- hql += " WHERE " + filterHql;
- }
-
- Object[] params = paramsList.toArray();
-
- if (log.isInfoEnabled()) {
- log.info("filterHql = " + hql + "\n" + Joiner.on('\n').join(params));
- }
-
-
- long count = dao.countByQuery("SELECT COUNT(*) " + hql, params);
-
- if (pager != null) {
-
- pager.setRecords(count);
- PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
- }
-
- List<E> result = dao.findAllByQueryAndPager(hql, pager, params);
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException("Could not obtain data", eee);
- }
- }
-
- public <E extends TopiaEntity> Iterable<E> iterateOnEntities(TableMeta<EchoBaseEntityEnum> tableMeta,
- String extraWhereQuery) {
-
- try {
- TopiaDAO<E> dao = (TopiaDAO<E>) getDAO(tableMeta.getSource().getContract());
-
- String hql = "FROM " +
- dao.getTopiaEntityEnum().getImplementationFQN() + " e";
- if (extraWhereQuery != null) {
- hql += " WHERE " + extraWhereQuery;
- }
- hql += " ORDER BY e.id";
- Iterable<E> result = dao.findAllLazyByQuery(5000, hql);
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException("Could not obtain data", eee);
- }
- }
-
- public Map<?, ?> getData(TableMeta<EchoBaseEntityEnum> tableMeta, String topiaId) {
-
- EchoBaseEntityEnum entityEnum = tableMeta.getSource();
- try {
- TopiaDAO<?> dao = getDAO(entityEnum.getContract());
- TopiaEntity entity = dao.findByTopiaId(topiaId);
- ExportModel<TopiaEntity> model = buildForLoad(tableMeta, TopiaEntity.PROPERTY_TOPIA_ID, true);
- return loadRow(entity, model);
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException("Could not obtain data", eee);
- }
- }
-
- public <E extends TopiaEntity> void decorateForeignKey(
- Map data,
- Class<E> propertyType,
- String property,
- String decoratorContext) {
-
- DecoratorService decoratorService = getService(DecoratorService.class);
-
- E mission = getEntityById(propertyType, (String) data.get(property));
- String voyageToString = decoratorService.decorate(getLocale(), mission, decoratorContext);
- data.put(property + "_lbl", voyageToString);
- }
-
- public void saveEntity(TableMeta<EchoBaseEntityEnum> meta,
- Map<String, String> properties,
- EchoBaseUser user) {
-
- // transform properties entity
- ImportExportModel<TopiaEntity> model = buildForSave(meta);
-
- TopiaEntity entity = model.newEmptyInstance();
-
- for (ImportableColumn<TopiaEntity, Object> column : model.getColumnsForImport()) {
- String propertyName = column.getHeaderName();
- String stringValue = properties.get(propertyName);
- Object o;
- try {
- o = column.parseValue(stringValue);
- } catch (Exception e) {
- throw new EchoBaseTechnicalException("Could not parse property [" + propertyName + "] with value " + stringValue, e);
- }
- try {
- column.setValue(entity, o);
- } catch (Exception e) {
- throw new EchoBaseTechnicalException(
- "Could not set property [" + propertyName + "] with value " + stringValue + " to entity " + entity, e);
- }
- }
-
- saveEntity(meta,
- "Modification utilisateur",
- entity,
- user,
- false
- );
- commitTransaction("Could not commit transaction");
- }
-
- public boolean saveEntity(TableMeta<EchoBaseEntityEnum> tableMeta,
- String messagePrefix,
- TopiaEntity entity,
- EchoBaseUser user,
- boolean createIfNotFound) {
- String[] columnNames = tableMeta.getColumnNamesAsArray();
- BeanMonitor monitor = null;
-
- String id = entity.getTopiaId();
-
- try {
- TopiaDAO<?> dao = getDAO(tableMeta.getSource().getContract());
-
- TopiaEntity entityToSave;
-
- // Find or create entity if no id
- boolean create = StringUtils.isEmpty(id);
-
- if (create) {
-
- // get naturalIds or not-null properties
- Map<String, Object> properties =
- tableMeta.prepareCreate(entity, null);
-
- entityToSave = dao.create(properties);
-
- // push back topiaId (could be used by caller)
- entity.setTopiaId(entityToSave.getTopiaId());
-
- } else {
-
- entityToSave = dao.findByTopiaId(id);
- if (entityToSave == null) {
-
- if (!createIfNotFound) {
-
- // this is an error
- throw new EchoBaseTechnicalException(
- "Could not found entity with id " + id);
- } else {
- entityToSave = dao.create(TopiaEntity.PROPERTY_TOPIA_ID, id);
- create = true;
- }
- }
- }
-
- if (user != null && !create) {
-
- // monitor the existing bean
- monitor = new BeanMonitor(columnNames);
- monitor.setBean(entityToSave);
- }
-
- tableMeta.copy(entity, entityToSave);
-
- if (user != null) {
-
- createEntityModificationLog(
- tableMeta,
- messagePrefix,
- entityToSave,
- user,
- monitor
- );
- }
- return create;
- } catch (Exception eee) {
- throw new EchoBaseTechnicalException("Could not update entity", eee);
- } finally {
- if (monitor != null) {
- monitor.setBean(null);
- }
- }
- }
-
- protected <O> Decorator<O> getDecorator(Class<O> type) {
- return getDecoratorService().getDecorator(getLocale(), type, null);
- }
-
- protected String getFilterHql(TableMeta<EchoBaseEntityEnum> tableMeta,
- TopiaPagerBean pager,
- List<Object> params) {
- Preconditions.checkNotNull(pager);
- Preconditions.checkState(pager.canFilter());
-
- String filterHql = null;
-
- Map<String, Object> filterParams = Maps.newHashMap();
-
- List<String> strFilterRules = Lists.newLinkedList();
-
- long timestamp = System.currentTimeMillis();
- int index = 0;
- for (FilterRule rule : pager.getRules()) {
- String ruleFilter;
-
- String field = rule.getField();
-
- ColumnMeta columnMeta = tableMeta.getColumns(field);
- Preconditions.checkNotNull(columnMeta,
- "no property named " + columnMeta);
-
- FilterRuleOperator op = rule.getOp();
- String data = rule.getData();
- String paramName = field + "_" + timestamp + (index++);
- String propertyName = "e." + field;
- Object realData = data;
- if (columnMeta.isFK()) {
-
- if (op == FilterRuleOperator.nu || op == FilterRuleOperator.nn) {
-
- // is null or is not null is a simple case
-
- ruleFilter = op.toHql(propertyName,
- propertyName,
- data,
- filterParams);
- } else {
- // must do a select in using the decoration pattern
- JXPathDecorator<?> decorator =
- (JXPathDecorator<?>) getDecorator(columnMeta.getType());
-
- if (decorator.getNbToken() == 1) {
-
- String fName = "f_" + timestamp + (index++);
-
- // simple case one token
- String token = fName + "." + decorator.getProperty(0);
-
- String subQuery = op.toHql(paramName,
- token,
- data,
- filterParams);
-
- ruleFilter = propertyName + " IN ( FROM " +
- columnMeta.getType().getName() + " " +
- fName + " WHERE " + subQuery + ")";
- } else {
-
- throw new UnsupportedOperationException();
- }
- }
-
- } else {
-
- if (columnMeta.isNumber()) {
-
- if (op == FilterRuleOperator.cn ||
- op == FilterRuleOperator.nc ||
- op == FilterRuleOperator.bw ||
- op == FilterRuleOperator.bn ||
- op == FilterRuleOperator.ew ||
- op == FilterRuleOperator.en) {
-
- // string operation
-
-// realData = "'" + realData + "'";
- propertyName = "str(" + propertyName + ")";
- } else {
-
- // real number operation
-
- if (columnMeta.getType() == int.class ||
- columnMeta.getType() == Integer.class) {
- realData = Integer.valueOf(data);
- } else {
-
- realData = Double.valueOf(data);
- }
- }
- } else if (columnMeta.isDate()) {
- propertyName = "str(" + propertyName + ")";
- }
- ruleFilter = op.toHql(paramName,
- propertyName,
- realData,
- filterParams);
- }
-
- strFilterRules.add("(" + ruleFilter + ")");
-
- if (CollectionUtils.isNotEmpty(strFilterRules)) {
- FilterRuleGroupOperator groupOp =
- pager.getGroupOp();
- filterHql = StringUtils.join(strFilterRules, groupOp.name());
- }
-
- for (Map.Entry<String, Object> entry : filterParams.entrySet()) {
- params.add(entry.getKey());
- params.add(entry.getValue());
- }
- }
- return filterHql;
- }
-
- protected void createEntityModificationLog(TableMeta<EchoBaseEntityEnum> tableMeta,
- String messagePrefix,
- TopiaEntity entity,
- EchoBaseUser user,
- BeanMonitor monitor) throws TopiaException {
-
- StringBuilder buffer;
-
- String topiaId = entity.getTopiaId();
-
- buffer = new StringBuilder(messagePrefix).append('\n');
- Locale l = getLocale();
- if (monitor == null) {
-
- // no monitor, means this is a creation of an object
- buffer.append(l_(l, "echobase.info.newEntityCreated", topiaId));
- } else {
-
- PropertyDiff[] propertyDiffs = monitor.getPropertyDiffs();
-
- int length = propertyDiffs.length;
-
- if (length == 0) {
-
- // no property modified, do nothing
- return;
- }
-
- if (length == 1) {
- buffer.append(l_(l, "echobase.info.onePropertyModified"));
- } else {
- buffer.append(
- l_(l, "echobase.info.somePropertiesModified", length));
- }
- for (PropertyDiff diff : propertyDiffs) {
-
- Object sourceValue = diff.getSourceValue();
- Object targetValue = diff.getTargetValue();
-
- String propertyName = diff.getSourceProperty();
-
- if (tableMeta.getColumns(propertyName).isFK()) {
-
- // replace by the decorate value
- if (sourceValue != null) {
- sourceValue = getDecoratorService().decorate(
- l, sourceValue, null);
- }
- if (targetValue != null) {
- targetValue = getDecoratorService().decorate(
- l, targetValue, null);
- }
- }
- buffer.append("\n ");
- buffer.append(
- l_(l, "echobase.info.modifiedProperty", propertyName,
- sourceValue,
- targetValue));
- }
- }
-
- getDAO(EntityModificationLog.class).create(
- EntityModificationLog.PROPERTY_ENTITY_TYPE, tableMeta.getSource().name(),
- EntityModificationLog.PROPERTY_ENTITY_ID, topiaId,
- EntityModificationLog.PROPERTY_MODIFICATION_USER, user.getEmail(),
- EntityModificationLog.PROPERTY_MODIFICATION_DATE, newDate(),
- EntityModificationLog.PROPERTY_MODIFICATION_TEXT, buffer.toString()
- );
- }
-
- protected <E extends TopiaEntity> Map<String, Object> loadRow(
- E entity,
- ExportModel<E> loadModel) {
-
- Map<String, Object> row = Maps.newLinkedHashMap();
-
- Iterable<ExportableColumn<E, Object>> columns =
- loadModel.getColumnsForExport();
-
- for (ExportableColumn<E, Object> column : columns) {
- String propertyName = column.getHeaderName();
- Object value;
- try {
- value = column.getValue(entity);
- } catch (Exception eee) {
- throw new EchoBaseTechnicalException(
- "Could not obtain property [" + propertyName +
- "] value from entity " + entity.getTopiaId(), eee);
- }
- String formatedValue;
- try {
- formatedValue = column.formatValue(value);
- } catch (Exception eee) {
- throw new EchoBaseTechnicalException(
- "Could not format property [" + propertyName +
- "] from value [" + value +
- "] from entity " + entity.getTopiaId(), eee);
- }
- row.put(propertyName, formatedValue);
-
- }
- return row;
- }
-
- protected <E extends TopiaEntity> ImportExportModel<E> buildForSave(TableMeta<EchoBaseEntityEnum> meta) {
-
- EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
- getConfiguration().getCsvSeparator(),
- meta,
- TopiaEntity.PROPERTY_TOPIA_ID
- );
-
- for (ColumnMeta columnMeta : meta) {
- String propertyName = columnMeta.getName();
- Class<?> type = columnMeta.getType();
- if (columnMeta.isFK()) {
-
- Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
- Collection<TopiaEntity> universe = getForeignData(entityType);
-
- // translate foreign key to his id
- model.addForeignKeyForImport(propertyName, entityType, universe);
-
- } else if (Date.class.equals(type)) {
- model.newMandatoryColumn(
- propertyName,
- EchoBaseCsvUtil.DATE_TIME_VALUE_PARSER);
- } else {
- model.addDefaultColumn(propertyName, type);
- }
- }
- return model;
- }
-
- protected <E extends TopiaEntity> ExportModel<E> buildForLoad(TableMeta<EchoBaseEntityEnum> meta,
- String idName,
- boolean addDecorated) {
-
- EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
- getConfiguration().getCsvSeparator(),
- meta,
- idName
- );
-
- for (ColumnMeta columnMeta : meta) {
- String propertyName = columnMeta.getName();
- Class<?> type = columnMeta.getType();
- if (columnMeta.isFK()) {
-
- Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
-
- // translate foreign key to his id
- model.addForeignKeyForExport(propertyName, entityType);
-
- if (addDecorated) {
-
- // translate foreign key to his decorated value
- Decorator<TopiaEntity> decorator = getDecorator(entityType);
- model.addDecoratedForeignKeyForExport(
- propertyName + "_lib",
- propertyName,
- decorator
- );
- }
-
- } else if ("id".equals(propertyName)) {
-
- if ("id".equals(idName)) {
-
- // there will be a conflict with this meta, rename it to ID
- model.addDefaultColumn("ID", propertyName, type);
- } else {
-
- // no id conflict
- model.addDefaultColumn(propertyName, type);
-
- }
- } else if ("importId".equals(propertyName) &&
- Collection.class.equals(type)) {
-
- // special case we do not want to deal with {@link ImportLog#importId}
- } else {
- model.addDefaultColumn(propertyName, type);
- }
- }
- return model;
- }
-
-// public <E extends TopiaEntity> List<E> getEntities(TableMeta<EchoBaseEntityEnum> tableMeta, TopiaPagerBean pager) {
-//
-// //TODO-tchemit-2012-08-19 Replace TopiaQuery with simple hql query
-// List<E> result;
-// EchoBaseEntityEnum entityEnum = tableMeta.getSource();
-// try {
-// TopiaDAO<E> dao = (TopiaDAO<E>) getDAO(entityEnum.getContract());
-//
-// // first query to count datas
-// TopiaQuery countQuery = dao.createQuery("e");
-// countQuery.addSelect("count(*)");
-// String filterHql = null;
-//
-// Map<String, Object> filterParams = Maps.newHashMap();
-//
-// if (pager != null && pager.canFilter()) {
-//
-// DecoratorService decoratorService = getDecoratorService();
-//
-// // prepare the filter hql code
-// List<FilterRule> rules = pager.getRules();
-// List<String> strFilterRules = Lists.newLinkedList();
-// long timestamp = System.currentTimeMillis();
-// int index = 0;
-// for (FilterRule rule : rules) {
-// String ruleFilter;
-//
-// String field = rule.getField();
-//
-// ColumnMeta columnMeta = tableMeta.getColumns(field);
-// Preconditions.checkNotNull(
-// columnMeta, "no property named " + columnMeta);
-//
-// FilterRuleOperator op = rule.getOp();
-// String data = rule.getData();
-// String paramName = field + "_" + timestamp + (index++);
-// String propertyName = "e." + field;
-// Object realData = data;
-// if (columnMeta.isFK()) {
-//
-// // must do a select in using the decoration pattern
-//
-// JXPathDecorator<?> decorator =
-// (JXPathDecorator<?>) decoratorService.getDecorator(getLocale(),
-// columnMeta.getType(),
-// null);
-//
-// if (decorator.getNbToken() == 1) {
-//
-// // simple case one token
-// String token = "f." + decorator.getProperty(0);
-//
-// String subQuery = op.toHql(paramName,
-// token,
-// data,
-// filterParams);
-//
-// ruleFilter = propertyName + " in ( SELECT f FROM " + columnMeta.getType().getName() + " f WHERE " + subQuery + ")";
-// } else {
-//
-// throw new UnsupportedOperationException();
-// }
-//
-//
-// } else {
-//
-// if (columnMeta.isNumber()) {
-// if (columnMeta.getType() == int.class ||
-// columnMeta.getType() == Integer.class) {
-// realData = Integer.valueOf(data);
-// } else {
-//
-// realData = Double.valueOf(data);
-// }
-// } else if (columnMeta.isDate()) {
-// propertyName = "str(" + propertyName + ")";
-// }
-// ruleFilter = op.toHql(paramName,
-// propertyName,
-// realData,
-// filterParams);
-//
-// }
-//
-// strFilterRules.add("(" + ruleFilter + ")");
-// }
-//
-// if (CollectionUtils.isNotEmpty(strFilterRules)) {
-// FilterRuleGroupOperator groupOp =
-// pager.getGroupOp();
-// filterHql = StringUtils.join(strFilterRules, groupOp.name());
-// }
-// }
-//
-// if (filterHql != null) {
-// if (log.isInfoEnabled()) {
-// log.info("filterHql = " + filterHql);
-// }
-// for (Map.Entry<String, Object> e : filterParams.entrySet()) {
-// String paramName = e.getKey();
-// Object paramValue = e.getValue();
-// if (log.isInfoEnabled()) {
-// log.info("filterParam = " +
-// paramName + "/" + paramValue);
-// }
-// countQuery.addParam(paramName, paramValue);
-// }
-// countQuery.addWhere(filterHql);
-//
-// String fullQuery = countQuery.fullQuery();
-// if (log.isInfoEnabled()) {
-// log.info("fullquery = " + fullQuery);
-// }
-// }
-//
-// int count = dao.countByQuery(countQuery);
-//
-// TopiaQuery query = dao.createQuery("e");
-//
-// if (pager != null) {
-//
-// pager.setRecords(count);
-// PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
-//
-// long from = pager.getRecordStartIndex();
-// long to = pager.getRecordEndIndex();
-//
-// if (log.isDebugEnabled()) {
-// log.debug("Count = " + count);
-// log.debug("page = " + pager.getPageIndex());
-// log.debug("pageSize = " + pager.getPageSize());
-// log.debug("from = " + from);
-// log.debug("to = " + to);
-// log.debug("pageCount= " + pager.getPagesNumber());
-// }
-//
-// if (filterHql != null) {
-// for (Map.Entry<String, Object> entry : filterParams.entrySet()) {
-// String paramName = entry.getKey();
-// Object paramValue = entry.getValue();
-// query.addParam(paramName, paramValue);
-// }
-// query.addWhere(filterHql);
-// }
-//
-// String sidx = pager.getSortColumn();
-// boolean ascendantOrder = pager.isSortAscendant();
-//
-// if (StringUtils.isNotEmpty(sidx)) {
-// if (ascendantOrder) {
-// query.addOrder(sidx);
-// } else {
-// query.addOrderDesc(sidx);
-// }
-// }
-//
-// query.setLimit((int) from, (int) to - 1);
-// }
-//
-// dao.findAllByQueryAndPager("hql", pager, filterParams.toString());
-// result = dao.findAllByQuery(query);
-// return result;
-// } catch (TopiaException eee) {
-// throw new EchoBaseTechnicalException("Could not obtain data", eee);
-// }
-// }
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DecoratorService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DecoratorService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DecoratorService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,372 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.entities.ImportLog;
-import fr.ifremer.echobase.entities.WorkingDbConfiguration;
-import fr.ifremer.echobase.entities.data.Category;
-import fr.ifremer.echobase.entities.data.Cell;
-import fr.ifremer.echobase.entities.data.Data;
-import fr.ifremer.echobase.entities.data.DataAcquisition;
-import fr.ifremer.echobase.entities.data.DataProcessing;
-import fr.ifremer.echobase.entities.data.Echotype;
-import fr.ifremer.echobase.entities.data.GearMetadataValue;
-import fr.ifremer.echobase.entities.data.LengthAgeKey;
-import fr.ifremer.echobase.entities.data.LengthWeightKey;
-import fr.ifremer.echobase.entities.data.Operation;
-import fr.ifremer.echobase.entities.data.OperationMetadataValue;
-import fr.ifremer.echobase.entities.data.Result;
-import fr.ifremer.echobase.entities.data.Sample;
-import fr.ifremer.echobase.entities.data.SampleData;
-import fr.ifremer.echobase.entities.data.Transect;
-import fr.ifremer.echobase.entities.data.Transit;
-import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.entities.references.AcousticInstrument;
-import fr.ifremer.echobase.entities.references.AgeCategory;
-import fr.ifremer.echobase.entities.references.AreaOfOperation;
-import fr.ifremer.echobase.entities.references.Calibration;
-import fr.ifremer.echobase.entities.references.CategoryMeaning;
-import fr.ifremer.echobase.entities.references.CategoryRef;
-import fr.ifremer.echobase.entities.references.CategoryType;
-import fr.ifremer.echobase.entities.references.CellMethod;
-import fr.ifremer.echobase.entities.references.CellType;
-import fr.ifremer.echobase.entities.references.DataMetadata;
-import fr.ifremer.echobase.entities.references.DataProtocol;
-import fr.ifremer.echobase.entities.references.DataQuality;
-import fr.ifremer.echobase.entities.references.DataType;
-import fr.ifremer.echobase.entities.references.DepthStratum;
-import fr.ifremer.echobase.entities.references.EchotypeCategory;
-import fr.ifremer.echobase.entities.references.Gear;
-import fr.ifremer.echobase.entities.references.GearCharacteristic;
-import fr.ifremer.echobase.entities.references.GearCharacteristicValue;
-import fr.ifremer.echobase.entities.references.GearMetadata;
-import fr.ifremer.echobase.entities.references.Impacte;
-import fr.ifremer.echobase.entities.references.MeasureType;
-import fr.ifremer.echobase.entities.references.MeasurementMetadata;
-import fr.ifremer.echobase.entities.references.Mission;
-import fr.ifremer.echobase.entities.references.OperationEvent;
-import fr.ifremer.echobase.entities.references.OperationMetadata;
-import fr.ifremer.echobase.entities.references.ReferenceDatum;
-import fr.ifremer.echobase.entities.references.ReferenceDatumType;
-import fr.ifremer.echobase.entities.references.ReferencingMethod;
-import fr.ifremer.echobase.entities.references.SampleDataType;
-import fr.ifremer.echobase.entities.references.SampleType;
-import fr.ifremer.echobase.entities.references.SexCategory;
-import fr.ifremer.echobase.entities.references.SizeCategory;
-import fr.ifremer.echobase.entities.references.Species;
-import fr.ifremer.echobase.entities.references.SpeciesCategory;
-import fr.ifremer.echobase.entities.references.Strata;
-import fr.ifremer.echobase.entities.references.TSParameters;
-import fr.ifremer.echobase.entities.references.Vessel;
-import fr.ifremer.echobase.entities.references.VesselType;
-import org.apache.commons.collections.CollectionUtils;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.decorator.Decorator;
-import org.nuiton.decorator.DecoratorMulti18nProvider;
-import org.nuiton.decorator.DecoratorUtil;
-import org.nuiton.decorator.JXPathDecorator;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * Service to decorate entities.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public class DecoratorService extends EchoBaseServiceSupport {
-
- public static final String DATE_ONLY = "dateOnly";
-
- protected final DecoratorMulti18nProvider decoratorProvider;
-
- public DecoratorService() {
- decoratorProvider = new EchoBaseDecoratorProvider();
- }
-
- public <O> Decorator<O> getDecorator(Locale locale,
- Class<O> type,
- String context) {
- Preconditions.checkNotNull(type, "Decorator type can not be null!");
- Decorator<O> decorator = decoratorProvider.getDecoratorByType(locale, type, context);
- Preconditions.checkNotNull(
- decorator,
- "Could not find decorator for type " + type +
- " and context " + context
- );
- return decorator;
- }
-
- public String decorate(Locale locale, Object o, String context) {
- Decorator<?> decorator = getDecorator(locale, o.getClass(), context);
- String result = decorator.toString(o);
- return result;
- }
-
- public <O> List<O> sortToList(Locale locale, Collection<O> beans, String context) {
- Preconditions.checkNotNull(beans);
- List<O> list = Lists.newArrayList(beans);
- getDecoratorAndSort(locale, context, list);
- return list;
- }
-
- public <E extends TopiaEntity> Map<String, String> sortAndDecorate(Locale locale,
- Collection<E> beans,
- String context) {
- Preconditions.checkNotNull(beans);
- List<E> list = Lists.newArrayList(beans);
-
- Decorator<E> decorator = getDecoratorAndSort(locale, context, list);
- Map<String, String> result = Maps.newLinkedHashMap();
- for (E bean : list) {
- result.put(bean.getTopiaId(), decorator.toString(bean));
- }
- return result;
- }
-
- protected <O> Decorator<O> getDecoratorAndSort(Locale locale,
- String context,
- List<O> list) {
- Decorator<O> decorator = null;
- if (CollectionUtils.isNotEmpty(list)) {
- O object = list.get(0);
- Preconditions.checkNotNull(object);
- decorator = decoratorProvider.getDecorator(locale, object, context);
- Preconditions.checkNotNull(
- decorator,
- "Could not find decorator for type " + object.getClass() +
- " and context " + context
- );
- DecoratorUtil.sort((JXPathDecorator<O>) decorator, list, 0);
- }
- return decorator;
- }
-
- static class EchoBaseDecoratorProvider extends DecoratorMulti18nProvider {
-
- @Override
- protected void loadDecorators(Locale locale) {
-
- // EchoBaseUser decorator
- registerJXPathDecorator(locale, EchoBaseUser.class, "${email}$s");
-
- // ExportQuery decorator
- registerJXPathDecorator(locale, ExportQuery.class, "${name}$s - ${description}$s");
-
- // ImportLog decorator
- registerJXPathDecorator(locale, ImportLog.class, "${importType}$s - ${importDate}$s - ${importText}$s");
-
- // ImportLog decorator
- registerJXPathDecorator(locale, ImportLog.class, DATE_ONLY, "${importDate}$s");
-
-
- // WorkingDbConfiguration decorator
- registerJXPathDecorator(locale, WorkingDbConfiguration.class, "${url}$s - (${description}$s)");
-
- // AcousticInstrument decorator
- registerJXPathDecorator(locale, AcousticInstrument.class, "${id}$s");
-
- // AgeCategory decorator
- registerJXPathDecorator(locale, AgeCategory.class, "${name}$s");
-
- // AreaOfOperation decorator
- registerJXPathDecorator(locale, AreaOfOperation.class, "${name}$s");
-
- // Calibration decorator
- registerJXPathDecorator(locale, Calibration.class, "${date}$s - acquisition ${aquisitionMethod}$s");
-
- // Category decorator
- registerJXPathDecorator(locale, Category.class, "${echotypeLabel}$s ${speciesLabel}$s ${processedAgeLabel}$s ${processedLengthLabel}$s");
-
- // CategoryMeaning decorator
- registerJXPathDecorator(locale, CategoryMeaning.class, "${name}$s");
-
- // CategoryRef decorator
- registerJXPathDecorator(locale, CategoryRef.class, "${genusSpecies}$s");
-
- // CategoryType decorator
- registerJXPathDecorator(locale, CategoryType.class, "${name}$s");
-
- // CellMethod decorator
- registerJXPathDecorator(locale, CellMethod.class, "${name}$s");
-
- // CellType decorator
- registerJXPathDecorator(locale, CellType.class, "${name}$s");
-
- // DataMetadata decorator
- registerJXPathDecorator(locale, DataMetadata.class, "${name}$s - ${standardName}$s");
- //registerJXPathDecorator(locale, DataMetadata.class, "${name}$s");
-
- // DataProtocol decorator
- registerJXPathDecorator(locale, DataProtocol.class, "${description}$s [ ${validSince}$td/%2$tm/%2$tY - ${invalidSince}$td/%3$tm/%3$tY ]");
-
- // DataQuality decorator
- //registerJXPathDecorator(locale, DataQuality.class, "${qualityDataFlagValues}$s - ${flagMeanings}$s");
- registerJXPathDecorator(locale, DataQuality.class, "${flagMeanings}$s");
-
- // DataType decorator
- registerJXPathDecorator(locale, DataType.class, "${name}$s");
-
- // DepthStratum decorator
- //registerJXPathDecorator(locale, DepthStratum.class, "${id}$s - ${meaning}$s");
- registerJXPathDecorator(locale, DepthStratum.class, "${meaning}$s");
-
- // Echotype decorator
- //registerJXPathDecorator(locale, Echotype.class, "${id}$s - ${name}$s");
- registerJXPathDecorator(locale, Echotype.class, "${name}$s");
-
- // EchotypeCategory decorator
- registerJXPathDecorator(locale, EchotypeCategory.class, "${name}$s");
-
- // Gear decorator
- //registerJXPathDecorator(locale, Gear.class, "${name}$s [ ${validSince}$td/%2$tm/%2$tY - ${invalidSince}$td/%3$tm/%3$tY ]");
- registerJXPathDecorator(locale, Gear.class, "${name}$s");
-
- // GearCaracteristic decorator
- registerJXPathDecorator(locale, GearCharacteristic.class, "${name}$s");
-
- // GearMetadata decorator
- //registerJXPathDecorator(locale, GearMetadata.class, "${name}$s (${operationEvent/name}$s)");
- registerJXPathDecorator(locale, GearMetadata.class, "${name}$s");
-
- // GearCharacteristicValue decorator
- registerJXPathDecorator(locale, GearCharacteristicValue.class, "${dataValue}$s");
-
- // GearMetadataValue decorator
- registerJXPathDecorator(locale, GearMetadataValue.class, "${dataValue}$s");
-
- // Impacte decorator
- //registerJXPathDecorator(locale, Impacte.class, "${measurementUnit}$s - ${species/genusSpecies}");
- registerJXPathDecorator(locale, Impacte.class, "${measurementUnit}$s");
-
- // LengthAgeKey decorator
- registerJXPathDecorator(locale, LengthAgeKey.class, "Age ${age}$s - Length ${length}");
-
- // MeasurementMetadata decorator
- registerJXPathDecorator(locale, MeasurementMetadata.class, "${name}$s");
-
- // MeasureType decorator
- registerJXPathDecorator(locale, MeasureType.class, "${name}$s");
-
- // Mission decorator
- registerJXPathDecorator(locale, Mission.class, "${name}$s");
-
- // OperationEvent decorator
- registerJXPathDecorator(locale, OperationEvent.class, "${name}$s");
-
- // OperationMetadata decorator
- registerJXPathDecorator(locale, OperationMetadata.class, "${name}$s");
-
- // ReferenceDatum decorator
- registerJXPathDecorator(locale, ReferenceDatum.class, "${id}$s");
-
- // ReferenceDatumType decorator
- registerJXPathDecorator(locale, ReferenceDatumType.class, "${name}$s");
-
- // ReferencingMethod decorator
- registerJXPathDecorator(locale, ReferencingMethod.class, "${name}$s");
-
- // SampleDataType decorator
- registerJXPathDecorator(locale, SampleDataType.class, "${name}$s");
-
- // SampleType decorator
- //registerJXPathDecorator(locale, SampleType.class, "${name}$s - level ${level}$s");
- registerJXPathDecorator(locale, SampleType.class, "${name}$s");
-
- // SexCategory decorator
- registerJXPathDecorator(locale, SexCategory.class, "${name}$s");
-
- // SizeCategory decorator
- registerJXPathDecorator(locale, SizeCategory.class, "${name}$s");
-
- // Species decorator
- //registerJXPathDecorator(locale, Species.class, "${genusSpecies}$s (${baracoudaCode}$s)");
- registerJXPathDecorator(locale, Species.class, "${genusSpecies}$s");
-
- // SpeciesCategory decorator
- registerJXPathDecorator(locale, SpeciesCategory.class, "${species/genusSpecies}$s ${sizeCategoryLabel}$s ${ageCategoryLabel}$s ${sexCategoryLabel}$s");
-
- // Strata decorator
- registerJXPathDecorator(locale, Strata.class, "Latitude <${minLatitude}$s - ${maxLatitude}$s>, Longitude <${minLongitude}$s - ${maxLongitude}$s>");
-
- //TODO
- // TSParameters decorator
- registerJXPathDecorator(locale, TSParameters.class, "${}$s");
-
- // Vessel decorator
- registerJXPathDecorator(locale, Vessel.class, "${name}$s");
-
- // VesselType decorator
- registerJXPathDecorator(locale, VesselType.class, "${name}$s");
-
- // LengthWeightKey decorator
- registerJXPathDecorator(locale, LengthWeightKey.class, "Species ${species/genusSpecies}$s - a=${aParameter}$s, b=${bParameter}$s");
-
- // Cell decorator
- registerJXPathDecorator(locale, Cell.class, "${name}$s");
-
- // Data decorator
- registerJXPathDecorator(locale, Data.class, "${dataValue}$s");
-
- // DataAcquisition decorator
- registerJXPathDecorator(locale, DataAcquisition.class, "${acousticInstrument/id}$s ");
-
- // DataProcessing decorator
- registerJXPathDecorator(locale, DataProcessing.class, "${id}$s");
-
- // Operation decorator
- registerJXPathDecorator(locale, Operation.class, "${startDate}$td/%1$tm/%1$tY - ${endDate}$td/%2$tm/%2$tY");
-
- // OperationMetadataValue decorator
- registerJXPathDecorator(locale, OperationMetadataValue.class, "${operationMetadata/name} - ${dataValue}$s");
-
- // Result decorator
- registerJXPathDecorator(locale, Result.class, "${resultvalue}$s");
-
- // Sample decorator
- registerJXPathDecorator(locale, Sample.class, "${resultvalue}$s");
-
- // SampleData decorator
- registerJXPathDecorator(locale, SampleData.class, "${resultvalue}$s");
-
- // Transect decorator
- registerJXPathDecorator(locale, Transect.class, "${title}$s - Vessel ${vessel/name}$s");
-
- // Transit decorator
- registerJXPathDecorator(locale, Transit.class, "${startTime}$td/%1$tm/%1$tY - ${endTime}$td/%2$tm/%2$tY");
-
- // Voyage decorator
- registerJXPathDecorator(locale, Voyage.class, "${name}$s [ ${startDate}$td/%2$tm/%2$tY - ${endDate}$td/%3$tm/%3$tY ]");
- }
- }
-
-}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DefaultEchoBaseServiceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,153 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services;
+
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.entities.spatial.SpatialDataCache;
+import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
+import org.apache.commons.lang3.time.DateUtils;
+import org.nuiton.topia.TopiaContextFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.Date;
+import java.util.Locale;
+
+/**
+ * Instances of this class will be given to service factory.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public class DefaultEchoBaseServiceContext implements EchoBaseServiceContext {
+
+ protected final Locale locale;
+
+ protected TopiaEchoBasePersistenceContext echoBasePersistenceContext;
+
+ protected TopiaEchoBaseInternalPersistenceContext echoBaseInternalPersistenceContext;
+
+ protected EchoBaseConfiguration configuration;
+
+ protected EchoBaseDbMeta dbMeta;
+
+ private SpatialDataCache spatialCache;
+
+ public static EchoBaseServiceContext newContext(
+ Locale locale,
+ EchoBaseConfiguration configuration,
+ EchoBaseDbMeta dbMeta,
+ SpatialDataCache spatialCache) {
+ return new DefaultEchoBaseServiceContext(locale,
+ configuration,
+ dbMeta,
+ spatialCache);
+ }
+
+ protected DefaultEchoBaseServiceContext(Locale locale,
+ EchoBaseConfiguration configuration,
+ EchoBaseDbMeta dbMeta,
+ SpatialDataCache spatialCache) {
+ this.locale = locale;
+ this.configuration = configuration;
+ this.dbMeta = dbMeta;
+ this.spatialCache = spatialCache;
+ }
+
+ @Override
+ public SpatialDataCache getSpatialDataCache() {
+ return spatialCache;
+ }
+
+ @Override
+ public TopiaEchoBasePersistenceContext getEchoBasePersistenceContext() {
+ return echoBasePersistenceContext;
+ }
+
+ @Override
+ public void setEchoBasePersistenceContext(TopiaEchoBasePersistenceContext echoBasePersistenceContext) {
+ this.echoBasePersistenceContext = echoBasePersistenceContext;
+ }
+
+ @Override
+ public TopiaEchoBaseInternalPersistenceContext getEchoBaseInternalPersistenceContext() {
+ return echoBaseInternalPersistenceContext;
+ }
+
+ @Override
+ public void setEchoBaseInternalPersistenceContext(TopiaEchoBaseInternalPersistenceContext echoBaseInternalPersistenceContext) {
+ this.echoBaseInternalPersistenceContext = echoBaseInternalPersistenceContext;
+ }
+
+ @Override
+ public Locale getLocale() {
+ return locale;
+ }
+
+ @Override
+ public Date newDate() {
+ Date result = new Date();
+ DateUtils.setMilliseconds(result, 0);
+ return result;
+ }
+
+ @Override
+ public EchoBaseConfiguration getConfiguration() {
+ return configuration;
+ }
+
+ @Override
+ public EchoBaseDbMeta getDbMeta() {
+ return dbMeta;
+ }
+
+ @Override
+ public <S extends EchoBaseService> S newService(Class<S> serviceClass) {
+ // instantiate service using empty constructor
+ S service;
+ try {
+ service = serviceClass.getConstructor().newInstance();
+ } catch (InstantiationException e) {
+ throw new EchoBaseTechnicalException(e);
+ } catch (IllegalAccessException e) {
+ throw new EchoBaseTechnicalException(e);
+ } catch (InvocationTargetException e) {
+ throw new EchoBaseTechnicalException(e);
+ } catch (NoSuchMethodException e) {
+ throw new EchoBaseTechnicalException(e);
+ }
+
+ service.setServiceContext(this);
+
+ return service;
+ }
+
+ @Override
+ public String getWorkgingDbUrl() {
+ String result = getEchoBasePersistenceContext().getConfig().getProperty(TopiaContextFactory.CONFIG_URL);
+ return result;
+ }
+
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,38 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+package fr.ifremer.echobase.services;
+
+/**
+ * Contract to place on each EchoBase service to push the {@code serviceContext}
+ * inside the service.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @see EchoBaseServiceContext
+ * @since 0.1
+ */
+public interface EchoBaseService {
+
+ void setServiceContext(EchoBaseServiceContext serviceContext);
+
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,66 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+package fr.ifremer.echobase.services;
+
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.entities.spatial.SpatialDataCache;
+import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
+
+import java.util.Date;
+import java.util.Locale;
+
+/**
+ * This contract represents objects you must provide when asking for a service.
+ * Objects provided may be injected in services returned by
+ * {@link #newService(Class)}
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public interface EchoBaseServiceContext {
+
+ SpatialDataCache getSpatialDataCache();
+
+ TopiaEchoBasePersistenceContext getEchoBasePersistenceContext();
+
+ void setEchoBasePersistenceContext(TopiaEchoBasePersistenceContext internalPersistenceContext);
+
+ TopiaEchoBaseInternalPersistenceContext getEchoBaseInternalPersistenceContext();
+
+ void setEchoBaseInternalPersistenceContext(TopiaEchoBaseInternalPersistenceContext internalPersistenceContext);
+
+ Locale getLocale();
+
+ EchoBaseConfiguration getConfiguration();
+
+ EchoBaseDbMeta getDbMeta();
+
+ Date newDate();
+
+ String getWorkgingDbUrl();
+
+ <S extends EchoBaseService> S newService(Class<S> serviceClass);
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/EchoBaseServiceSupport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,147 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services;
+
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.entities.spatial.SpatialDataCache;
+import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbService;
+import fr.ifremer.echobase.services.service.exportdb.ExportService;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.importdb.ImportDbService;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.DbEditorService;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import fr.ifremer.echobase.services.service.InternalDbPersistenceService;
+import fr.ifremer.echobase.services.service.UserService;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+
+import java.util.Date;
+import java.util.Locale;
+
+/**
+ * @author sletellier <letellier(a)codelutin.com>
+ * @since 0.1
+ */
+public class EchoBaseServiceSupport implements EchoBaseService {
+
+ protected EchoBaseServiceContext serviceContext;
+
+ @Override
+ public void setServiceContext(EchoBaseServiceContext serviceContext) {
+ this.serviceContext = serviceContext;
+ }
+
+ protected <E extends EchoBaseService> E newService(Class<E> serviceClass) {
+ return serviceContext.newService(serviceClass);
+ }
+
+ public TopiaEchoBasePersistenceContext getEchoBasePersistenceContext() {
+ return serviceContext.getEchoBasePersistenceContext();
+ }
+
+ public TopiaEchoBaseInternalPersistenceContext getEchoBaseInternalPersistenceContext() {
+ return serviceContext.getEchoBaseInternalPersistenceContext();
+ }
+
+ public final EchoBaseConfiguration getConfiguration() {
+ return serviceContext.getConfiguration();
+ }
+
+ protected final String getWorkgingDbUrl() {
+ return serviceContext.getWorkgingDbUrl();
+ }
+
+ protected final SpatialDataCache getSpatialDataCache() {
+ return serviceContext.getSpatialDataCache();
+ }
+
+ protected final Locale getLocale() {
+ return serviceContext.getLocale();
+ }
+
+ protected final Date newDate() {
+ return serviceContext.newDate();
+ }
+
+ protected final EchoBaseDbMeta getDbMeta() {
+ return serviceContext.getDbMeta();
+ }
+
+ protected char getCsvSeparator() {
+ return getConfiguration().getCsvSeparator();
+ }
+
+ public DbEditorService getDbEditorService() {
+ return newService(DbEditorService.class);
+ }
+
+ public DecoratorService getDecoratorService() {
+ return newService(DecoratorService.class);
+ }
+
+ public InternalDbPersistenceService getInternalDbPersistenceService() {
+ return newService(InternalDbPersistenceService.class);
+ }
+
+ public WorkingDbPersistenceService getWorkingDbPersistenceService() {
+ return newService(WorkingDbPersistenceService.class);
+ }
+
+ public UserService getUserService() {
+ return newService(UserService.class);
+ }
+
+ public SpatialService getSpatialService() {
+ return newService(SpatialService.class);
+ }
+
+ public ExportService getExportService() {
+ return newService(ExportService.class);
+ }
+
+ public ExportDbService getExportDbService() {
+ return newService(ExportDbService.class);
+ }
+
+ public ImportDbService getImportDbService() {
+ return newService(ImportDbService.class);
+ }
+
+ public RemoveDataService getRemoveDataService() {
+ return newService(RemoveDataService.class);
+ }
+
+ public ExportQueryService getExportQueryService() {
+ return newService(ExportQueryService.class);
+ }
+
+// public final <E extends EchoBaseService> E getService(Class<E> serviceClass) {
+// E result = serviceContext.newService(serviceClass);
+// return result;
+// }
+
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/ProgressModel.java (from rev 839, trunk/echobase-domain/src/main/java/fr/ifremer/echobase/services/ProgressModel.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/ProgressModel.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/ProgressModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,46 @@
+/*
+ * #%L
+ * EchoBase :: Domain
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services;
+
+import org.nuiton.topia.persistence.csv.CsvProgressModel;
+
+import java.io.Serializable;
+
+/**
+ * Contract for a progression model while long service actions.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public interface ProgressModel extends CsvProgressModel, Serializable {
+
+ long getStartTime();
+
+ void setStartTime(long startTime);
+
+ long getEndTime();
+
+ void setEndTime(long endTime);
+
+ String getActionTime();
+}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/UserService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/UserService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/UserService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,166 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import com.google.common.base.Preconditions;
-import fr.ifremer.echobase.EchoBaseTechnicalException;
-import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.entities.EchoBaseUserDAO;
-import org.apache.commons.lang3.StringUtils;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.pager.TopiaPagerBean;
-import org.nuiton.util.StringUtil;
-
-import java.util.List;
-
-/**
- * @author sletellier <letellier(a)codelutin.com>
- * @since 0.1
- */
-public class UserService extends EchoBaseServiceSupport {
-
- public static final String DEFAULT_ADMIN_EMAIL = "admin";
-
- public static final String DEFAULT_ADMIN_PASSWORD = "admin";
-
- public static final String DEFAULT_USER_EMAIL = "user";
-
- public static final String DEFAULT_USER_PASSWORD = "user";
-
- public List<EchoBaseUser> getUsers() {
- return getUsers(null);
- }
-
- public List<EchoBaseUser> getUsers(TopiaPagerBean pager) {
- try {
- EchoBaseUserDAO dao = getDAO();
- List<EchoBaseUser> users = dao.findAll(pager);
- return users;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public EchoBaseUser getUserByEmail(String email) {
- Preconditions.checkNotNull(email);
- try {
- EchoBaseUserDAO dao = getDAO();
- EchoBaseUser user = dao.findByEmail(email);
- return user;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public EchoBaseUser getUserById(String userId) {
- Preconditions.checkNotNull(userId);
- try {
- EchoBaseUser user = getDAO().findByTopiaId(userId);
- EchoBaseUser result = newUser();
- result.setEmail(user.getEmail());
- result.setPassword(user.getPassword());
- result.setAdmin(user.isAdmin());
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public void createOrUpdate(EchoBaseUser user) {
- try {
- EchoBaseUser userToCreateOrUpdate;
-
- // No id, creating new one entity
- String id = user.getTopiaId();
- String password = user.getPassword();
- if (StringUtils.isEmpty(id)) {
- userToCreateOrUpdate = getDAO().create(
- EchoBaseUser.PROPERTY_EMAIL, user.getEmail(),
- EchoBaseUser.PROPERTY_PASSWORD, encodePassword(password)
- );
- } else {
- userToCreateOrUpdate = getEntityById(EchoBaseUser.class, id);
-
- userToCreateOrUpdate.setEmail(user.getEmail());
- if (StringUtils.isNotEmpty(password)) {
- userToCreateOrUpdate.setPassword(encodePassword(password));
- }
- }
- userToCreateOrUpdate.setAdmin(user.isAdmin());
- commitInternalTransaction("Could not create or update user");
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public void delete(EchoBaseUser user) {
- try {
- EchoBaseUser userToDelete = getEntityById(EchoBaseUser.class,
- user.getTopiaId());
- getDAO().delete(userToDelete);
- commitInternalTransaction("Could not delete user");
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public boolean checkPassword(EchoBaseUser user,
- String password) throws Exception {
- String s = encodePassword(password);
- return s.equals(user.getPassword());
- }
-
- public void createDefaultUsers() {
- EchoBaseUser user;
-
- user = newUser();
- user.setEmail(DEFAULT_ADMIN_EMAIL);
- user.setPassword(DEFAULT_ADMIN_PASSWORD);
- user.setAdmin(true);
- createOrUpdate(user);
-
- user = newUser();
- user.setEmail(DEFAULT_USER_EMAIL);
- user.setPassword(DEFAULT_USER_PASSWORD);
- user.setAdmin(false);
- createOrUpdate(user);
- }
-
- public static String encodePassword(String password) {
- String encodedPassword = StringUtil.encodeMD5(password);
- return encodedPassword;
- }
-
- public EchoBaseUser newUser() {
- try {
- return getDAO().newInstance();
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException(e);
- }
- }
-
- protected EchoBaseUserDAO getDAO() {
- return getDAO(EchoBaseUser.class, EchoBaseUserDAO.class);
- }
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationConfiguration.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,105 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.embeddedapplication;
-
-import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
-import org.apache.commons.io.FileUtils;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-
-/**
- * Configuration of a embedded application creation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class EmbeddedApplicationConfiguration extends AbstractEchobaseActionConfiguration {
-
- private static final long serialVersionUID = 1L;
-
- /** File name of the embedded application archive (without the zip extension). */
- private String fileName;
-
- /** Working directory where to generate the archive of embedded application. */
- private File workingDirectory;
-
- /** Embedded application archive file. */
- private File embeddedApplicationFile;
-
- /** Location of the war file to push in embedded application. */
- private File warLocation;
-
- /** Ids of voyages to push in embedded application (with all their datas). */
- private String[] voyageIds;
-
- public String getFileName() {
- return fileName;
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public File getWorkingDirectory() {
- return workingDirectory;
- }
-
- public void setWorkingDirectory(File workingDirectory) {
- this.workingDirectory = workingDirectory;
- }
-
- public File getEmbeddedApplicationFile() {
- return embeddedApplicationFile;
- }
-
- public void setEmbeddedApplicationFile(File embeddedApplicationFile) {
- this.embeddedApplicationFile = embeddedApplicationFile;
- }
-
- public String[] getVoyageIds() {
- return voyageIds;
- }
-
- // Attention on ne peut pas utiliser un ... car sinon ça plante dans l'ui
- public void setVoyageIds(String[] voyageIds) {
- this.voyageIds = Arrays.copyOf(voyageIds, voyageIds.length);
- }
-
- public File getWarLocation() {
- return warLocation;
- }
-
- public void setWarLocation(File warLocation) {
- this.warLocation = warLocation;
- }
-
- @Override
- public void destroy() throws IOException {
- if (workingDirectory != null) {
- FileUtils.deleteDirectory(workingDirectory);
- }
- }
-}
\ No newline at end of file
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,415 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.embeddedapplication;
-
-import com.google.common.base.Charsets;
-import com.google.common.base.Preconditions;
-import fr.ifremer.echobase.EchoBaseTechnicalException;
-import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.entities.WorkingDbConfiguration;
-import fr.ifremer.echobase.io.EchoBaseIOUtil;
-import fr.ifremer.echobase.persistence.EchoBaseEntityHelper;
-import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
-import fr.ifremer.echobase.persistence.JdbcConfiguration;
-import fr.ifremer.echobase.services.DefaultEchoBaseServiceContext;
-import fr.ifremer.echobase.services.EchoBaseServiceContext;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.UserService;
-import fr.ifremer.echobase.services.exportdb.ExportDbConfiguration;
-import fr.ifremer.echobase.services.exportdb.ExportDbMode;
-import fr.ifremer.echobase.services.exportdb.ExportDbService;
-import fr.ifremer.echobase.services.exportquery.ExportQueryInvalidNameException;
-import fr.ifremer.echobase.services.exportquery.ExportQueryNameAlreadyExistException;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
-import fr.ifremer.echobase.services.importdata.ImportException;
-import fr.ifremer.echobase.services.importdb.ImportDbConfiguration;
-import fr.ifremer.echobase.services.importdb.ImportDbMode;
-import fr.ifremer.echobase.services.importdb.ImportDbService;
-import fr.ifremer.echobase.services.workingDb.WorkingDbConfigurationAlreadyExistException;
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.util.FileUtil;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.List;
-
-/**
- * To create embedded application.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @author sletellier <letellier(a)codelutin.com>
- * @since 0.1
- */
-public class EmbeddedApplicationService extends EchoBaseServiceSupport {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(EmbeddedApplicationService.class);
-
- public static final String EMBEDDED_PATH = "/embedded/";
-
- public File createEmbeddedApplication(EmbeddedApplicationConfiguration model) {
-
- int nbSteps = computeNbSteps(model);
- model.setNbSteps(nbSteps);
-
- String fileName = model.getFileName();
-
- File tempDirectory = model.getWorkingDirectory();
- tempDirectory.deleteOnExit();
-
- File zipFile = new File(tempDirectory, fileName + ".zip");
- model.setEmbeddedApplicationFile(zipFile);
-
- File dir = new File(tempDirectory, fileName);
-
- if (log.isInfoEnabled()) {
- log.info("Creates embedded application to file [" + zipFile + "]");
- }
-
- // export db to csv
- File exportZipFile = exportDb(model, tempDirectory);
-
- // create static archive structure
- createStaticArchiveStructure(model, dir);
-
- model.incrementsProgress();
-
- // create new service context
- EchoBaseServiceContext newServiceContext =
- DefaultEchoBaseServiceContext.newContext(
- getLocale(),
- null,
- null,
- getConfiguration(),
- getDbMeta());
-
- EchoBaseUser admin;
- try {
- admin = importInternalDb(model, dir, newServiceContext);
- } catch (Exception e) {
- throw new EchoBaseTechnicalException(
- "Could not create internal db", e);
- }
-
- // create working db in /db
- try {
- importWorkingDb(model, dir, exportZipFile, newServiceContext, admin);
-
- } catch (Exception eee) {
-
- throw new EchoBaseTechnicalException(
- "Could not create h2 working database at " + dir, eee);
- }
-
- try {
- EchoBaseIOUtil.compressZipFile(zipFile, dir);
- } catch (IOException eee) {
- throw new EchoBaseTechnicalException(
- "Could not create zip file at " + zipFile, eee);
- }
-
- return zipFile;
- }
-
- protected EchoBaseUser importInternalDb(EmbeddedApplicationConfiguration model,
- File dir,
- EchoBaseServiceContext newServiceContext) throws TopiaException, ExportQueryNameAlreadyExistException, WorkingDbConfigurationAlreadyExistException, ExportQueryInvalidNameException {
-
- File internalDir = new File(dir, "internaldb");
-
- TopiaContext internalRootContext =
- EchobaseTopiaContexts.newInternalDb(internalDir);
-
- newServiceContext.setInternalTransaction(
- internalRootContext.beginTransaction());
-
-
- try {
- // get user service from h2 db
- UserService userService = newServiceContext.getService(UserService.class);
-
- // create admin user
- userService.createDefaultUsers();
-
- // get admin from h2 db
- EchoBaseUser admin = userService.getUserByEmail(
- UserService.DEFAULT_ADMIN_EMAIL);
-
- model.incrementsProgress();
-
- // get all export queries from application
- List<ExportQuery> queries = getEntities(ExportQuery.class);
-
- // replicate queries
- getInternalTransaction().replicateEntities(
- newServiceContext.getInternalTransaction(), queries);
-
- // create export sql service from h2 db
- ExportQueryService exportQueryService =
- newServiceContext.getService(ExportQueryService.class);
-
- // get all queries from h2 db
- queries = exportQueryService.getEntities(ExportQuery.class);
-
- // attach them to default created admin user in the db
- for (ExportQuery query : queries) {
- exportQueryService.createOrUpdate(query, admin);
- }
-
- model.incrementsProgress();
-
- // get all working db configuration from application
-
- List<WorkingDbConfiguration> confs =
- getEntities(WorkingDbConfiguration.class);
-
- // replicate configs
- getInternalTransaction().replicateEntities(
- newServiceContext.getInternalTransaction(), confs);
-
- model.incrementsProgress();
-
- return admin;
-
- } finally {
- newServiceContext.setInternalTransaction(null);
- EchoBaseEntityHelper.releaseRootContext(internalRootContext);
- }
- }
-
- protected void importWorkingDb(EmbeddedApplicationConfiguration model,
- File dir,
- File exportZipFile,
- EchoBaseServiceContext newServiceContext,
- EchoBaseUser admin) throws IOException, ImportException, TopiaException {
-
- JdbcConfiguration dbConf = JdbcConfiguration.newEmbeddedConfig(dir);
- TopiaContext rootContext = EchobaseTopiaContexts.newWorkingDb(
- dbConf);
- try {
-
- // inject a new transaction in service context
- newServiceContext.setTransaction(rootContext.beginTransaction());
-
- model.incrementsProgress();
-
- // prepare import configuration
- ImportDbConfiguration importConfiguration =
- new ImportDbConfiguration(model, getLocale());
- importConfiguration.getInput().setFile(exportZipFile);
- File importTempDir = new File(model.getWorkingDirectory(), "importDb");
- importConfiguration.setWorkingDirectory(importTempDir);
- importConfiguration.setImportDbMode(ImportDbMode.FREE);
- importConfiguration.setComputeSteps(false);
- importConfiguration.setCommitAfterEachFile(true);
-
- // do import to embedded working db
- newServiceContext.getService(ImportDbService.class).doImport(
- importConfiguration, admin);
-
- } finally {
- // remove current transaction
- newServiceContext.setTransaction(null);
-
- // release any connexion to the working db
- EchoBaseEntityHelper.releaseRootContext(rootContext);
- }
- }
-
- protected void closeContext(TopiaContext tx, String message) {
- try {
- tx.closeContext();
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(message, eee);
- }
- }
-
- protected TopiaContext beginTransaction(TopiaContext tx, String message) {
- try {
- return tx.beginTransaction();
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(message, eee);
- }
- }
-
- protected void rollbackTransaction(TopiaContext tx, String message) {
- try {
- if (tx != null) {
- tx.rollbackTransaction();
- }
- } catch (TopiaException eee) {
- if (log.isErrorEnabled()) {
- log.error(message, eee);
- }
- }
- }
-
- protected int computeNbSteps(EmbeddedApplicationConfiguration model) {
- int nbSteps = 5;
-
- // export db steps
-
- nbSteps += getDbMeta().getReferenceEntriesSize();
- if (model.getVoyageIds() != null) {
- nbSteps += model.getVoyageIds().length;
- }
-
- // import db stesp
- nbSteps += getDbMeta().getEntriesSize();
- return nbSteps;
- }
-
- protected void createStaticArchiveStructure(EmbeddedApplicationConfiguration model, File dir) {
-
- try {
-
- // create /
- FileUtil.createDirectoryIfNecessary(dir);
-
- // copy embedded files to /
- copyEmbeddedTextFile("echobase.properties", dir, false);
- copyEmbeddedTextFile("startEchobase.bat", dir, true);
- copyEmbeddedTextFile("startEchobase.sh", dir, true);
- copyEmbeddedTextFile("README.txt", dir, false);
-
- // copy war to /
- File warLocation = model.getWarLocation();
- FileUtils.copyFile(warLocation,
- new File(dir, warLocation.getName()));
- } catch (Exception eee) {
- throw new EchoBaseTechnicalException(
- "Could not create embedded zip structure at " + dir, eee);
- }
- }
-
- protected File exportDb(EmbeddedApplicationConfiguration model, File dir) {
-
- try {
- // create export zip file
- ExportDbConfiguration exportconfiguration =
- new ExportDbConfiguration(model);
- exportconfiguration.setFileName("echobase-export");
- File exportTempDir = new File(dir, "exportDb");
- exportconfiguration.setWorkingDirectory(exportTempDir);
- exportconfiguration.setVoyageIds(model.getVoyageIds());
- exportconfiguration.setComputeSteps(false);
- exportconfiguration.setExportDbMode(ExportDbMode.REFERENTIAL_AND_DATA);
-
- TopiaContext transaction = serviceContext.getTransaction();
-
- TopiaContext newTx = beginTransaction(
- transaction,
- "Could not begin transaction on main db");
- try {
- serviceContext.setTransaction(newTx);
- ExportDbService exportDbService = getService(ExportDbService.class);
- exportDbService.doExport(exportconfiguration);
- } catch (IOException eee) {
- rollbackTransaction(
- newTx,
- "Could not rollback transaction on db");
- throw eee;
- } catch (RuntimeException eee) {
- rollbackTransaction(
- newTx,
- "Could not rollback transaction on db");
- throw eee;
- } finally {
- serviceContext.setTransaction(transaction);
- closeContext(newTx, "Could not close transaction on main db");
- }
- File exportZipFile = exportconfiguration.getExportFile();
- if (log.isInfoEnabled()) {
- log.info("Export zip file = " + exportZipFile);
- }
- return exportZipFile;
- } catch (IOException eee) {
- throw new EchoBaseTechnicalException(
- "Could not export db to zip", eee);
- }
- }
-
- public void copyEmbeddedTextFile(String resourceName,
- File targetDirectory,
- boolean executable) throws IOException {
- String resourcePath = EMBEDDED_PATH + resourceName;
- InputStream inputStream = getClass().getResourceAsStream(resourcePath);
- Preconditions.checkNotNull(inputStream,
- "could not find resource " + resourcePath);
- try {
- File outputFile = new File(targetDirectory, resourceName);
- if (log.isInfoEnabled()) {
- log.info("Copy configuration to " + resourceName + " to " + outputFile);
- }
- OutputStreamWriter outputStream = new OutputStreamWriter(
- new FileOutputStream(outputFile), Charsets.UTF_8);
- try {
- IOUtils.copy(inputStream, outputStream);
- } finally {
- outputStream.close();
- }
- if (executable) {
- outputFile.setExecutable(true);
- }
- } finally {
- inputStream.close();
- }
- }
-
- public void copyEmbeddedBinaryFile(String resourceName,
- File targetDirectory) throws IOException {
- String resourcePath = EMBEDDED_PATH + resourceName;
- InputStream inputStream = getClass().getResourceAsStream(resourcePath);
- Preconditions.checkNotNull(inputStream,
- "could not find resource " + resourcePath);
- try {
- File outputFile = new File(targetDirectory, resourceName);
- if (log.isInfoEnabled()) {
- log.info("Copy binary file from " + resourceName + " to " +
- outputFile);
- }
- OutputStream outputStream = new FileOutputStream(outputFile);
- try {
- IOUtils.copy(inputStream, outputStream);
- outputStream.close();
- } finally {
- IOUtils.closeQuietly(outputStream);
- }
- inputStream.close();
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
- }
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbConfiguration.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,119 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportdb;
-
-import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
-import fr.ifremer.echobase.services.ProgressModel;
-import org.apache.commons.io.FileUtils;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * Configuration of a complete db export.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class ExportDbConfiguration extends AbstractEchobaseActionConfiguration {
-
- private static final long serialVersionUID = 1L;
-
- private String fileName;
-
- private File workingDirectory;
-
- private File exportFile;
-
- private ExportDbMode exportDbMode;
-
- /** Ids of voyages to push in embedded application (with all their datas). */
- private String[] voyageIds;
-
- private boolean computeSteps;
-
- public ExportDbConfiguration() {
- }
-
- public ExportDbConfiguration(ProgressModel progressModel) {
- super(progressModel);
- }
-
- public String getFileName() {
- return fileName;
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public File getWorkingDirectory() {
- return workingDirectory;
- }
-
- public void setWorkingDirectory(File workingDirectory) {
- this.workingDirectory = workingDirectory;
- }
-
- public File getExportFile() {
- return exportFile;
- }
-
- public void setExportFile(File exportFile) {
- this.exportFile = exportFile;
- }
-
- public String[] getVoyageIds() {
- return voyageIds;
- }
-
- // Attention on ne peut pas utiliser un ... car sinon ça plante dans l'ui
- public void setVoyageIds(String[] voyageIds) {
- this.voyageIds = voyageIds;
- }
-
- public ExportDbMode getExportDbMode() {
- return exportDbMode;
- }
-
- public void setExportDbMode(ExportDbMode exportDbMode) {
- this.exportDbMode = exportDbMode;
- }
-
- public boolean isComputeSteps() {
- return computeSteps;
- }
-
- public void setComputeSteps(boolean computeSteps) {
- this.computeSteps = computeSteps;
- }
-
- @Override
- public void destroy() throws IOException {
- if (workingDirectory != null) {
- FileUtils.deleteDirectory(workingDirectory);
- }
- }
-
-}
\ No newline at end of file
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbMode.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbMode.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbMode.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,71 +0,0 @@
-package fr.ifremer.echobase.services.exportdb;
-
-/*
- * #%L
- * EchoBase :: Services
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-import fr.ifremer.echobase.I18nAble;
-
-import static org.nuiton.i18n.I18n.n_;
-
-/**
- * Db export mode.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.2
- */
-public enum ExportDbMode implements I18nAble {
-
- /** Export only referential. */
- REFERENTIAL(n_("echobase.common.exportDbMode.referential"), true, false),
-
- /** Export selected data + referential. */
- REFERENTIAL_AND_DATA(n_("echobase.common.exportDbMode.referentialAndData"), true, true),
-
- /** Export all the db. */
- ALL(n_("echobase.common.exportDbMode.all"), true, true);
-
- private final String i18nKey;
-
- private final boolean exportReferential;
-
- private final boolean exportData;
-
- ExportDbMode(String i18nKey, boolean exportReferential, boolean exportData) {
- this.i18nKey = i18nKey;
- this.exportReferential = exportReferential;
- this.exportData = exportData;
- }
-
- @Override
- public String getI18nKey() {
- return i18nKey;
- }
-
- public boolean isExportReferential() {
- return exportReferential;
- }
-
- public boolean isExportData() {
- return exportData;
- }
-}
\ No newline at end of file
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,267 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportdb;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.entities.data.Cell;
-import fr.ifremer.echobase.entities.data.Result;
-import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.io.EchoBaseIOUtil;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaPersistenceHelper;
-import org.nuiton.topia.persistence.csv.out.ExportEntityVisitor;
-import org.nuiton.topia.persistence.csv.out.TopiaCsvExports;
-import org.nuiton.topia.persistence.metadata.AssociationMeta;
-import org.nuiton.topia.persistence.metadata.TableMeta;
-import org.nuiton.util.FileUtil;
-import org.nuiton.util.TimeLog;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Service to import / export a complete db.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class ExportDbService extends EchoBaseServiceSupport {
-
- /** Logger. */
- private static final Log log = LogFactory.getLog(ExportDbService.class);
-
- public static final TimeLog timeLog = new TimeLog(ExportDbService.class);
-
- public void doExport(ExportDbConfiguration model) throws IOException {
-
- String fileName = model.getFileName();
-
- File tempDirectory = model.getWorkingDirectory();
-
- File zipFile = new File(tempDirectory, fileName + ".echobase");
-
- if (log.isInfoEnabled()) {
- log.info("Will export db to " + zipFile);
- }
- model.setExportFile(zipFile);
-
- File dir = new File(tempDirectory, "echobase");
-
- FileUtil.createDirectoryIfNecessary(dir);
-
- ExportDbMode exportDbMode = model.getExportDbMode();
-
- ExportService exportService = getService(ExportService.class);
-
- boolean exportVoyagesByVisitor = exportDbMode.isExportData();
-
- if (exportVoyagesByVisitor) {
-
- long nbVoyages = exportService.countEntities(Voyage.class);
- if (exportDbMode == ExportDbMode.ALL ||
- model.getVoyageIds().length == nbVoyages) {
-
- // no need to export via visitor, can export all data tables
- exportVoyagesByVisitor = false;
- }
- }
-
- List<TableMeta<EchoBaseEntityEnum>> tablesToExport = Lists.newArrayList();
- List<AssociationMeta<EchoBaseEntityEnum>> associationsToExport = Lists.newArrayList();
-
- if (exportDbMode.isExportReferential()) {
-
- // add referential tables
- tablesToExport.addAll(getDbMeta().getReferenceTables());
- associationsToExport.addAll(getDbMeta().getReferenceAssociations());
- }
-
- if (exportDbMode.isExportData() && !exportVoyagesByVisitor) {
-
- // will export complete data tables
- tablesToExport.addAll(getDbMeta().getDataTables());
- associationsToExport.addAll(getDbMeta().getDataAssociations());
- }
-
- if (model.isComputeSteps()) {
-
- int nbSteps = tablesToExport.size() + associationsToExport.size();
-
- if (exportVoyagesByVisitor) {
- nbSteps += model.getVoyageIds().length;
- }
-
- if (log.isInfoEnabled()) {
- log.info("NB steps: " + nbSteps);
- }
- model.setNbSteps(nbSteps);
- }
-
- exportTables(model, dir, tablesToExport, exportService);
-
- exportAssociations(model, dir, associationsToExport, exportService);
-
- if (exportVoyagesByVisitor) {
-
- exportVoyages(model, dir, exportService);
- }
-
- EchoBaseIOUtil.compressZipFile(zipFile, dir);
- }
-
- private void exportTables(ExportDbConfiguration model,
- File dir,
- List<TableMeta<EchoBaseEntityEnum>> tablesToExport,
- ExportService exportService) {
- for (TableMeta<EchoBaseEntityEnum> meta : tablesToExport) {
-
- model.incrementsProgress();
-
- File entryFile = new File(dir, meta.getFilename());
- exportService.exportData(meta, entryFile);
- }
- }
-
- private void exportAssociations(ExportDbConfiguration model,
- File dir,
- List<AssociationMeta<EchoBaseEntityEnum>> associationsToExport,
- ExportService exportService) {
- for (AssociationMeta<EchoBaseEntityEnum> associationMeta : associationsToExport) {
-
- model.incrementsProgress();
-
- File entryFile = new File(dir, associationMeta.getFilename());
- exportService.exportData(associationMeta, entryFile);
- }
- }
-
- private void exportVoyages(ExportDbConfiguration model,
- File dir,
- ExportService exportService) throws IOException {
-
- Map<EchoBaseEntityEnum, TopiaCsvExports.EntityExportContext<EchoBaseEntityEnum>> contexts =
- TopiaCsvExports.createReplicateEntityVisitorContexts(
- exportService.getModelFactory(false),
- getDbMeta().getDataTables(),
- getDbMeta().getDataAssociations(),
- dir);
-
- ReplicateEntityVisitor visitor = new ReplicateEntityVisitor(
- getDbMeta().getPersistenceHelper(),
- contexts);
-
- try {
- for (String voyageId : model.getVoyageIds()) {
-
- model.incrementsProgress();
-
- Voyage voyage = getEntityById(Voyage.class, voyageId);
- visitor.export(voyage);
- }
- } finally {
-
- // close visitor to close export files
- visitor.close();
- }
- }
-
- /**
- * entity visitor to export data to csv files.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
- static class ReplicateEntityVisitor extends ExportEntityVisitor<EchoBaseEntityEnum> {
-
- protected final Set<String> categoryIds;
-
- public ReplicateEntityVisitor(TopiaPersistenceHelper<EchoBaseEntityEnum> typeProvider,
- Map<EchoBaseEntityEnum, TopiaCsvExports.EntityExportContext<EchoBaseEntityEnum>> entityExporters) {
- super(typeProvider, entityExporters);
- categoryIds = Sets.newHashSet();
- }
-
- @Override
- public void visit(TopiaEntity entity, String propertyName,
- Class<?> type, Object value) {
- if (Result.PROPERTY_CATEGORY.equals(propertyName) &&
- entity instanceof Result) {
-
- // export category
- try {
- TopiaEntity topiaEntity = (TopiaEntity) value;
- if (categoryIds.add(topiaEntity.getTopiaId())) {
- // add this new category
- topiaEntity.accept(this);
- }
-
- } catch (TopiaException e) {
- if (log.isErrorEnabled()) {
- log.error("Can not visit entity " + value, e);
- }
- }
- }
- }
-
- @Override
- protected void visitEntityCollection(TopiaEntity entity,
- String propertyName,
- Class<?> collectionType,
- Class<?> type,
- Collection<?> cValue) {
- if (Voyage.PROPERTY_POST_CELL.equals(propertyName) && entity instanceof Voyage) {
-
- // special case, we don not want to visit childs of cells
- for (Object o : cValue) {
- Cell cell = (Cell) o;
-
- cell.acceptWithNoChild(this);
- }
- } else {
- // normal entity collection visit
- super.visitEntityCollection(entity,
- propertyName,
- collectionType,
- type,
- cValue);
- }
- }
-
- @Override
- public void close() throws IOException {
- categoryIds.clear();
- super.close();
- }
- }
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,209 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportdb;
-
-import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.DbEditorService;
-import fr.ifremer.echobase.services.DecoratorService;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.csv.EntityCsvModel;
-import org.nuiton.topia.persistence.csv.out.EntityAssociationExportModel;
-import org.nuiton.topia.persistence.csv.out.ExportModelFactory;
-import org.nuiton.topia.persistence.csv.out.PrepareDataForExport;
-import org.nuiton.topia.persistence.csv.out.TopiaCsvExports;
-import org.nuiton.topia.persistence.metadata.AssociationMeta;
-import org.nuiton.topia.persistence.metadata.ColumnMeta;
-import org.nuiton.topia.persistence.metadata.TableMeta;
-import org.nuiton.csv.ExportModel;
-import org.nuiton.decorator.Decorator;
-
-import java.io.File;
-
-/**
- * To export datas from db to csv files.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class ExportService extends EchoBaseServiceSupport {
-
- /** Logger. */
- private static final Log log = LogFactory.getLog(ExportService.class);
-
- public String exportData(TableMeta<EchoBaseEntityEnum> meta, boolean asSeen) {
-
- if (log.isInfoEnabled()) {
- log.info("Export " + meta);
- }
- String result = TopiaCsvExports.exportData(meta,
- getModelFactory(asSeen),
- defaultPrepareDataForExport);
- return result;
- }
-
- public void exportData(TableMeta<EchoBaseEntityEnum> meta, File file) {
-
- if (log.isInfoEnabled()) {
- log.info("Export " + meta + " to " + file);
- }
-
- TopiaCsvExports.exportData(meta,
- defaultExportFactory,
- defaultPrepareDataForExport,
- file);
-
- clearCache();
- }
-
-
- public void exportData(AssociationMeta<EchoBaseEntityEnum> meta, File file) {
-
- if (log.isInfoEnabled()) {
- log.info("Export " + meta + " to " + file);
- }
- TopiaCsvExports.exportData(meta,
- defaultExportFactory,
- defaultPrepareDataForExport,
- file);
-
- clearCache();
- }
-
- public ExportModelFactory<EchoBaseEntityEnum> getModelFactory(boolean asSeen) {
- ExportModelFactory<EchoBaseEntityEnum> result;
- if (asSeen) {
- result = asSeenExportFactory;
- } else {
- result = defaultExportFactory;
- }
- return result;
- }
-
- private ExportModelFactory<EchoBaseEntityEnum> defaultExportFactory = new ExportModelFactory<EchoBaseEntityEnum>() {
-
- @Override
- public <E extends TopiaEntity> ExportModel<E> buildForExport(TableMeta<EchoBaseEntityEnum> meta) {
-
- // normal export add topiaId column
- EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
- getConfiguration().getCsvSeparator(),
- meta,
- TopiaEntity.PROPERTY_TOPIA_ID
- );
-
- for (ColumnMeta columnMeta : meta) {
- String propertyName = columnMeta.getName();
- Class<?> type = columnMeta.getType();
- if (columnMeta.isFK()) {
-
- Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
-
-
- // export foreign key value as his topiaId
- model.addForeignKeyForExport(propertyName, entityType);
-
- } else {
- model.addDefaultColumn(propertyName, type);
- }
- }
- return model;
- }
-
- @Override
- public <E extends TopiaEntity> ExportModel<E> buildForExport(AssociationMeta<EchoBaseEntityEnum> associationMeta) {
- ExportModel<E> model = EntityAssociationExportModel.newExportModel(
- getConfiguration().getCsvSeparator(),
- associationMeta
- );
- return model;
- }
- };
-
- private ExportModelFactory<EchoBaseEntityEnum> asSeenExportFactory = new ExportModelFactory<EchoBaseEntityEnum>() {
-
- @Override
- public <E extends TopiaEntity> ExportModel<E> buildForExport(TableMeta<EchoBaseEntityEnum> meta) {
-
-
- // no need to have topiaId as first column
- EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
- getConfiguration().getCsvSeparator(),
- meta
- );
-
-
- DecoratorService service = getService(DecoratorService.class);
-
- for (ColumnMeta columnMeta : meta) {
- String propertyName = columnMeta.getName();
- Class<?> type = columnMeta.getType();
- if (columnMeta.isFK()) {
-
- Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
-
- // export decorated foreign key value
- Decorator<TopiaEntity> decorator =
- service.getDecorator(getLocale(), entityType, null);
- model.addDecoratedForeignKeyForExport(propertyName, propertyName, decorator);
-
- } else {
- model.addDefaultColumn(propertyName, type);
- }
- }
- return model;
- }
-
- @Override
- public <E extends TopiaEntity> ExportModel<E> buildForExport(AssociationMeta<EchoBaseEntityEnum> associationMeta) {
- ExportModel<E> model = EntityAssociationExportModel.newExportModel(
- getConfiguration().getCsvSeparator(),
- associationMeta
- );
- return model;
- }
- };
-
- private PrepareDataForExport<EchoBaseEntityEnum> defaultPrepareDataForExport = new PrepareDataForExport<EchoBaseEntityEnum>() {
-
- @Override
- public <E extends TopiaEntity> Iterable<E> prepareData(TableMeta<EchoBaseEntityEnum> tableMeta) {
- DbEditorService service = getService(DbEditorService.class);
-
- Iterable<E> data = service.iterateOnEntities(tableMeta, null);
- return data;
- }
-
- @Override
- public <E extends TopiaEntity> Iterable<E> prepareData(AssociationMeta<EchoBaseEntityEnum> associationMeta) {
- DbEditorService service = getService(DbEditorService.class);
-
- TableMeta<EchoBaseEntityEnum> tableMeta = service.getTableMeta(associationMeta.getSource());
- Iterable<E> data = service.iterateOnEntities(tableMeta, "size(e." + associationMeta.getName() + ") > 0");
- return data;
- }
- };
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryCsvModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryCsvModel.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryCsvModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,49 +0,0 @@
-package fr.ifremer.echobase.services.exportquery;
-
-/*
- * #%L
- * EchoBase :: Services
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
-import org.nuiton.csv.ext.AbstractExportModel;
-
-import java.util.Map;
-
-/**
- * Csv model to export sql in {@link ExportQueryService}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class ExportQueryCsvModel extends AbstractExportModel<Map<String, Object>> {
-
- public ExportQueryCsvModel(char separator, String[] columnHeaders) {
- super(separator);
- for (String columnHeader : columnHeaders) {
- newColumnForExport(
- columnHeader,
- EchoBaseCsvUtil.TO_STRING_FORMATTER
- );
- }
- }
-
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryInvalidNameException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryInvalidNameException.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryInvalidNameException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,35 +0,0 @@
-package fr.ifremer.echobase.services.exportquery;
-
-/*
- * #%L
- * EchoBase :: Services
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-/**
- * To be thrown if a query has not a valid query name.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.4
- */
-public class ExportQueryInvalidNameException extends Exception {
-
- private static final long serialVersionUID = 1L;
-}
\ No newline at end of file
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNameAlreadyExistException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNameAlreadyExistException.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNameAlreadyExistException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,35 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportquery;
-
-/**
- * TODO
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
-public class ExportQueryNameAlreadyExistException extends Exception {
-
- private static final long serialVersionUID = 1L;
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNotFoundException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNotFoundException.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNotFoundException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,35 +0,0 @@
-package fr.ifremer.echobase.services.exportquery;
-
-/*
- * #%L
- * EchoBase :: Services
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-/**
- * When a export query is not found.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.4
- */
-public class ExportQueryNotFoundException extends Exception {
-
- private static final long serialVersionUID = 1L;
-}
\ No newline at end of file
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryService.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,243 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportquery;
-
-import com.google.common.base.Charsets;
-import fr.ifremer.echobase.EchoBaseTechnicalException;
-import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.entities.ExportQueries;
-import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.entities.ExportQueryDAO;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import org.apache.commons.lang3.StringUtils;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.pager.TopiaPagerBean;
-import org.nuiton.util.RecursiveProperties;
-import org.nuiton.csv.Export;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * Service to deal with sql export.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.1
- */
-public class ExportQueryService extends EchoBaseServiceSupport {
-
- public ExportQuery getExportQuery(String topiaId) throws ExportQueryNotFoundException {
- ExportQuery exportQuery = getEntityById(ExportQuery.class, topiaId);
-
- if (exportQuery == null) {
- throw new ExportQueryNotFoundException();
- }
- ExportQuery entityToSave = newExportQuery();
- entityToSave.setTopiaId(exportQuery.getTopiaId());
- entityToSave.setName(exportQuery.getName());
- entityToSave.setDescription(exportQuery.getDescription());
- entityToSave.setSqlQuery(exportQuery.getSqlQuery());
- entityToSave.setLastModifiedDate(exportQuery.getLastModifiedDate());
- entityToSave.setLastModifiedUser(exportQuery.getLastModifiedUser());
- return entityToSave;
- }
-
-
- public ExportQuery createOrUpdate(ExportQuery exportQuery,
- EchoBaseUser user) throws ExportQueryNameAlreadyExistException, ExportQueryInvalidNameException {
- try {
-
- ExportQueryDAO dao = getDAO();
-
- // No id, creating new one entity
- String id = exportQuery.getTopiaId();
-
- boolean mustCreate = StringUtils.isEmpty(id);
-
- String queryName = exportQuery.getName();
-
- if (!ExportQueries.isQueryNameValid(queryName)) {
-
- // can not accept a non alpha numeric name
- throw new ExportQueryInvalidNameException();
- }
-
- // check query does not already exists with this name
- if (mustCreate) {
-
- boolean queryExists = dao.isQueryExists(id, queryName);
-
- if (queryExists) {
- throw new ExportQueryNameAlreadyExistException();
- }
- }
-
- ExportQuery entityToSave;
-
- exportQuery.setLastModifiedDate(newDate());
- exportQuery.setLastModifiedUser(user.getEmail());
-
- if (mustCreate) {
- entityToSave = dao.create(exportQuery);
- } else {
- entityToSave = dao.findByTopiaId(id);
- entityToSave.setName(queryName);
- entityToSave.setDescription(exportQuery.getDescription());
- entityToSave.setSqlQuery(exportQuery.getSqlQuery());
- entityToSave.setLastModifiedDate(exportQuery.getLastModifiedDate());
- entityToSave.setLastModifiedUser(exportQuery.getLastModifiedUser());
- }
-
-// dao.update(entityToSave);
- commitInternalTransaction("Could not create export query");
- return entityToSave;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public void delete(String topiaId) {
- try {
- ExportQueryDAO dao = getDAO();
-
- ExportQuery entityToDelete = dao.findByTopiaId(topiaId);
- dao.delete(entityToDelete);
-
- commitInternalTransaction("Could not delete export query");
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(eee);
- }
- }
-
- public String getSqlQuery(String queryId) throws ExportQueryNotFoundException {
-
- ExportQuery exportQuery = getExportQuery(queryId);
-
- String result = getSafeSql(exportQuery.getSqlQuery());
- return result;
- }
-
- protected String getSafeSql(String sql) {
- RecursiveProperties sqls = new RecursiveProperties();
- List<ExportQuery> queries = getEntities(ExportQuery.class);
- for (ExportQuery query : queries) {
- sqls.put(query.getName(), query.getSqlQuery());
- }
- if (!sqls.containsKey(sql)) {
-
- sqls.put(sql, sql);
- }
-
- String result = sqls.getProperty(sql);
- return result;
- }
-
- public void testSql(String sql) throws TopiaException {
-
- String safeSql = getSafeSql(sql);
- GenericSQLQuery sqlQuery = new GenericSQLQuery(safeSql, null);
-
- sqlQuery.getColumnNames(getTransaction());
- }
-
- public Map<String, Object>[] executeExportquery(String queryId,
- TopiaPagerBean pager) throws ExportQueryNotFoundException {
-
- String sql = getSqlQuery(queryId);
-
- // get a query to count all rows for the request
- GenericSQLQuery sqlQuery = new GenericSQLQuery(sql, pager);
- try {
- List<Map<String, Object>> result =
- sqlQuery.getResult(getTransaction());
- return result.toArray(new Map[result.size()]);
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not execute sql query", eee);
- }
- }
-
- public String[] getColumnNames(String sql) {
-
- String limitSql = sql.trim();
- if (limitSql.endsWith(";")) {
- limitSql = limitSql.substring(0, limitSql.length() - 1);
- limitSql += " LIMIT 1";
- }
- try {
- // do a limit query to one result and obtain the column names
- // from the meta data of the result set
- GenericSQLQuery sqlQuery = new GenericSQLQuery(limitSql, null);
- String[] result = sqlQuery.getColumnNames(getTransaction());
- return result;
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not execute query " + limitSql + " for reason " + eee.getCause().getMessage(), eee);
- } catch (Exception eee) {
- throw new EchoBaseTechnicalException(
- "Could not execute query " + limitSql + " for reason " + eee.getMessage(), eee);
- }
- }
-
- public String createCsvFileContent(String queryId) throws ExportQueryNotFoundException {
-
- String sql = getSqlQuery(queryId);
-
- GenericSQLQuery sqlQuery = new GenericSQLQuery(sql, null);
- List<Map<String, Object>> rows;
- try {
- rows = sqlQuery.getResult(getTransaction());
- } catch (TopiaException eee) {
- throw new EchoBaseTechnicalException(
- "Could not execute sql query", eee);
- }
- char csvSeparator = getConfiguration().getCsvSeparator();
- ExportQueryCsvModel csvModel = sqlQuery.generateCsvModel(csvSeparator);
- Export<Map<String, Object>> exporter = Export.newExport(csvModel, rows);
- try {
- String content = exporter.toString(Charsets.UTF_8);
- return content;
- } catch (Exception eee) {
- throw new EchoBaseTechnicalException("Could not export sql", eee);
- }
- }
-
- public ExportQuery newExportQuery() {
- try {
- return getDAO().newInstance();
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException(e);
- }
- }
-
- public String processLibreOfficeSqlQuery(String libreOfficeQuery) {
-
- String result = libreOfficeQuery.replaceAll("\\\"", "");
- return result;
- }
-
- protected ExportQueryDAO getDAO() {
- return getDAO(ExportQuery.class, ExportQueryDAO.class);
- }
-}
Deleted: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/GenericSQLQuery.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/GenericSQLQuery.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/GenericSQLQuery.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,138 +0,0 @@
-package fr.ifremer.echobase.services.exportquery;
-
-/*
- * #%L
- * EchoBase :: Services
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaSQLQuery;
-import org.nuiton.util.PagerBean;
-import org.nuiton.util.PagerBeanUtil;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.List;
-import java.util.Map;
-
-/**
- * TODO
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.0
- */
-public class GenericSQLQuery extends TopiaSQLQuery<Map<String, Object>> {
-
- /** Logger. */
- private static final Log log = LogFactory.getLog(GenericSQLQuery.class);
-
- protected String[] columnNames;
-
- private final String sql;
-
- private final PagerBean pager;
-
- public GenericSQLQuery(String sql, PagerBean pager) {
- this.sql = sql;
- this.pager = pager;
- }
-
- public String[] getColumnNames() {
- return columnNames;
- }
-
- public ExportQueryCsvModel generateCsvModel(char charSeparator) {
- ExportQueryCsvModel model = new ExportQueryCsvModel(
- charSeparator,
- columnNames
- );
- return model;
- }
-
- public List<Map<String, Object>> getResult(TopiaContext tx) throws TopiaException {
- List<Map<String, Object>> rows =
- findMultipleResult(tx);
- return rows;
- }
-
- public void testQuery(TopiaContext tx) throws TopiaException {
- findSingleResult(tx);
- }
-
- public String[] getColumnNames(TopiaContext tx) throws TopiaException {
- findSingleResult(tx);
- return columnNames;
- }
-
- @Override
- protected PreparedStatement prepareQuery(Connection connection) throws SQLException {
- return connection.prepareStatement(
- sql,
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY
- );
- }
-
- @Override
- protected void afterExecuteQuery(ResultSet set) throws SQLException {
- super.afterExecuteQuery(set);
-
- // obtain columnNames
- columnNames = getColumnNames(set);
-
- if (pager != null) {
-
- // must count rows
- long nbRows = getNbRows(set);
- if (log.isInfoEnabled()) {
- log.info("For request " + sql + ", nb rows = " + nbRows);
- }
- pager.setRecords(nbRows);
- PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
- }
- }
-
- @Override
- protected Map<String, Object> prepareResult(ResultSet set) throws SQLException {
-
- if (pager != null) {
-
- // get row number (getRow() begins at 1)
- int rowNumber = set.getRow() - 1;
- if (rowNumber < pager.getRecordStartIndex() ||
- rowNumber >= pager.getRecordEndIndex()) {
-
- // out of pager bound, by returning null
- // result will not be take in account
- return null;
- }
- }
-
- Map<String, Object> result = getRowAsMap(columnNames, set);
- return result;
- }
-
-}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DbEditorService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DbEditorService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DbEditorService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DbEditorService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,785 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
+import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.EntityModificationLog;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.csv.ExportModel;
+import org.nuiton.csv.ExportableColumn;
+import org.nuiton.csv.ImportExportModel;
+import org.nuiton.csv.ImportableColumn;
+import org.nuiton.decorator.Decorator;
+import org.nuiton.decorator.JXPathDecorator;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.csv.EntityCsvModel;
+import org.nuiton.topia.persistence.metadata.ColumnMeta;
+import org.nuiton.topia.persistence.metadata.DbMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.topia.persistence.pager.FilterRule;
+import org.nuiton.topia.persistence.pager.FilterRuleGroupOperator;
+import org.nuiton.topia.persistence.pager.FilterRuleOperator;
+import org.nuiton.topia.persistence.pager.TopiaPagerBean;
+import org.nuiton.util.PagerBeanUtil;
+import org.nuiton.util.beans.BeanMonitor;
+import org.nuiton.util.beans.PropertyDiff;
+
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import static org.nuiton.i18n.I18n.l_;
+
+/**
+ * Service to edit the database.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public class DbEditorService extends EchoBaseServiceSupport {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(DbEditorService.class);
+
+ public <E extends TopiaEntity> List<E> getForeignData(Class<E> entityType) {
+ Preconditions.checkNotNull(entityType);
+ try {
+ TopiaDAO<E> dao = getEchoBasePersistenceContext().getDAO(entityType);
+
+ List<E> result = dao.findAll();
+ return result;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException("Could not obtain data", eee);
+ }
+ }
+
+ public TableMeta<EchoBaseEntityEnum> getTableMeta(EchoBaseEntityEnum tableName) {
+ DbMeta<EchoBaseEntityEnum> dbMeta = getDbMeta();
+ TableMeta<EchoBaseEntityEnum> result = dbMeta.getTable(tableName);
+ return result;
+ }
+
+ public Map<?, ?>[] getData(EchoBaseEntityEnum type, TopiaPagerBean pager) {
+
+ TableMeta<EchoBaseEntityEnum> meta = getTableMeta(type);
+
+ List<TopiaEntity> entities = getEntities(meta, pager);
+
+ Map<?, ?>[] rows = new Map[entities.size()];
+
+ ExportModel<TopiaEntity> model = buildForLoad(meta, "id", true);
+
+ int i = 0;
+ for (Object o : entities) {
+ TopiaEntity entity = (TopiaEntity) o;
+ Map<String, Object> row = loadRow(entity, model);
+ rows[i++] = row;
+ }
+ return rows;
+ }
+
+ public <E extends TopiaEntity> List<E> getEntities(TableMeta<EchoBaseEntityEnum> tableMeta,
+ TopiaPagerBean pager) {
+
+ EchoBaseEntityEnum entityEnum = tableMeta.getSource();
+ try {
+ TopiaDAO<E> dao = (TopiaDAO<E>) getEchoBasePersistenceContext().getDAO(entityEnum.getContract());
+
+ List<Object> paramsList = Lists.newArrayList();
+
+ String hql = dao.createSimpleQuery("e");
+
+ if (pager != null && pager.canFilter()) {
+ String filterHql = getFilterHql(tableMeta, pager, paramsList);
+ hql += " WHERE " + filterHql;
+ }
+
+ Object[] params = paramsList.toArray();
+
+ if (log.isInfoEnabled()) {
+ log.info("filterHql = " + hql + "\n" + Joiner.on('\n').join(params));
+ }
+
+
+ long count = dao.countByQuery("SELECT COUNT(*) " + hql, params);
+
+ if (pager != null) {
+
+ pager.setRecords(count);
+ PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
+ }
+
+ List<E> result = dao.findAllByQueryAndPager(hql, pager, params);
+ return result;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException("Could not obtain data", eee);
+ }
+ }
+
+ public <E extends TopiaEntity> Iterable<E> iterateOnEntities(TableMeta<EchoBaseEntityEnum> tableMeta,
+ String extraWhereQuery) {
+
+ try {
+ TopiaDAO<E> dao = (TopiaDAO<E>) getEchoBasePersistenceContext().getDAO(tableMeta.getSource().getContract());
+
+ String hql = "FROM " +
+ dao.getTopiaEntityEnum().getImplementationFQN() + " e";
+ if (extraWhereQuery != null) {
+ hql += " WHERE " + extraWhereQuery;
+ }
+ hql += " ORDER BY e.id";
+ Iterable<E> result = dao.findAllLazyByQuery(5000, hql);
+ return result;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException("Could not obtain data", eee);
+ }
+ }
+
+ public Map<?, ?> getData(TableMeta<EchoBaseEntityEnum> tableMeta, String topiaId) {
+
+ EchoBaseEntityEnum entityEnum = tableMeta.getSource();
+ try {
+ TopiaDAO<?> dao = getEchoBasePersistenceContext().getDAO(entityEnum.getContract());
+ TopiaEntity entity = dao.findByTopiaId(topiaId);
+ ExportModel<TopiaEntity> model = buildForLoad(tableMeta, TopiaEntity.PROPERTY_TOPIA_ID, true);
+ return loadRow(entity, model);
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException("Could not obtain data", eee);
+ }
+ }
+
+ public <E extends TopiaEntity> void decorateForeignKey(
+ Map data,
+ Class<E> propertyType,
+ String property,
+ String decoratorContext) {
+
+ DecoratorService decoratorService =
+ serviceContext.newService(DecoratorService.class);
+
+ E mission = getEchoBasePersistenceContext().getEntityById(propertyType, (String) data.get(property));
+ String voyageToString = decoratorService.decorate(getLocale(), mission, decoratorContext);
+ data.put(property + "_lbl", voyageToString);
+ }
+
+ public void saveEntity(TableMeta<EchoBaseEntityEnum> meta,
+ Map<String, String> properties,
+ EchoBaseUser user) {
+
+ // transform properties entity
+ ImportExportModel<TopiaEntity> model = buildForSave(meta);
+
+ TopiaEntity entity = model.newEmptyInstance();
+
+ for (ImportableColumn<TopiaEntity, Object> column : model.getColumnsForImport()) {
+ String propertyName = column.getHeaderName();
+ String stringValue = properties.get(propertyName);
+ Object o;
+ try {
+ o = column.parseValue(stringValue);
+ } catch (Exception e) {
+ throw new EchoBaseTechnicalException("Could not parse property [" + propertyName + "] with value " + stringValue, e);
+ }
+ try {
+ column.setValue(entity, o);
+ } catch (Exception e) {
+ throw new EchoBaseTechnicalException(
+ "Could not set property [" + propertyName + "] with value " + stringValue + " to entity " + entity, e);
+ }
+ }
+
+ saveEntity(meta,
+ "Modification utilisateur",
+ entity,
+ user,
+ false
+ );
+ getEchoBasePersistenceContext().commitTransaction();
+ }
+
+ public boolean saveEntity(TableMeta<EchoBaseEntityEnum> tableMeta,
+ String messagePrefix,
+ TopiaEntity entity,
+ EchoBaseUser user,
+ boolean createIfNotFound) {
+ String[] columnNames = tableMeta.getColumnNamesAsArray();
+ BeanMonitor monitor = null;
+
+ String id = entity.getTopiaId();
+
+ try {
+ TopiaDAO<?> dao = getEchoBasePersistenceContext().getDAO(tableMeta.getSource().getContract());
+
+ TopiaEntity entityToSave;
+
+ // Find or create entity if no id
+ boolean create = StringUtils.isEmpty(id);
+
+ if (create) {
+
+ // get naturalIds or not-null properties
+ Map<String, Object> properties =
+ tableMeta.prepareCreate(entity, null);
+
+ entityToSave = dao.create(properties);
+
+ // push back topiaId (could be used by caller)
+ entity.setTopiaId(entityToSave.getTopiaId());
+
+ } else {
+
+ entityToSave = dao.findByTopiaId(id);
+ if (entityToSave == null) {
+
+ if (!createIfNotFound) {
+
+ // this is an error
+ throw new EchoBaseTechnicalException(
+ "Could not found entity with id " + id);
+ } else {
+ entityToSave = dao.create(TopiaEntity.PROPERTY_TOPIA_ID, id);
+ create = true;
+ }
+ }
+ }
+
+ if (user != null && !create) {
+
+ // monitor the existing bean
+ monitor = new BeanMonitor(columnNames);
+ monitor.setBean(entityToSave);
+ }
+
+ tableMeta.copy(entity, entityToSave);
+
+ if (user != null) {
+
+ createEntityModificationLog(
+ tableMeta,
+ messagePrefix,
+ entityToSave,
+ user,
+ monitor
+ );
+ }
+ return create;
+ } catch (Exception eee) {
+ throw new EchoBaseTechnicalException("Could not update entity", eee);
+ } finally {
+ if (monitor != null) {
+ monitor.setBean(null);
+ }
+ }
+ }
+
+ protected <O> Decorator<O> getDecorator(Class<O> type) {
+ return getDecoratorService().getDecorator(getLocale(), type, null);
+ }
+
+ protected String getFilterHql(TableMeta<EchoBaseEntityEnum> tableMeta,
+ TopiaPagerBean pager,
+ List<Object> params) {
+ Preconditions.checkNotNull(pager);
+ Preconditions.checkState(pager.canFilter());
+
+ String filterHql = null;
+
+ Map<String, Object> filterParams = Maps.newHashMap();
+
+ List<String> strFilterRules = Lists.newLinkedList();
+
+ long timestamp = System.currentTimeMillis();
+ int index = 0;
+ for (FilterRule rule : pager.getRules()) {
+ String ruleFilter;
+
+ String field = rule.getField();
+
+ ColumnMeta columnMeta = tableMeta.getColumns(field);
+ Preconditions.checkNotNull(columnMeta,
+ "no property named " + columnMeta);
+
+ FilterRuleOperator op = rule.getOp();
+ String data = rule.getData();
+ String paramName = field + "_" + timestamp + (index++);
+ String propertyName = "e." + field;
+ Object realData = data;
+ if (columnMeta.isFK()) {
+
+ if (op == FilterRuleOperator.nu || op == FilterRuleOperator.nn) {
+
+ // is null or is not null is a simple case
+
+ ruleFilter = op.toHql(propertyName,
+ propertyName,
+ data,
+ filterParams);
+ } else {
+ // must do a select in using the decoration pattern
+ JXPathDecorator<?> decorator =
+ (JXPathDecorator<?>) getDecorator(columnMeta.getType());
+
+ if (decorator.getNbToken() == 1) {
+
+ String fName = "f_" + timestamp + (index++);
+
+ // simple case one token
+ String token = fName + "." + decorator.getProperty(0);
+
+ String subQuery = op.toHql(paramName,
+ token,
+ data,
+ filterParams);
+
+ ruleFilter = propertyName + " IN ( FROM " +
+ columnMeta.getType().getName() + " " +
+ fName + " WHERE " + subQuery + ")";
+ } else {
+
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ } else {
+
+ if (columnMeta.isNumber()) {
+
+ if (op == FilterRuleOperator.cn ||
+ op == FilterRuleOperator.nc ||
+ op == FilterRuleOperator.bw ||
+ op == FilterRuleOperator.bn ||
+ op == FilterRuleOperator.ew ||
+ op == FilterRuleOperator.en) {
+
+ // string operation
+
+// realData = "'" + realData + "'";
+ propertyName = "str(" + propertyName + ")";
+ } else {
+
+ // real number operation
+
+ if (columnMeta.getType() == int.class ||
+ columnMeta.getType() == Integer.class) {
+ realData = Integer.valueOf(data);
+ } else {
+
+ realData = Double.valueOf(data);
+ }
+ }
+ } else if (columnMeta.isDate()) {
+ propertyName = "str(" + propertyName + ")";
+ }
+ ruleFilter = op.toHql(paramName,
+ propertyName,
+ realData,
+ filterParams);
+ }
+
+ strFilterRules.add("(" + ruleFilter + ")");
+
+ if (CollectionUtils.isNotEmpty(strFilterRules)) {
+ FilterRuleGroupOperator groupOp =
+ pager.getGroupOp();
+ filterHql = StringUtils.join(strFilterRules, groupOp.name());
+ }
+
+ for (Map.Entry<String, Object> entry : filterParams.entrySet()) {
+ params.add(entry.getKey());
+ params.add(entry.getValue());
+ }
+ }
+ return filterHql;
+ }
+
+ protected void createEntityModificationLog(TableMeta<EchoBaseEntityEnum> tableMeta,
+ String messagePrefix,
+ TopiaEntity entity,
+ EchoBaseUser user,
+ BeanMonitor monitor) throws TopiaException {
+
+ StringBuilder buffer;
+
+ String topiaId = entity.getTopiaId();
+
+ buffer = new StringBuilder(messagePrefix).append('\n');
+ Locale l = getLocale();
+ if (monitor == null) {
+
+ // no monitor, means this is a creation of an object
+ buffer.append(l_(l, "echobase.info.newEntityCreated", topiaId));
+ } else {
+
+ PropertyDiff[] propertyDiffs = monitor.getPropertyDiffs();
+
+ int length = propertyDiffs.length;
+
+ if (length == 0) {
+
+ // no property modified, do nothing
+ return;
+ }
+
+ if (length == 1) {
+ buffer.append(l_(l, "echobase.info.onePropertyModified"));
+ } else {
+ buffer.append(
+ l_(l, "echobase.info.somePropertiesModified", length));
+ }
+ for (PropertyDiff diff : propertyDiffs) {
+
+ Object sourceValue = diff.getSourceValue();
+ Object targetValue = diff.getTargetValue();
+
+ String propertyName = diff.getSourceProperty();
+
+ if (tableMeta.getColumns(propertyName).isFK()) {
+
+ // replace by the decorate value
+ if (sourceValue != null) {
+ sourceValue = getDecoratorService().decorate(
+ l, sourceValue, null);
+ }
+ if (targetValue != null) {
+ targetValue = getDecoratorService().decorate(
+ l, targetValue, null);
+ }
+ }
+ buffer.append("\n ");
+ buffer.append(
+ l_(l, "echobase.info.modifiedProperty", propertyName,
+ sourceValue,
+ targetValue));
+ }
+ }
+
+ getEchoBasePersistenceContext().getEntityModificationLogDAO().create(
+ EntityModificationLog.PROPERTY_ENTITY_TYPE, tableMeta.getSource().name(),
+ EntityModificationLog.PROPERTY_ENTITY_ID, topiaId,
+ EntityModificationLog.PROPERTY_MODIFICATION_USER, user.getEmail(),
+ EntityModificationLog.PROPERTY_MODIFICATION_DATE, newDate(),
+ EntityModificationLog.PROPERTY_MODIFICATION_TEXT, buffer.toString()
+ );
+ }
+
+ protected <E extends TopiaEntity> Map<String, Object> loadRow(
+ E entity,
+ ExportModel<E> loadModel) {
+
+ Map<String, Object> row = Maps.newLinkedHashMap();
+
+ Iterable<ExportableColumn<E, Object>> columns =
+ loadModel.getColumnsForExport();
+
+ for (ExportableColumn<E, Object> column : columns) {
+ String propertyName = column.getHeaderName();
+ Object value;
+ try {
+ value = column.getValue(entity);
+ } catch (Exception eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not obtain property [" + propertyName +
+ "] value from entity " + entity.getTopiaId(), eee);
+ }
+ String formatedValue;
+ try {
+ formatedValue = column.formatValue(value);
+ } catch (Exception eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not format property [" + propertyName +
+ "] from value [" + value +
+ "] from entity " + entity.getTopiaId(), eee);
+ }
+ row.put(propertyName, formatedValue);
+
+ }
+ return row;
+ }
+
+ protected <E extends TopiaEntity> ImportExportModel<E> buildForSave(TableMeta<EchoBaseEntityEnum> meta) {
+
+ EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
+ getConfiguration().getCsvSeparator(),
+ meta,
+ TopiaEntity.PROPERTY_TOPIA_ID
+ );
+
+ for (ColumnMeta columnMeta : meta) {
+ String propertyName = columnMeta.getName();
+ Class<?> type = columnMeta.getType();
+ if (columnMeta.isFK()) {
+
+ Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
+ Collection<TopiaEntity> universe = getForeignData(entityType);
+
+ // translate foreign key to his id
+ model.addForeignKeyForImport(propertyName, entityType, universe);
+
+ } else if (Date.class.equals(type)) {
+ model.newMandatoryColumn(
+ propertyName,
+ EchoBaseCsvUtil.DATE_TIME_VALUE_PARSER);
+ } else {
+ model.addDefaultColumn(propertyName, type);
+ }
+ }
+ return model;
+ }
+
+ protected <E extends TopiaEntity> ExportModel<E> buildForLoad(TableMeta<EchoBaseEntityEnum> meta,
+ String idName,
+ boolean addDecorated) {
+
+ EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
+ getConfiguration().getCsvSeparator(),
+ meta,
+ idName
+ );
+
+ for (ColumnMeta columnMeta : meta) {
+ String propertyName = columnMeta.getName();
+ Class<?> type = columnMeta.getType();
+ if (columnMeta.isFK()) {
+
+ Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
+
+ // translate foreign key to his id
+ model.addForeignKeyForExport(propertyName, entityType);
+
+ if (addDecorated) {
+
+ // translate foreign key to his decorated value
+ Decorator<TopiaEntity> decorator = getDecorator(entityType);
+ model.addDecoratedForeignKeyForExport(
+ propertyName + "_lib",
+ propertyName,
+ decorator
+ );
+ }
+
+ } else if ("id".equals(propertyName)) {
+
+ if ("id".equals(idName)) {
+
+ // there will be a conflict with this meta, rename it to ID
+ model.addDefaultColumn("ID", propertyName, type);
+ } else {
+
+ // no id conflict
+ model.addDefaultColumn(propertyName, type);
+
+ }
+ } else if ("importId".equals(propertyName) &&
+ Collection.class.equals(type)) {
+
+ // special case we do not want to deal with {@link ImportLog#importId}
+ } else {
+ model.addDefaultColumn(propertyName, type);
+ }
+ }
+ return model;
+ }
+
+// public <E extends TopiaEntity> List<E> getEntities(TableMeta<EchoBaseEntityEnum> tableMeta, TopiaPagerBean pager) {
+//
+// //TODO-tchemit-2012-08-19 Replace TopiaQuery with simple hql query
+// List<E> result;
+// EchoBaseEntityEnum entityEnum = tableMeta.getSource();
+// try {
+// TopiaDAO<E> dao = (TopiaDAO<E>) getDAO(entityEnum.getContract());
+//
+// // first query to count datas
+// TopiaQuery countQuery = dao.createQuery("e");
+// countQuery.addSelect("count(*)");
+// String filterHql = null;
+//
+// Map<String, Object> filterParams = Maps.newHashMap();
+//
+// if (pager != null && pager.canFilter()) {
+//
+// DecoratorService decoratorService = getDecoratorService();
+//
+// // prepare the filter hql code
+// List<FilterRule> rules = pager.getRules();
+// List<String> strFilterRules = Lists.newLinkedList();
+// long timestamp = System.currentTimeMillis();
+// int index = 0;
+// for (FilterRule rule : rules) {
+// String ruleFilter;
+//
+// String field = rule.getField();
+//
+// ColumnMeta columnMeta = tableMeta.getColumns(field);
+// Preconditions.checkNotNull(
+// columnMeta, "no property named " + columnMeta);
+//
+// FilterRuleOperator op = rule.getOp();
+// String data = rule.getData();
+// String paramName = field + "_" + timestamp + (index++);
+// String propertyName = "e." + field;
+// Object realData = data;
+// if (columnMeta.isFK()) {
+//
+// // must do a select in using the decoration pattern
+//
+// JXPathDecorator<?> decorator =
+// (JXPathDecorator<?>) decoratorService.getDecorator(getLocale(),
+// columnMeta.getType(),
+// null);
+//
+// if (decorator.getNbToken() == 1) {
+//
+// // simple case one token
+// String token = "f." + decorator.getProperty(0);
+//
+// String subQuery = op.toHql(paramName,
+// token,
+// data,
+// filterParams);
+//
+// ruleFilter = propertyName + " in ( SELECT f FROM " + columnMeta.getType().getName() + " f WHERE " + subQuery + ")";
+// } else {
+//
+// throw new UnsupportedOperationException();
+// }
+//
+//
+// } else {
+//
+// if (columnMeta.isNumber()) {
+// if (columnMeta.getType() == int.class ||
+// columnMeta.getType() == Integer.class) {
+// realData = Integer.valueOf(data);
+// } else {
+//
+// realData = Double.valueOf(data);
+// }
+// } else if (columnMeta.isDate()) {
+// propertyName = "str(" + propertyName + ")";
+// }
+// ruleFilter = op.toHql(paramName,
+// propertyName,
+// realData,
+// filterParams);
+//
+// }
+//
+// strFilterRules.add("(" + ruleFilter + ")");
+// }
+//
+// if (CollectionUtils.isNotEmpty(strFilterRules)) {
+// FilterRuleGroupOperator groupOp =
+// pager.getGroupOp();
+// filterHql = StringUtils.join(strFilterRules, groupOp.name());
+// }
+// }
+//
+// if (filterHql != null) {
+// if (log.isInfoEnabled()) {
+// log.info("filterHql = " + filterHql);
+// }
+// for (Map.Entry<String, Object> e : filterParams.entrySet()) {
+// String paramName = e.getKey();
+// Object paramValue = e.getValue();
+// if (log.isInfoEnabled()) {
+// log.info("filterParam = " +
+// paramName + "/" + paramValue);
+// }
+// countQuery.addParam(paramName, paramValue);
+// }
+// countQuery.addWhere(filterHql);
+//
+// String fullQuery = countQuery.fullQuery();
+// if (log.isInfoEnabled()) {
+// log.info("fullquery = " + fullQuery);
+// }
+// }
+//
+// int count = dao.countByQuery(countQuery);
+//
+// TopiaQuery query = dao.createQuery("e");
+//
+// if (pager != null) {
+//
+// pager.setRecords(count);
+// PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
+//
+// long from = pager.getRecordStartIndex();
+// long to = pager.getRecordEndIndex();
+//
+// if (log.isDebugEnabled()) {
+// log.debug("Count = " + count);
+// log.debug("page = " + pager.getPageIndex());
+// log.debug("pageSize = " + pager.getPageSize());
+// log.debug("from = " + from);
+// log.debug("to = " + to);
+// log.debug("pageCount= " + pager.getPagesNumber());
+// }
+//
+// if (filterHql != null) {
+// for (Map.Entry<String, Object> entry : filterParams.entrySet()) {
+// String paramName = entry.getKey();
+// Object paramValue = entry.getValue();
+// query.addParam(paramName, paramValue);
+// }
+// query.addWhere(filterHql);
+// }
+//
+// String sidx = pager.getSortColumn();
+// boolean ascendantOrder = pager.isSortAscendant();
+//
+// if (StringUtils.isNotEmpty(sidx)) {
+// if (ascendantOrder) {
+// query.addOrder(sidx);
+// } else {
+// query.addOrderDesc(sidx);
+// }
+// }
+//
+// query.setLimit((int) from, (int) to - 1);
+// }
+//
+// dao.findAllByQueryAndPager("hql", pager, filterParams.toString());
+// result = dao.findAllByQuery(query);
+// return result;
+// } catch (TopiaException eee) {
+// throw new EchoBaseTechnicalException("Could not obtain data", eee);
+// }
+// }
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DecoratorService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/DecoratorService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DecoratorService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/DecoratorService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,384 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import fr.ifremer.echobase.I18nAble;
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.ExportQuery;
+import fr.ifremer.echobase.entities.ImportLog;
+import fr.ifremer.echobase.entities.WorkingDbConfiguration;
+import fr.ifremer.echobase.entities.data.Category;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.DataAcquisition;
+import fr.ifremer.echobase.entities.data.DataProcessing;
+import fr.ifremer.echobase.entities.data.Echotype;
+import fr.ifremer.echobase.entities.data.GearMetadataValue;
+import fr.ifremer.echobase.entities.data.LengthAgeKey;
+import fr.ifremer.echobase.entities.data.LengthWeightKey;
+import fr.ifremer.echobase.entities.data.Operation;
+import fr.ifremer.echobase.entities.data.OperationMetadataValue;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.data.Sample;
+import fr.ifremer.echobase.entities.data.SampleData;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.references.AcousticInstrument;
+import fr.ifremer.echobase.entities.references.AgeCategory;
+import fr.ifremer.echobase.entities.references.AreaOfOperation;
+import fr.ifremer.echobase.entities.references.Calibration;
+import fr.ifremer.echobase.entities.references.CategoryMeaning;
+import fr.ifremer.echobase.entities.references.CategoryRef;
+import fr.ifremer.echobase.entities.references.CategoryType;
+import fr.ifremer.echobase.entities.references.CellMethod;
+import fr.ifremer.echobase.entities.references.CellType;
+import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.entities.references.DataProtocol;
+import fr.ifremer.echobase.entities.references.DataQuality;
+import fr.ifremer.echobase.entities.references.DataType;
+import fr.ifremer.echobase.entities.references.DepthStratum;
+import fr.ifremer.echobase.entities.references.EchotypeCategory;
+import fr.ifremer.echobase.entities.references.Gear;
+import fr.ifremer.echobase.entities.references.GearCharacteristic;
+import fr.ifremer.echobase.entities.references.GearCharacteristicValue;
+import fr.ifremer.echobase.entities.references.GearMetadata;
+import fr.ifremer.echobase.entities.references.Impacte;
+import fr.ifremer.echobase.entities.references.MeasureType;
+import fr.ifremer.echobase.entities.references.MeasurementMetadata;
+import fr.ifremer.echobase.entities.references.Mission;
+import fr.ifremer.echobase.entities.references.OperationEvent;
+import fr.ifremer.echobase.entities.references.OperationMetadata;
+import fr.ifremer.echobase.entities.references.ReferenceDatum;
+import fr.ifremer.echobase.entities.references.ReferenceDatumType;
+import fr.ifremer.echobase.entities.references.ReferencingMethod;
+import fr.ifremer.echobase.entities.references.SampleDataType;
+import fr.ifremer.echobase.entities.references.SampleType;
+import fr.ifremer.echobase.entities.references.SexCategory;
+import fr.ifremer.echobase.entities.references.SizeCategory;
+import fr.ifremer.echobase.entities.references.Species;
+import fr.ifremer.echobase.entities.references.SpeciesCategory;
+import fr.ifremer.echobase.entities.references.Strata;
+import fr.ifremer.echobase.entities.references.TSParameters;
+import fr.ifremer.echobase.entities.references.Vessel;
+import fr.ifremer.echobase.entities.references.VesselType;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.apache.commons.collections.CollectionUtils;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.decorator.Decorator;
+import org.nuiton.decorator.DecoratorMulti18nProvider;
+import org.nuiton.decorator.DecoratorUtil;
+import org.nuiton.decorator.JXPathDecorator;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import static org.nuiton.i18n.I18n._;
+
+/**
+ * Service to decorate entities.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public class DecoratorService extends EchoBaseServiceSupport {
+
+ public static final String DATE_ONLY = "dateOnly";
+
+ protected final DecoratorMulti18nProvider decoratorProvider;
+
+ public DecoratorService() {
+ decoratorProvider = new EchoBaseDecoratorProvider();
+ }
+
+ public <O> Decorator<O> getDecorator(Locale locale,
+ Class<O> type,
+ String context) {
+ Preconditions.checkNotNull(type, "Decorator type can not be null!");
+ Decorator<O> decorator = decoratorProvider.getDecoratorByType(locale, type, context);
+ Preconditions.checkNotNull(
+ decorator,
+ "Could not find decorator for type " + type +
+ " and context " + context
+ );
+ return decorator;
+ }
+
+ public String decorate(Locale locale, Object o, String context) {
+ Decorator<?> decorator = getDecorator(locale, o.getClass(), context);
+ String result = decorator.toString(o);
+ return result;
+ }
+
+ public final <E extends Enum<E> & I18nAble> Map<String, String> decorateEnums(E... enumValues) {
+ Map<String, String> result = Maps.newLinkedHashMap();
+ for (E enumValue : enumValues) {
+ result.put(enumValue.name(), _(enumValue.getI18nKey()));
+ }
+ return result;
+ }
+
+ public <O> List<O> sortToList(Locale locale, Collection<O> beans, String context) {
+ Preconditions.checkNotNull(beans);
+ List<O> list = Lists.newArrayList(beans);
+ getDecoratorAndSort(locale, context, list);
+ return list;
+ }
+
+ public <E extends TopiaEntity> Map<String, String> sortAndDecorate(Locale locale,
+ Collection<E> beans,
+ String context) {
+ Preconditions.checkNotNull(beans);
+ List<E> list = Lists.newArrayList(beans);
+
+ Decorator<E> decorator = getDecoratorAndSort(locale, context, list);
+ Map<String, String> result = Maps.newLinkedHashMap();
+ for (E bean : list) {
+ result.put(bean.getTopiaId(), decorator.toString(bean));
+ }
+ return result;
+ }
+
+ protected <O> Decorator<O> getDecoratorAndSort(Locale locale,
+ String context,
+ List<O> list) {
+ Decorator<O> decorator = null;
+ if (CollectionUtils.isNotEmpty(list)) {
+ O object = list.get(0);
+ Preconditions.checkNotNull(object);
+ decorator = decoratorProvider.getDecorator(locale, object, context);
+ Preconditions.checkNotNull(
+ decorator,
+ "Could not find decorator for type " + object.getClass() +
+ " and context " + context
+ );
+ DecoratorUtil.sort((JXPathDecorator<O>) decorator, list, 0);
+ }
+ return decorator;
+ }
+
+ static class EchoBaseDecoratorProvider extends DecoratorMulti18nProvider {
+
+ @Override
+ protected void loadDecorators(Locale locale) {
+
+ // EchoBaseUser decorator
+ registerJXPathDecorator(locale, EchoBaseUser.class, "${email}$s");
+
+ // ExportQuery decorator
+ registerJXPathDecorator(locale, ExportQuery.class, "${name}$s - ${description}$s");
+
+ // ImportLog decorator
+ registerJXPathDecorator(locale, ImportLog.class, "${importType}$s - ${importDate}$s - ${importText}$s");
+
+ // ImportLog decorator
+ registerJXPathDecorator(locale, ImportLog.class, DATE_ONLY, "${importDate}$s");
+
+
+ // WorkingDbConfiguration decorator
+ registerJXPathDecorator(locale, WorkingDbConfiguration.class, "${url}$s - (${description}$s)");
+
+ // AcousticInstrument decorator
+ registerJXPathDecorator(locale, AcousticInstrument.class, "${id}$s");
+
+ // AgeCategory decorator
+ registerJXPathDecorator(locale, AgeCategory.class, "${name}$s");
+
+ // AreaOfOperation decorator
+ registerJXPathDecorator(locale, AreaOfOperation.class, "${name}$s");
+
+ // Calibration decorator
+ registerJXPathDecorator(locale, Calibration.class, "${date}$s - acquisition ${aquisitionMethod}$s");
+
+ // Category decorator
+ registerJXPathDecorator(locale, Category.class, "${echotypeLabel}$s ${speciesLabel}$s ${processedAgeLabel}$s ${processedLengthLabel}$s");
+
+ // CategoryMeaning decorator
+ registerJXPathDecorator(locale, CategoryMeaning.class, "${name}$s");
+
+ // CategoryRef decorator
+ registerJXPathDecorator(locale, CategoryRef.class, "${genusSpecies}$s");
+
+ // CategoryType decorator
+ registerJXPathDecorator(locale, CategoryType.class, "${name}$s");
+
+ // CellMethod decorator
+ registerJXPathDecorator(locale, CellMethod.class, "${name}$s");
+
+ // CellType decorator
+ registerJXPathDecorator(locale, CellType.class, "${name}$s");
+
+ // DataMetadata decorator
+ registerJXPathDecorator(locale, DataMetadata.class, "${name}$s - ${standardName}$s");
+ //registerJXPathDecorator(locale, DataMetadata.class, "${name}$s");
+
+ // DataProtocol decorator
+ registerJXPathDecorator(locale, DataProtocol.class, "${description}$s [ ${validSince}$td/%2$tm/%2$tY - ${invalidSince}$td/%3$tm/%3$tY ]");
+
+ // DataQuality decorator
+ //registerJXPathDecorator(locale, DataQuality.class, "${qualityDataFlagValues}$s - ${flagMeanings}$s");
+ registerJXPathDecorator(locale, DataQuality.class, "${flagMeanings}$s");
+
+ // DataType decorator
+ registerJXPathDecorator(locale, DataType.class, "${name}$s");
+
+ // DepthStratum decorator
+ //registerJXPathDecorator(locale, DepthStratum.class, "${id}$s - ${meaning}$s");
+ registerJXPathDecorator(locale, DepthStratum.class, "${meaning}$s");
+
+ // Echotype decorator
+ //registerJXPathDecorator(locale, Echotype.class, "${id}$s - ${name}$s");
+ registerJXPathDecorator(locale, Echotype.class, "${name}$s");
+
+ // EchotypeCategory decorator
+ registerJXPathDecorator(locale, EchotypeCategory.class, "${name}$s");
+
+ // Gear decorator
+ //registerJXPathDecorator(locale, Gear.class, "${name}$s [ ${validSince}$td/%2$tm/%2$tY - ${invalidSince}$td/%3$tm/%3$tY ]");
+ registerJXPathDecorator(locale, Gear.class, "${name}$s");
+
+ // GearCaracteristic decorator
+ registerJXPathDecorator(locale, GearCharacteristic.class, "${name}$s");
+
+ // GearMetadata decorator
+ //registerJXPathDecorator(locale, GearMetadata.class, "${name}$s (${operationEvent/name}$s)");
+ registerJXPathDecorator(locale, GearMetadata.class, "${name}$s");
+
+ // GearCharacteristicValue decorator
+ registerJXPathDecorator(locale, GearCharacteristicValue.class, "${dataValue}$s");
+
+ // GearMetadataValue decorator
+ registerJXPathDecorator(locale, GearMetadataValue.class, "${dataValue}$s");
+
+ // Impacte decorator
+ //registerJXPathDecorator(locale, Impacte.class, "${measurementUnit}$s - ${species/genusSpecies}");
+ registerJXPathDecorator(locale, Impacte.class, "${measurementUnit}$s");
+
+ // LengthAgeKey decorator
+ registerJXPathDecorator(locale, LengthAgeKey.class, "Age ${age}$s - Length ${length}");
+
+ // MeasurementMetadata decorator
+ registerJXPathDecorator(locale, MeasurementMetadata.class, "${name}$s");
+
+ // MeasureType decorator
+ registerJXPathDecorator(locale, MeasureType.class, "${name}$s");
+
+ // Mission decorator
+ registerJXPathDecorator(locale, Mission.class, "${name}$s");
+
+ // OperationEvent decorator
+ registerJXPathDecorator(locale, OperationEvent.class, "${name}$s");
+
+ // OperationMetadata decorator
+ registerJXPathDecorator(locale, OperationMetadata.class, "${name}$s");
+
+ // ReferenceDatum decorator
+ registerJXPathDecorator(locale, ReferenceDatum.class, "${id}$s");
+
+ // ReferenceDatumType decorator
+ registerJXPathDecorator(locale, ReferenceDatumType.class, "${name}$s");
+
+ // ReferencingMethod decorator
+ registerJXPathDecorator(locale, ReferencingMethod.class, "${name}$s");
+
+ // SampleDataType decorator
+ registerJXPathDecorator(locale, SampleDataType.class, "${name}$s");
+
+ // SampleType decorator
+ //registerJXPathDecorator(locale, SampleType.class, "${name}$s - level ${level}$s");
+ registerJXPathDecorator(locale, SampleType.class, "${name}$s");
+
+ // SexCategory decorator
+ registerJXPathDecorator(locale, SexCategory.class, "${name}$s");
+
+ // SizeCategory decorator
+ registerJXPathDecorator(locale, SizeCategory.class, "${name}$s");
+
+ // Species decorator
+ //registerJXPathDecorator(locale, Species.class, "${genusSpecies}$s (${baracoudaCode}$s)");
+ registerJXPathDecorator(locale, Species.class, "${genusSpecies}$s");
+
+ // SpeciesCategory decorator
+ registerJXPathDecorator(locale, SpeciesCategory.class, "${species/genusSpecies}$s ${sizeCategoryLabel}$s ${ageCategoryLabel}$s ${sexCategoryLabel}$s");
+
+ // Strata decorator
+ registerJXPathDecorator(locale, Strata.class, "Latitude <${minLatitude}$s - ${maxLatitude}$s>, Longitude <${minLongitude}$s - ${maxLongitude}$s>");
+
+ //TODO
+ // TSParameters decorator
+ registerJXPathDecorator(locale, TSParameters.class, "${}$s");
+
+ // Vessel decorator
+ registerJXPathDecorator(locale, Vessel.class, "${name}$s");
+
+ // VesselType decorator
+ registerJXPathDecorator(locale, VesselType.class, "${name}$s");
+
+ // LengthWeightKey decorator
+ registerJXPathDecorator(locale, LengthWeightKey.class, "Species ${species/genusSpecies}$s - a=${aParameter}$s, b=${bParameter}$s");
+
+ // Cell decorator
+ registerJXPathDecorator(locale, Cell.class, "${name}$s");
+
+ // Data decorator
+ registerJXPathDecorator(locale, Data.class, "${dataValue}$s");
+
+ // DataAcquisition decorator
+ registerJXPathDecorator(locale, DataAcquisition.class, "${acousticInstrument/id}$s ");
+
+ // DataProcessing decorator
+ registerJXPathDecorator(locale, DataProcessing.class, "${id}$s");
+
+ // Operation decorator
+ registerJXPathDecorator(locale, Operation.class, "${startDate}$td/%1$tm/%1$tY - ${endDate}$td/%2$tm/%2$tY");
+
+ // OperationMetadataValue decorator
+ registerJXPathDecorator(locale, OperationMetadataValue.class, "${operationMetadata/name} - ${dataValue}$s");
+
+ // Result decorator
+ registerJXPathDecorator(locale, Result.class, "${resultvalue}$s");
+
+ // Sample decorator
+ registerJXPathDecorator(locale, Sample.class, "${resultvalue}$s");
+
+ // SampleData decorator
+ registerJXPathDecorator(locale, SampleData.class, "${resultvalue}$s");
+
+ // Transect decorator
+ registerJXPathDecorator(locale, Transect.class, "${title}$s - Vessel ${vessel/name}$s");
+
+ // Transit decorator
+ registerJXPathDecorator(locale, Transit.class, "${startTime}$td/%1$tm/%1$tY - ${endTime}$td/%2$tm/%2$tY");
+
+ // Voyage decorator
+ registerJXPathDecorator(locale, Voyage.class, "${name}$s [ ${startDate}$td/%2$tm/%2$tY - ${endDate}$td/%3$tm/%3$tY ]");
+ }
+ }
+
+}
Added: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,159 @@
+package fr.ifremer.echobase.services.service;
+
+import fr.ifremer.echobase.entities.AbstractTopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.EchoBaseInternalEntityEnum;
+import fr.ifremer.echobase.entities.EchoBaseUserDAO;
+import fr.ifremer.echobase.entities.ExportQueryDAO;
+import fr.ifremer.echobase.entities.WorkingDbConfigurationDAO;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaIdFactory;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class InternalDbPersistenceService extends EchoBaseServiceSupport {
+
+
+ public void commitTransaction() {
+ getEchoBaseInternalPersistenceContext().commitTransaction();
+ }
+
+ public WorkingDbConfigurationDAO getWorkingDbConfigurationDAO() throws TopiaException {
+ return getEchoBaseInternalPersistenceContext().getWorkingDbConfigurationDAO();
+ }
+
+ public <E extends TopiaEntity> TopiaDAO<E> getDAO(Class<E> entityClass) {
+ return getEchoBaseInternalPersistenceContext().getDAO(entityClass);
+ }
+
+ public <E extends TopiaEntity, D extends TopiaDAO<E>> D getDAO(Class<E> entityClass, Class<D> daoClass) {
+ return getEchoBaseInternalPersistenceContext().getDAO(entityClass, daoClass);
+ }
+
+ public boolean isTableExists(Class<?> clazz) {
+ return getEchoBaseInternalPersistenceContext().isTableExists(clazz);
+ }
+
+ public <T extends TopiaEntity> void replicateEntity(TopiaContext destinationContext, T entity) throws IllegalArgumentException {
+ getEchoBaseInternalPersistenceContext().replicateEntity(destinationContext, entity);
+ }
+
+ public static String getModelName() {
+ return AbstractTopiaEchoBaseInternalPersistenceContext.getModelName();
+ }
+
+ public Properties getConfig() {
+ return getEchoBaseInternalPersistenceContext().getConfig();
+ }
+
+ public static <T extends TopiaEntity> Class<T> getContractClass(Class<T> klass) {
+ return AbstractTopiaEchoBaseInternalPersistenceContext.getContractClass(klass);
+ }
+
+
+ public List<Class<?>> getPersistenceClasses() {
+ return getEchoBaseInternalPersistenceContext().getPersistenceClasses();
+ }
+
+ public void rollbackTransaction() {
+ getEchoBaseInternalPersistenceContext().rollbackTransaction();
+ }
+
+ public static String getModelVersion() {
+ return AbstractTopiaEchoBaseInternalPersistenceContext.getModelVersion();
+ }
+
+ public void createSchema() {
+ getEchoBaseInternalPersistenceContext().createSchema();
+ }
+
+ public EchoBaseUserDAO getEchoBaseUserDAO() throws TopiaException {
+ return getEchoBaseInternalPersistenceContext().getEchoBaseUserDAO();
+ }
+
+ public boolean isClosed() {
+ return getEchoBaseInternalPersistenceContext().isClosed();
+ }
+
+ public TopiaIdFactory getTopiaIdFactory() {
+ return getEchoBaseInternalPersistenceContext().getTopiaIdFactory();
+ }
+
+ public void setUseFlushMode(boolean useFlushMode) {
+ getEchoBaseInternalPersistenceContext().setUseFlushMode(useFlushMode);
+ }
+
+ public <E extends TopiaEntity> E findByTopiaId(String topiaId) {
+ return getEchoBaseInternalPersistenceContext().findByTopiaId(topiaId);
+ }
+
+ public static EchoBaseInternalEntityEnum[] getContracts() {
+ return AbstractTopiaEchoBaseInternalPersistenceContext.getContracts();
+ }
+
+ public void closeContext() {
+ getEchoBaseInternalPersistenceContext().closeContext();
+ }
+
+ public String getSchemaName() {
+ return getEchoBaseInternalPersistenceContext().getSchemaName();
+ }
+
+ public ExportQueryDAO getExportQueryDAO() throws TopiaException {
+ return getEchoBaseInternalPersistenceContext().getExportQueryDAO();
+ }
+
+ public void dropSchema() {
+ getEchoBaseInternalPersistenceContext().dropSchema();
+ }
+
+ public void updateSchema() {
+ getEchoBaseInternalPersistenceContext().updateSchema();
+ }
+
+ public void update(TopiaEntity entity) {
+ getEchoBaseInternalPersistenceContext().update(entity);
+ }
+
+ public void replicate(TopiaContext destinationContext, Object... entityAndCondition) throws IllegalArgumentException {
+ getEchoBaseInternalPersistenceContext().replicate(destinationContext, entityAndCondition);
+ }
+
+ public <T extends TopiaEntity> void replicateEntities(TopiaContext destinationContext, List<T> entities) throws IllegalArgumentException {
+ getEchoBaseInternalPersistenceContext().replicateEntities(destinationContext, entities);
+ }
+
+ public void showCreateSchema() {
+ getEchoBaseInternalPersistenceContext().showCreateSchema();
+ }
+
+ public static String getImplementationClassesAsString() {
+ return AbstractTopiaEchoBaseInternalPersistenceContext.getImplementationClassesAsString();
+ }
+
+ public boolean isSchemaEmpty() {
+ return getEchoBaseInternalPersistenceContext().isSchemaEmpty();
+ }
+
+// public <E extends TopiaEntity> E getEntityById(Class<E> entityType, String id) {
+// return getEchoBaseInternalPersistenceContext().getEntityById(entityType, id);
+// }
+
+ public <E extends TopiaEntity> Map<String, String> loadSortAndDecorate(Class<E> beanType) {
+
+ List<E> beans = getEchoBaseInternalPersistenceContext().getDAO(beanType).findAll();
+ return getDecoratorService().sortAndDecorate(getLocale(), beans, null);
+ }
+
+}
Property changes on: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/InternalDbPersistenceService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/UserService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/UserService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/UserService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/UserService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,166 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service;
+
+import com.google.common.base.Preconditions;
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.EchoBaseUserDAO;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.apache.commons.lang3.StringUtils;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.pager.TopiaPagerBean;
+import org.nuiton.util.StringUtil;
+
+import java.util.List;
+
+/**
+ * @author sletellier <letellier(a)codelutin.com>
+ * @since 0.1
+ */
+public class UserService extends EchoBaseServiceSupport {
+
+ public static final String DEFAULT_ADMIN_EMAIL = "admin";
+
+ public static final String DEFAULT_ADMIN_PASSWORD = "admin";
+
+ public static final String DEFAULT_USER_EMAIL = "user";
+
+ public static final String DEFAULT_USER_PASSWORD = "user";
+
+ public List<EchoBaseUser> getUsers() {
+ return getUsers(null);
+ }
+
+ public List<EchoBaseUser> getUsers(TopiaPagerBean pager) {
+ try {
+ EchoBaseUserDAO dao = getDAO();
+ List<EchoBaseUser> users = dao.findAll(pager);
+ return users;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public EchoBaseUser getUserByEmail(String email) {
+ Preconditions.checkNotNull(email);
+ try {
+ EchoBaseUserDAO dao = getDAO();
+ EchoBaseUser user = dao.findByEmail(email);
+ return user;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public EchoBaseUser getUserById(String userId) {
+ Preconditions.checkNotNull(userId);
+ try {
+ EchoBaseUser user = getDAO().findByTopiaId(userId);
+ EchoBaseUser result = newUser();
+ result.setEmail(user.getEmail());
+ result.setPassword(user.getPassword());
+ result.setAdmin(user.isAdmin());
+ return result;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public void createOrUpdate(EchoBaseUser user) {
+ try {
+ EchoBaseUser userToCreateOrUpdate;
+
+ // No id, creating new one entity
+ String id = user.getTopiaId();
+ String password = user.getPassword();
+ if (StringUtils.isEmpty(id)) {
+ userToCreateOrUpdate = getDAO().create(
+ EchoBaseUser.PROPERTY_EMAIL, user.getEmail(),
+ EchoBaseUser.PROPERTY_PASSWORD, encodePassword(password)
+ );
+ } else {
+ userToCreateOrUpdate = getDAO().findByTopiaId(id);
+
+ userToCreateOrUpdate.setEmail(user.getEmail());
+ if (StringUtils.isNotEmpty(password)) {
+ userToCreateOrUpdate.setPassword(encodePassword(password));
+ }
+ }
+ userToCreateOrUpdate.setAdmin(user.isAdmin());
+ getEchoBaseInternalPersistenceContext().commitTransaction();
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public void delete(EchoBaseUser user) {
+ try {
+ EchoBaseUser userToDelete = getDAO().findByTopiaId(user.getTopiaId());
+ getDAO().delete(userToDelete);
+ getEchoBaseInternalPersistenceContext().commitTransaction();
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public boolean checkPassword(EchoBaseUser user,
+ String password) throws Exception {
+ String s = encodePassword(password);
+ return s.equals(user.getPassword());
+ }
+
+ public void createDefaultUsers() {
+ EchoBaseUser user;
+
+ user = newUser();
+ user.setEmail(DEFAULT_ADMIN_EMAIL);
+ user.setPassword(DEFAULT_ADMIN_PASSWORD);
+ user.setAdmin(true);
+ createOrUpdate(user);
+
+ user = newUser();
+ user.setEmail(DEFAULT_USER_EMAIL);
+ user.setPassword(DEFAULT_USER_PASSWORD);
+ user.setAdmin(false);
+ createOrUpdate(user);
+ }
+
+ public static String encodePassword(String password) {
+ String encodedPassword = StringUtil.encodeMD5(password);
+ return encodedPassword;
+ }
+
+ public EchoBaseUser newUser() {
+ try {
+ return getDAO().newInstance();
+ } catch (TopiaException e) {
+ throw new EchoBaseTechnicalException(e);
+ }
+ }
+
+ protected EchoBaseUserDAO getDAO() {
+ return getEchoBaseInternalPersistenceContext().getEchoBaseUserDAO();
+ }
+}
Added: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,310 @@
+package fr.ifremer.echobase.services.service;
+
+import fr.ifremer.echobase.entities.EntityModificationLogDAO;
+import fr.ifremer.echobase.entities.ImportLogDAO;
+import fr.ifremer.echobase.entities.data.CategoryDAO;
+import fr.ifremer.echobase.entities.data.CellDAO;
+import fr.ifremer.echobase.entities.data.DataAcquisitionDAO;
+import fr.ifremer.echobase.entities.data.DataDAO;
+import fr.ifremer.echobase.entities.data.DataProcessingDAO;
+import fr.ifremer.echobase.entities.data.EchotypeDAO;
+import fr.ifremer.echobase.entities.data.GearMetadataValueDAO;
+import fr.ifremer.echobase.entities.data.LengthAgeKeyDAO;
+import fr.ifremer.echobase.entities.data.LengthWeightKeyDAO;
+import fr.ifremer.echobase.entities.data.OperationDAO;
+import fr.ifremer.echobase.entities.data.OperationMetadataValueDAO;
+import fr.ifremer.echobase.entities.data.ResultDAO;
+import fr.ifremer.echobase.entities.data.SampleDAO;
+import fr.ifremer.echobase.entities.data.SampleDataDAO;
+import fr.ifremer.echobase.entities.data.TransectDAO;
+import fr.ifremer.echobase.entities.data.TransitDAO;
+import fr.ifremer.echobase.entities.data.VoyageDAO;
+import fr.ifremer.echobase.entities.references.AcousticInstrumentDAO;
+import fr.ifremer.echobase.entities.references.AgeCategoryDAO;
+import fr.ifremer.echobase.entities.references.AreaOfOperationDAO;
+import fr.ifremer.echobase.entities.references.CalibrationDAO;
+import fr.ifremer.echobase.entities.references.CategoryMeaningDAO;
+import fr.ifremer.echobase.entities.references.CategoryRefDAO;
+import fr.ifremer.echobase.entities.references.CategoryTypeDAO;
+import fr.ifremer.echobase.entities.references.CellMethodDAO;
+import fr.ifremer.echobase.entities.references.CellTypeDAO;
+import fr.ifremer.echobase.entities.references.DataMetadataDAO;
+import fr.ifremer.echobase.entities.references.DataProtocolDAO;
+import fr.ifremer.echobase.entities.references.DataQualityDAO;
+import fr.ifremer.echobase.entities.references.DataTypeDAO;
+import fr.ifremer.echobase.entities.references.DepthStratumDAO;
+import fr.ifremer.echobase.entities.references.EchotypeCategoryDAO;
+import fr.ifremer.echobase.entities.references.GearCharacteristicDAO;
+import fr.ifremer.echobase.entities.references.GearCharacteristicValueDAO;
+import fr.ifremer.echobase.entities.references.GearDAO;
+import fr.ifremer.echobase.entities.references.GearMetadataDAO;
+import fr.ifremer.echobase.entities.references.ImpacteDAO;
+import fr.ifremer.echobase.entities.references.MeasureTypeDAO;
+import fr.ifremer.echobase.entities.references.MeasurementMetadataDAO;
+import fr.ifremer.echobase.entities.references.MissionDAO;
+import fr.ifremer.echobase.entities.references.OperationEventDAO;
+import fr.ifremer.echobase.entities.references.OperationMetadataDAO;
+import fr.ifremer.echobase.entities.references.ReferenceDatumDAO;
+import fr.ifremer.echobase.entities.references.ReferenceDatumTypeDAO;
+import fr.ifremer.echobase.entities.references.ReferencingMethodDAO;
+import fr.ifremer.echobase.entities.references.SampleDataTypeDAO;
+import fr.ifremer.echobase.entities.references.SampleTypeDAO;
+import fr.ifremer.echobase.entities.references.SexCategoryDAO;
+import fr.ifremer.echobase.entities.references.SizeCategoryDAO;
+import fr.ifremer.echobase.entities.references.SpeciesCategoryDAO;
+import fr.ifremer.echobase.entities.references.SpeciesDAO;
+import fr.ifremer.echobase.entities.references.StrataDAO;
+import fr.ifremer.echobase.entities.references.TSParametersDAO;
+import fr.ifremer.echobase.entities.references.VesselDAO;
+import fr.ifremer.echobase.entities.references.VesselTypeDAO;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class WorkingDbPersistenceService extends EchoBaseServiceSupport {
+
+ public EntityModificationLogDAO getEntityModificationLogDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getEntityModificationLogDAO();
+ }
+
+ public ImportLogDAO getImportLogDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getImportLogDAO();
+ }
+
+ public CategoryDAO getCategoryDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCategoryDAO();
+ }
+
+ public CellDAO getCellDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCellDAO();
+ }
+
+ public DataDAO getDataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataDAO();
+ }
+
+ public DataAcquisitionDAO getDataAcquisitionDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataAcquisitionDAO();
+ }
+
+ public DataProcessingDAO getDataProcessingDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataProcessingDAO();
+ }
+
+ public EchotypeDAO getEchotypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getEchotypeDAO();
+ }
+
+ public GearMetadataValueDAO getGearMetadataValueDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getGearMetadataValueDAO();
+ }
+
+ public LengthAgeKeyDAO getLengthAgeKeyDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getLengthAgeKeyDAO();
+ }
+
+ public LengthWeightKeyDAO getLengthWeightKeyDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getLengthWeightKeyDAO();
+ }
+
+ public OperationDAO getOperationDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getOperationDAO();
+ }
+
+ public OperationMetadataValueDAO getOperationMetadataValueDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getOperationMetadataValueDAO();
+ }
+
+ public ResultDAO getResultDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getResultDAO();
+ }
+
+ public SampleDAO getSampleDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSampleDAO();
+ }
+
+ public SampleDataDAO getSampleDataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSampleDataDAO();
+ }
+
+ public TransectDAO getTransectDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getTransectDAO();
+ }
+
+ public TransitDAO getTransitDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getTransitDAO();
+ }
+
+ public VoyageDAO getVoyageDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getVoyageDAO();
+ }
+
+ public AcousticInstrumentDAO getAcousticInstrumentDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getAcousticInstrumentDAO();
+ }
+
+ public AgeCategoryDAO getAgeCategoryDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getAgeCategoryDAO();
+ }
+
+ public AreaOfOperationDAO getAreaOfOperationDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getAreaOfOperationDAO();
+ }
+
+ public CalibrationDAO getCalibrationDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCalibrationDAO();
+ }
+
+ public CategoryMeaningDAO getCategoryMeaningDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCategoryMeaningDAO();
+ }
+
+ public CategoryRefDAO getCategoryRefDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCategoryRefDAO();
+ }
+
+ public CategoryTypeDAO getCategoryTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCategoryTypeDAO();
+ }
+
+ public CellMethodDAO getCellMethodDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCellMethodDAO();
+ }
+
+ public CellTypeDAO getCellTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getCellTypeDAO();
+ }
+
+ public DataMetadataDAO getDataMetadataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataMetadataDAO();
+ }
+
+ public DataProtocolDAO getDataProtocolDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataProtocolDAO();
+ }
+
+ public DataQualityDAO getDataQualityDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataQualityDAO();
+ }
+
+ public DataTypeDAO getDataTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDataTypeDAO();
+ }
+
+ public DepthStratumDAO getDepthStratumDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getDepthStratumDAO();
+ }
+
+ public EchotypeCategoryDAO getEchotypeCategoryDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getEchotypeCategoryDAO();
+ }
+
+ public GearDAO getGearDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getGearDAO();
+ }
+
+ public GearCharacteristicDAO getGearCharacteristicDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getGearCharacteristicDAO();
+ }
+
+ public GearCharacteristicValueDAO getGearCharacteristicValueDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getGearCharacteristicValueDAO();
+ }
+
+ public GearMetadataDAO getGearMetadataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getGearMetadataDAO();
+ }
+
+ public ImpacteDAO getImpacteDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getImpacteDAO();
+ }
+
+ public MeasureTypeDAO getMeasureTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getMeasureTypeDAO();
+ }
+
+ public MeasurementMetadataDAO getMeasurementMetadataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getMeasurementMetadataDAO();
+ }
+
+ public MissionDAO getMissionDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getMissionDAO();
+ }
+
+ public OperationEventDAO getOperationEventDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getOperationEventDAO();
+ }
+
+ public OperationMetadataDAO getOperationMetadataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getOperationMetadataDAO();
+ }
+
+ public ReferenceDatumDAO getReferenceDatumDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getReferenceDatumDAO();
+ }
+
+ public ReferenceDatumTypeDAO getReferenceDatumTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getReferenceDatumTypeDAO();
+ }
+
+ public ReferencingMethodDAO getReferencingMethodDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getReferencingMethodDAO();
+ }
+
+ public SampleDataTypeDAO getSampleDataTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSampleDataTypeDAO();
+ }
+
+ public SampleTypeDAO getSampleTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSampleTypeDAO();
+ }
+
+ public SexCategoryDAO getSexCategoryDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSexCategoryDAO();
+ }
+
+ public SizeCategoryDAO getSizeCategoryDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSizeCategoryDAO();
+ }
+
+ public SpeciesDAO getSpeciesDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSpeciesDAO();
+ }
+
+ public SpeciesCategoryDAO getSpeciesCategoryDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getSpeciesCategoryDAO();
+ }
+
+ public StrataDAO getStrataDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getStrataDAO();
+ }
+
+ public TSParametersDAO getTSParametersDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getTSParametersDAO();
+ }
+
+ public VesselDAO getVesselDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getVesselDAO();
+ }
+
+ public VesselTypeDAO getVesselTypeDAO() throws TopiaException {
+ return getEchoBasePersistenceContext().getVesselTypeDAO();
+ }
+
+ public <E extends TopiaEntity> Map<String, String> loadSortAndDecorate(Class<E> beanType) {
+
+ List<E> beans = getEchoBasePersistenceContext().getDAO(beanType).findAll();
+
+ return getDecoratorService().sortAndDecorate(getLocale(), beans, null);
+ }
+
+}
Property changes on: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/WorkingDbPersistenceService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationConfiguration.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationConfiguration.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationConfiguration.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,105 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.embeddedapplication;
+
+import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
+import org.apache.commons.io.FileUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+
+/**
+ * Configuration of a embedded application creation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class EmbeddedApplicationConfiguration extends AbstractEchobaseActionConfiguration {
+
+ private static final long serialVersionUID = 1L;
+
+ /** File name of the embedded application archive (without the zip extension). */
+ private String fileName;
+
+ /** Working directory where to generate the archive of embedded application. */
+ private File workingDirectory;
+
+ /** Embedded application archive file. */
+ private File embeddedApplicationFile;
+
+ /** Location of the war file to push in embedded application. */
+ private File warLocation;
+
+ /** Ids of voyages to push in embedded application (with all their datas). */
+ private String[] voyageIds;
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public File getWorkingDirectory() {
+ return workingDirectory;
+ }
+
+ public void setWorkingDirectory(File workingDirectory) {
+ this.workingDirectory = workingDirectory;
+ }
+
+ public File getEmbeddedApplicationFile() {
+ return embeddedApplicationFile;
+ }
+
+ public void setEmbeddedApplicationFile(File embeddedApplicationFile) {
+ this.embeddedApplicationFile = embeddedApplicationFile;
+ }
+
+ public String[] getVoyageIds() {
+ return voyageIds;
+ }
+
+ // Attention on ne peut pas utiliser un ... car sinon ça plante dans l'ui
+ public void setVoyageIds(String[] voyageIds) {
+ this.voyageIds = Arrays.copyOf(voyageIds, voyageIds.length);
+ }
+
+ public File getWarLocation() {
+ return warLocation;
+ }
+
+ public void setWarLocation(File warLocation) {
+ this.warLocation = warLocation;
+ }
+
+ @Override
+ public void destroy() throws IOException {
+ if (workingDirectory != null) {
+ FileUtils.deleteDirectory(workingDirectory);
+ }
+ }
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,419 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.embeddedapplication;
+
+import com.google.common.base.Charsets;
+import com.google.common.base.Preconditions;
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.ExportQuery;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.entities.WorkingDbConfiguration;
+import fr.ifremer.echobase.io.EchoBaseIOUtil;
+import fr.ifremer.echobase.persistence.EchoBaseEntityHelper;
+import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
+import fr.ifremer.echobase.persistence.JdbcConfiguration;
+import fr.ifremer.echobase.services.DefaultEchoBaseServiceContext;
+import fr.ifremer.echobase.services.EchoBaseServiceContext;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbConfiguration;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbMode;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryInvalidNameException;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryNameAlreadyExistException;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdb.ImportDbConfiguration;
+import fr.ifremer.echobase.services.service.importdb.ImportDbMode;
+import fr.ifremer.echobase.services.service.importdb.ImportDbService;
+import fr.ifremer.echobase.services.service.UserService;
+import fr.ifremer.echobase.services.service.workingDb.WorkingDbConfigurationAlreadyExistException;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.util.FileUtil;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.List;
+
+/**
+ * To create embedded application.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @author sletellier <letellier(a)codelutin.com>
+ * @since 0.1
+ */
+public class EmbeddedApplicationService extends EchoBaseServiceSupport {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(EmbeddedApplicationService.class);
+
+ public static final String EMBEDDED_PATH = "/embedded/";
+
+ public File createEmbeddedApplication(EmbeddedApplicationConfiguration model) {
+
+ int nbSteps = computeNbSteps(model);
+ model.setNbSteps(nbSteps);
+
+ String fileName = model.getFileName();
+
+ File tempDirectory = model.getWorkingDirectory();
+ tempDirectory.deleteOnExit();
+
+ File zipFile = new File(tempDirectory, fileName + ".zip");
+ model.setEmbeddedApplicationFile(zipFile);
+
+ File dir = new File(tempDirectory, fileName);
+
+ if (log.isInfoEnabled()) {
+ log.info("Creates embedded application to file [" + zipFile + "]");
+ }
+
+ // export db to csv
+ File exportZipFile = exportDb(model, tempDirectory);
+
+ // create static archive structure
+ createStaticArchiveStructure(model, dir);
+
+ model.incrementsProgress();
+
+ // create new service context
+ EchoBaseServiceContext newServiceContext =
+ DefaultEchoBaseServiceContext.newContext(
+ getLocale(),
+ getConfiguration(),
+ getDbMeta(),
+ getSpatialDataCache());
+
+ EchoBaseUser admin;
+ try {
+ admin = importInternalDb(model, dir, newServiceContext);
+ } catch (Exception e) {
+ throw new EchoBaseTechnicalException(
+ "Could not create internal db", e);
+ }
+
+ // create working db in /db
+ try {
+ importWorkingDb(model, dir, exportZipFile, newServiceContext, admin);
+
+ } catch (Exception eee) {
+
+ throw new EchoBaseTechnicalException(
+ "Could not create h2 working database at " + dir, eee);
+ }
+
+ try {
+ EchoBaseIOUtil.compressZipFile(zipFile, dir);
+ } catch (IOException eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not create zip file at " + zipFile, eee);
+ }
+
+ return zipFile;
+ }
+
+ protected EchoBaseUser importInternalDb(EmbeddedApplicationConfiguration model,
+ File dir,
+ EchoBaseServiceContext newServiceContext) throws TopiaException, ExportQueryNameAlreadyExistException, WorkingDbConfigurationAlreadyExistException, ExportQueryInvalidNameException {
+
+ File internalDir = new File(dir, "internaldb");
+
+ TopiaContext internalRootContext =
+ EchobaseTopiaContexts.newInternalDb(internalDir);
+
+ TopiaContext internalTransaction = internalRootContext.beginTransaction();
+ TopiaEchoBaseInternalPersistenceContext newPersistenceContext = new TopiaEchoBaseInternalPersistenceContext(
+ internalTransaction
+ );
+ newServiceContext.setEchoBaseInternalPersistenceContext(newPersistenceContext);
+// newServiceContext.setInternalTransaction(
+// internalRootContext.beginTransaction());
+
+
+ try {
+ // get user service from h2 db
+ UserService userService = newServiceContext.newService(UserService.class);
+
+ // create admin user
+ userService.createDefaultUsers();
+
+ // get admin from h2 db
+ EchoBaseUser admin = userService.getUserByEmail(
+ UserService.DEFAULT_ADMIN_EMAIL);
+
+ model.incrementsProgress();
+
+ // get all export queries from application
+ List<ExportQuery> queries = getEchoBaseInternalPersistenceContext().getExportQueryDAO().findAll();
+
+ // replicate queries
+ getEchoBaseInternalPersistenceContext().replicateEntities(
+ internalTransaction, queries);
+
+ // create export sql service from h2 db
+ ExportQueryService exportQueryService =
+ newServiceContext.newService(ExportQueryService.class);
+
+ // get all queries from h2 db
+ queries = newPersistenceContext.getExportQueryDAO().findAll();
+
+ // attach them to default created admin user in the db
+ for (ExportQuery query : queries) {
+ exportQueryService.createOrUpdate(query, admin);
+ }
+
+ model.incrementsProgress();
+
+ // get all working db configuration from application
+
+ List<WorkingDbConfiguration> confs =
+ getEchoBaseInternalPersistenceContext().getWorkingDbConfigurationDAO().findAll();
+
+ // replicate configs
+ getEchoBaseInternalPersistenceContext().replicateEntities(
+ internalTransaction, confs);
+
+ model.incrementsProgress();
+
+ return admin;
+
+ } finally {
+ newServiceContext.setEchoBaseInternalPersistenceContext(null);
+ EchoBaseEntityHelper.releaseRootContext(internalRootContext);
+ }
+ }
+
+ protected void importWorkingDb(EmbeddedApplicationConfiguration model,
+ File dir,
+ File exportZipFile,
+ EchoBaseServiceContext newServiceContext,
+ EchoBaseUser admin) throws IOException, ImportException, TopiaException {
+
+ JdbcConfiguration dbConf = JdbcConfiguration.newEmbeddedConfig(dir);
+ TopiaContext rootContext = EchobaseTopiaContexts.newWorkingDb(
+ dbConf);
+ try {
+
+ // inject a new transaction in service context
+ newServiceContext.setEchoBasePersistenceContext(new TopiaEchoBasePersistenceContext(rootContext.beginTransaction()));
+
+ model.incrementsProgress();
+
+ // prepare import configuration
+ ImportDbConfiguration importConfiguration =
+ new ImportDbConfiguration(model, getLocale());
+ importConfiguration.getInput().setFile(exportZipFile);
+ File importTempDir = new File(model.getWorkingDirectory(), "importDb");
+ importConfiguration.setWorkingDirectory(importTempDir);
+ importConfiguration.setImportDbMode(ImportDbMode.FREE);
+ importConfiguration.setComputeSteps(false);
+ importConfiguration.setCommitAfterEachFile(true);
+
+ // do import to embedded working db
+ newServiceContext.newService(ImportDbService.class).doImport(
+ importConfiguration, admin);
+
+ } finally {
+ // remove current transaction
+ newServiceContext.setEchoBasePersistenceContext(null);
+
+ // release any connexion to the working db
+ EchoBaseEntityHelper.releaseRootContext(rootContext);
+ }
+ }
+
+// protected void closeContext(TopiaContext tx, String message) {
+// try {
+// tx.closeContext();
+// } catch (TopiaException eee) {
+// throw new EchoBaseTechnicalException(message, eee);
+// }
+// }
+
+// protected TopiaContext beginTransaction(TopiaContext tx, String message) {
+// try {
+// return tx.beginTransaction();
+// } catch (TopiaException eee) {
+// throw new EchoBaseTechnicalException(message, eee);
+// }
+// }
+
+// protected void rollbackTransaction(TopiaContext tx, String message) {
+// try {
+// if (tx != null) {
+// tx.rollbackTransaction();
+// }
+// } catch (TopiaException eee) {
+// if (log.isErrorEnabled()) {
+// log.error(message, eee);
+// }
+// }
+// }
+
+ protected int computeNbSteps(EmbeddedApplicationConfiguration model) {
+ int nbSteps = 5;
+
+ // export db steps
+
+ nbSteps += getDbMeta().getReferenceEntriesSize();
+ if (model.getVoyageIds() != null) {
+ nbSteps += model.getVoyageIds().length;
+ }
+
+ // import db stesp
+ nbSteps += getDbMeta().getEntriesSize();
+ return nbSteps;
+ }
+
+ protected void createStaticArchiveStructure(EmbeddedApplicationConfiguration model, File dir) {
+
+ try {
+
+ // create /
+ FileUtil.createDirectoryIfNecessary(dir);
+
+ // copy embedded files to /
+ copyEmbeddedTextFile("echobase.properties", dir, false);
+ copyEmbeddedTextFile("startEchobase.bat", dir, true);
+ copyEmbeddedTextFile("startEchobase.sh", dir, true);
+ copyEmbeddedTextFile("README.txt", dir, false);
+
+ // copy war to /
+ File warLocation = model.getWarLocation();
+ FileUtils.copyFile(warLocation,
+ new File(dir, warLocation.getName()));
+ } catch (Exception eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not create embedded zip structure at " + dir, eee);
+ }
+ }
+
+ protected File exportDb(EmbeddedApplicationConfiguration model, File dir) {
+
+ try {
+ // create export zip file
+ ExportDbConfiguration exportconfiguration =
+ new ExportDbConfiguration(model);
+ exportconfiguration.setFileName("echobase-export");
+ File exportTempDir = new File(dir, "exportDb");
+ exportconfiguration.setWorkingDirectory(exportTempDir);
+ exportconfiguration.setVoyageIds(model.getVoyageIds());
+ exportconfiguration.setComputeSteps(false);
+ exportconfiguration.setExportDbMode(ExportDbMode.REFERENTIAL_AND_DATA);
+
+ TopiaEchoBasePersistenceContext persistenceContext = serviceContext.getEchoBasePersistenceContext();
+
+ TopiaContext newTx = persistenceContext.getContext().beginTransaction();
+
+ TopiaEchoBasePersistenceContext newPersistenceContext = new TopiaEchoBasePersistenceContext(newTx);
+
+// TopiaContext transaction = serviceContext.getTransaction();
+
+
+ try {
+ serviceContext.setEchoBasePersistenceContext(newPersistenceContext);
+ getExportDbService().doExport(exportconfiguration);
+ } catch (IOException eee) {
+ newPersistenceContext.rollbackTransaction();
+ throw eee;
+ } catch (RuntimeException eee) {
+ newPersistenceContext.rollbackTransaction();
+ throw eee;
+ } finally {
+ serviceContext.setEchoBasePersistenceContext(persistenceContext);
+ newPersistenceContext.closeContext();
+ }
+ File exportZipFile = exportconfiguration.getExportFile();
+ if (log.isInfoEnabled()) {
+ log.info("Export zip file = " + exportZipFile);
+ }
+ return exportZipFile;
+ } catch (IOException eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not export db to zip", eee);
+ }
+ }
+
+ public void copyEmbeddedTextFile(String resourceName,
+ File targetDirectory,
+ boolean executable) throws IOException {
+ String resourcePath = EMBEDDED_PATH + resourceName;
+ InputStream inputStream = getClass().getResourceAsStream(resourcePath);
+ Preconditions.checkNotNull(inputStream,
+ "could not find resource " + resourcePath);
+ try {
+ File outputFile = new File(targetDirectory, resourceName);
+ if (log.isInfoEnabled()) {
+ log.info("Copy configuration to " + resourceName + " to " + outputFile);
+ }
+ OutputStreamWriter outputStream = new OutputStreamWriter(
+ new FileOutputStream(outputFile), Charsets.UTF_8);
+ try {
+ IOUtils.copy(inputStream, outputStream);
+ } finally {
+ outputStream.close();
+ }
+ if (executable) {
+ outputFile.setExecutable(true);
+ }
+ } finally {
+ inputStream.close();
+ }
+ }
+
+ public void copyEmbeddedBinaryFile(String resourceName,
+ File targetDirectory) throws IOException {
+ String resourcePath = EMBEDDED_PATH + resourceName;
+ InputStream inputStream = getClass().getResourceAsStream(resourcePath);
+ Preconditions.checkNotNull(inputStream,
+ "could not find resource " + resourcePath);
+ try {
+ File outputFile = new File(targetDirectory, resourceName);
+ if (log.isInfoEnabled()) {
+ log.info("Copy binary file from " + resourceName + " to " +
+ outputFile);
+ }
+ OutputStream outputStream = new FileOutputStream(outputFile);
+ try {
+ IOUtils.copy(inputStream, outputStream);
+ outputStream.close();
+ } finally {
+ IOUtils.closeQuietly(outputStream);
+ }
+ inputStream.close();
+ } finally {
+ IOUtils.closeQuietly(inputStream);
+ }
+ }
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbConfiguration.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbConfiguration.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbConfiguration.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,119 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportdb;
+
+import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
+import fr.ifremer.echobase.services.ProgressModel;
+import org.apache.commons.io.FileUtils;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Configuration of a complete db export.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class ExportDbConfiguration extends AbstractEchobaseActionConfiguration {
+
+ private static final long serialVersionUID = 1L;
+
+ private String fileName;
+
+ private File workingDirectory;
+
+ private File exportFile;
+
+ private ExportDbMode exportDbMode;
+
+ /** Ids of voyages to push in embedded application (with all their datas). */
+ private String[] voyageIds;
+
+ private boolean computeSteps;
+
+ public ExportDbConfiguration() {
+ }
+
+ public ExportDbConfiguration(ProgressModel progressModel) {
+ super(progressModel);
+ }
+
+ public String getFileName() {
+ return fileName;
+ }
+
+ public void setFileName(String fileName) {
+ this.fileName = fileName;
+ }
+
+ public File getWorkingDirectory() {
+ return workingDirectory;
+ }
+
+ public void setWorkingDirectory(File workingDirectory) {
+ this.workingDirectory = workingDirectory;
+ }
+
+ public File getExportFile() {
+ return exportFile;
+ }
+
+ public void setExportFile(File exportFile) {
+ this.exportFile = exportFile;
+ }
+
+ public String[] getVoyageIds() {
+ return voyageIds;
+ }
+
+ // Attention on ne peut pas utiliser un ... car sinon ça plante dans l'ui
+ public void setVoyageIds(String[] voyageIds) {
+ this.voyageIds = voyageIds;
+ }
+
+ public ExportDbMode getExportDbMode() {
+ return exportDbMode;
+ }
+
+ public void setExportDbMode(ExportDbMode exportDbMode) {
+ this.exportDbMode = exportDbMode;
+ }
+
+ public boolean isComputeSteps() {
+ return computeSteps;
+ }
+
+ public void setComputeSteps(boolean computeSteps) {
+ this.computeSteps = computeSteps;
+ }
+
+ @Override
+ public void destroy() throws IOException {
+ if (workingDirectory != null) {
+ FileUtils.deleteDirectory(workingDirectory);
+ }
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbMode.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbMode.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbMode.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbMode.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,71 @@
+package fr.ifremer.echobase.services.service.exportdb;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.I18nAble;
+
+import static org.nuiton.i18n.I18n.n_;
+
+/**
+ * Db export mode.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.2
+ */
+public enum ExportDbMode implements I18nAble {
+
+ /** Export only referential. */
+ REFERENTIAL(n_("echobase.common.exportDbMode.referential"), true, false),
+
+ /** Export selected data + referential. */
+ REFERENTIAL_AND_DATA(n_("echobase.common.exportDbMode.referentialAndData"), true, true),
+
+ /** Export all the db. */
+ ALL(n_("echobase.common.exportDbMode.all"), true, true);
+
+ private final String i18nKey;
+
+ private final boolean exportReferential;
+
+ private final boolean exportData;
+
+ ExportDbMode(String i18nKey, boolean exportReferential, boolean exportData) {
+ this.i18nKey = i18nKey;
+ this.exportReferential = exportReferential;
+ this.exportData = exportData;
+ }
+
+ @Override
+ public String getI18nKey() {
+ return i18nKey;
+ }
+
+ public boolean isExportReferential() {
+ return exportReferential;
+ }
+
+ public boolean isExportData() {
+ return exportData;
+ }
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportDbService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportDbService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,272 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportdb;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.io.EchoBaseIOUtil;
+import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaPersistenceHelper;
+import org.nuiton.topia.persistence.csv.out.ExportEntityVisitor;
+import org.nuiton.topia.persistence.csv.out.TopiaCsvExports;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.util.FileUtil;
+import org.nuiton.util.TimeLog;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Service to import / export a complete db.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class ExportDbService extends EchoBaseServiceSupport {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(ExportDbService.class);
+
+ public static final TimeLog timeLog = new TimeLog(ExportDbService.class);
+
+ public void doExport(ExportDbConfiguration model) throws IOException {
+
+ String fileName = model.getFileName();
+
+ File tempDirectory = model.getWorkingDirectory();
+
+ File zipFile = new File(tempDirectory, fileName + ".echobase");
+
+ if (log.isInfoEnabled()) {
+ log.info("Will export db to " + zipFile);
+ }
+ model.setExportFile(zipFile);
+
+ File dir = new File(tempDirectory, "echobase");
+
+ FileUtil.createDirectoryIfNecessary(dir);
+
+ ExportDbMode exportDbMode = model.getExportDbMode();
+
+ ExportService exportService = getExportService();
+
+ boolean exportVoyagesByVisitor = exportDbMode.isExportData();
+
+ if (exportVoyagesByVisitor) {
+
+ long nbVoyages = getEchoBasePersistenceContext().getVoyageDAO().count();
+ if (exportDbMode == ExportDbMode.ALL ||
+ model.getVoyageIds().length == nbVoyages) {
+
+ // no need to export via visitor, can export all data tables
+ exportVoyagesByVisitor = false;
+ }
+ }
+
+ List<TableMeta<EchoBaseEntityEnum>> tablesToExport = Lists.newArrayList();
+ List<AssociationMeta<EchoBaseEntityEnum>> associationsToExport = Lists.newArrayList();
+
+ EchoBaseDbMeta dbMeta = getDbMeta();
+
+ if (exportDbMode.isExportReferential()) {
+
+ // add referential tables
+ tablesToExport.addAll(dbMeta.getReferenceTables());
+ associationsToExport.addAll(dbMeta.getReferenceAssociations());
+ }
+
+ if (exportDbMode.isExportData() && !exportVoyagesByVisitor) {
+
+ // will export complete data tables
+ tablesToExport.addAll(dbMeta.getDataTables());
+ associationsToExport.addAll(dbMeta.getDataAssociations());
+ }
+
+ if (model.isComputeSteps()) {
+
+ int nbSteps = tablesToExport.size() + associationsToExport.size();
+
+ if (exportVoyagesByVisitor) {
+ nbSteps += model.getVoyageIds().length;
+ }
+
+ if (log.isInfoEnabled()) {
+ log.info("NB steps: " + nbSteps);
+ }
+ model.setNbSteps(nbSteps);
+ }
+
+ exportTables(model, dir, tablesToExport, exportService);
+
+ exportAssociations(model, dir, associationsToExport, exportService);
+
+ if (exportVoyagesByVisitor) {
+
+ exportVoyages(model, dir, exportService);
+ }
+
+ EchoBaseIOUtil.compressZipFile(zipFile, dir);
+ }
+
+ private void exportTables(ExportDbConfiguration model,
+ File dir,
+ List<TableMeta<EchoBaseEntityEnum>> tablesToExport,
+ ExportService exportService) {
+ for (TableMeta<EchoBaseEntityEnum> meta : tablesToExport) {
+
+ model.incrementsProgress();
+
+ File entryFile = new File(dir, meta.getFilename());
+ exportService.exportData(meta, entryFile);
+ }
+ }
+
+ private void exportAssociations(ExportDbConfiguration model,
+ File dir,
+ List<AssociationMeta<EchoBaseEntityEnum>> associationsToExport,
+ ExportService exportService) {
+ for (AssociationMeta<EchoBaseEntityEnum> associationMeta : associationsToExport) {
+
+ model.incrementsProgress();
+
+ File entryFile = new File(dir, associationMeta.getFilename());
+ exportService.exportData(associationMeta, entryFile);
+ }
+ }
+
+ private void exportVoyages(ExportDbConfiguration model,
+ File dir,
+ ExportService exportService) throws IOException {
+
+ EchoBaseDbMeta dbMeta = getDbMeta();
+
+ Map<EchoBaseEntityEnum, TopiaCsvExports.EntityExportContext<EchoBaseEntityEnum>> contexts =
+ TopiaCsvExports.createReplicateEntityVisitorContexts(
+ exportService.getModelFactory(false),
+ dbMeta.getDataTables(),
+ dbMeta.getDataAssociations(),
+ dir);
+
+ ReplicateEntityVisitor visitor = new ReplicateEntityVisitor(
+ dbMeta.getPersistenceHelper(),
+ contexts);
+
+ try {
+ for (String voyageId : model.getVoyageIds()) {
+
+ model.incrementsProgress();
+
+ Voyage voyage = getEchoBasePersistenceContext().getVoyageDAO().findByTopiaId(voyageId);
+ visitor.export(voyage);
+ }
+ } finally {
+
+ // close visitor to close export files
+ visitor.close();
+ }
+ }
+
+ /**
+ * entity visitor to export data to csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+ static class ReplicateEntityVisitor extends ExportEntityVisitor<EchoBaseEntityEnum> {
+
+ protected final Set<String> categoryIds;
+
+ public ReplicateEntityVisitor(TopiaPersistenceHelper<EchoBaseEntityEnum> typeProvider,
+ Map<EchoBaseEntityEnum, TopiaCsvExports.EntityExportContext<EchoBaseEntityEnum>> entityExporters) {
+ super(typeProvider, entityExporters);
+ categoryIds = Sets.newHashSet();
+ }
+
+ @Override
+ public void visit(TopiaEntity entity, String propertyName,
+ Class<?> type, Object value) {
+ if (Result.PROPERTY_CATEGORY.equals(propertyName) &&
+ entity instanceof Result) {
+
+ // export category
+ try {
+ TopiaEntity topiaEntity = (TopiaEntity) value;
+ if (categoryIds.add(topiaEntity.getTopiaId())) {
+ // add this new category
+ topiaEntity.accept(this);
+ }
+
+ } catch (TopiaException e) {
+ if (log.isErrorEnabled()) {
+ log.error("Can not visit entity " + value, e);
+ }
+ }
+ }
+ }
+
+ @Override
+ protected void visitEntityCollection(TopiaEntity entity,
+ String propertyName,
+ Class<?> collectionType,
+ Class<?> type,
+ Collection<?> cValue) {
+ if (Voyage.PROPERTY_POST_CELL.equals(propertyName) && entity instanceof Voyage) {
+
+ // special case, we don not want to visit childs of cells
+ for (Object o : cValue) {
+ Cell cell = (Cell) o;
+
+ cell.acceptWithNoChild(this);
+ }
+ } else {
+ // normal entity collection visit
+ super.visitEntityCollection(entity,
+ propertyName,
+ collectionType,
+ type,
+ cValue);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ categoryIds.clear();
+ super.close();
+ }
+ }
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportdb/ExportService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportdb/ExportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,209 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportdb;
+
+import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import fr.ifremer.echobase.services.service.DbEditorService;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.csv.ExportModel;
+import org.nuiton.decorator.Decorator;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.csv.EntityCsvModel;
+import org.nuiton.topia.persistence.csv.out.EntityAssociationExportModel;
+import org.nuiton.topia.persistence.csv.out.ExportModelFactory;
+import org.nuiton.topia.persistence.csv.out.PrepareDataForExport;
+import org.nuiton.topia.persistence.csv.out.TopiaCsvExports;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.ColumnMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+
+import java.io.File;
+
+/**
+ * To export datas from db to csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class ExportService extends EchoBaseServiceSupport {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(ExportService.class);
+
+ public String exportData(TableMeta<EchoBaseEntityEnum> meta, boolean asSeen) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export " + meta);
+ }
+ String result = TopiaCsvExports.exportData(meta,
+ getModelFactory(asSeen),
+ defaultPrepareDataForExport);
+ return result;
+ }
+
+ public void exportData(TableMeta<EchoBaseEntityEnum> meta, File file) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export " + meta + " to " + file);
+ }
+
+ TopiaCsvExports.exportData(meta,
+ defaultExportFactory,
+ defaultPrepareDataForExport,
+ file);
+
+ getEchoBasePersistenceContext().clear();
+ }
+
+
+ public void exportData(AssociationMeta<EchoBaseEntityEnum> meta, File file) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export " + meta + " to " + file);
+ }
+ TopiaCsvExports.exportData(meta,
+ defaultExportFactory,
+ defaultPrepareDataForExport,
+ file);
+
+ getEchoBasePersistenceContext().clear();
+ }
+
+ public ExportModelFactory<EchoBaseEntityEnum> getModelFactory(boolean asSeen) {
+ ExportModelFactory<EchoBaseEntityEnum> result;
+ if (asSeen) {
+ result = asSeenExportFactory;
+ } else {
+ result = defaultExportFactory;
+ }
+ return result;
+ }
+
+ private ExportModelFactory<EchoBaseEntityEnum> defaultExportFactory = new ExportModelFactory<EchoBaseEntityEnum>() {
+
+ @Override
+ public <E extends TopiaEntity> ExportModel<E> buildForExport(TableMeta<EchoBaseEntityEnum> meta) {
+
+ // normal export add topiaId column
+ EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
+ getConfiguration().getCsvSeparator(),
+ meta,
+ TopiaEntity.PROPERTY_TOPIA_ID
+ );
+
+ for (ColumnMeta columnMeta : meta) {
+ String propertyName = columnMeta.getName();
+ Class<?> type = columnMeta.getType();
+ if (columnMeta.isFK()) {
+
+ Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
+
+
+ // export foreign key value as his topiaId
+ model.addForeignKeyForExport(propertyName, entityType);
+
+ } else {
+ model.addDefaultColumn(propertyName, type);
+ }
+ }
+ return model;
+ }
+
+ @Override
+ public <E extends TopiaEntity> ExportModel<E> buildForExport(AssociationMeta<EchoBaseEntityEnum> associationMeta) {
+ ExportModel<E> model = EntityAssociationExportModel.newExportModel(
+ getConfiguration().getCsvSeparator(),
+ associationMeta
+ );
+ return model;
+ }
+ };
+
+ private ExportModelFactory<EchoBaseEntityEnum> asSeenExportFactory = new ExportModelFactory<EchoBaseEntityEnum>() {
+
+ @Override
+ public <E extends TopiaEntity> ExportModel<E> buildForExport(TableMeta<EchoBaseEntityEnum> meta) {
+
+
+ // no need to have topiaId as first column
+ EntityCsvModel<EchoBaseEntityEnum, E> model = EntityCsvModel.newModel(
+ getConfiguration().getCsvSeparator(),
+ meta
+ );
+
+
+ DecoratorService service = getDecoratorService();
+
+ for (ColumnMeta columnMeta : meta) {
+ String propertyName = columnMeta.getName();
+ Class<?> type = columnMeta.getType();
+ if (columnMeta.isFK()) {
+
+ Class<TopiaEntity> entityType = (Class<TopiaEntity>) type;
+
+ // export decorated foreign key value
+ Decorator<TopiaEntity> decorator =
+ service.getDecorator(getLocale(), entityType, null);
+ model.addDecoratedForeignKeyForExport(propertyName, propertyName, decorator);
+
+ } else {
+ model.addDefaultColumn(propertyName, type);
+ }
+ }
+ return model;
+ }
+
+ @Override
+ public <E extends TopiaEntity> ExportModel<E> buildForExport(AssociationMeta<EchoBaseEntityEnum> associationMeta) {
+ ExportModel<E> model = EntityAssociationExportModel.newExportModel(
+ getConfiguration().getCsvSeparator(),
+ associationMeta
+ );
+ return model;
+ }
+ };
+
+ private PrepareDataForExport<EchoBaseEntityEnum> defaultPrepareDataForExport = new PrepareDataForExport<EchoBaseEntityEnum>() {
+
+ @Override
+ public <E extends TopiaEntity> Iterable<E> prepareData(TableMeta<EchoBaseEntityEnum> tableMeta) {
+ DbEditorService service = getDbEditorService();
+
+ Iterable<E> data = service.iterateOnEntities(tableMeta, null);
+ return data;
+ }
+
+ @Override
+ public <E extends TopiaEntity> Iterable<E> prepareData(AssociationMeta<EchoBaseEntityEnum> associationMeta) {
+ DbEditorService service = getDbEditorService();
+
+ TableMeta<EchoBaseEntityEnum> tableMeta = service.getTableMeta(associationMeta.getSource());
+ Iterable<E> data = service.iterateOnEntities(tableMeta, "size(e." + associationMeta.getName() + ") > 0");
+ return data;
+ }
+ };
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryCsvModel.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryCsvModel.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryCsvModel.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryCsvModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,49 @@
+package fr.ifremer.echobase.services.service.exportquery;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
+import org.nuiton.csv.ext.AbstractExportModel;
+
+import java.util.Map;
+
+/**
+ * Csv model to export sql in {@link ExportQueryService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class ExportQueryCsvModel extends AbstractExportModel<Map<String, Object>> {
+
+ public ExportQueryCsvModel(char separator, String[] columnHeaders) {
+ super(separator);
+ for (String columnHeader : columnHeaders) {
+ newColumnForExport(
+ columnHeader,
+ EchoBaseCsvUtil.TO_STRING_FORMATTER
+ );
+ }
+ }
+
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryInvalidNameException.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryInvalidNameException.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryInvalidNameException.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryInvalidNameException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,35 @@
+package fr.ifremer.echobase.services.service.exportquery;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+/**
+ * To be thrown if a query has not a valid query name.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.4
+ */
+public class ExportQueryInvalidNameException extends Exception {
+
+ private static final long serialVersionUID = 1L;
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNameAlreadyExistException.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNameAlreadyExistException.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNameAlreadyExistException.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNameAlreadyExistException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,35 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportquery;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ExportQueryNameAlreadyExistException extends Exception {
+
+ private static final long serialVersionUID = 1L;
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNotFoundException.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryNotFoundException.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNotFoundException.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryNotFoundException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,35 @@
+package fr.ifremer.echobase.services.service.exportquery;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+/**
+ * When a export query is not found.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.4
+ */
+public class ExportQueryNotFoundException extends Exception {
+
+ private static final long serialVersionUID = 1L;
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryService.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/ExportQueryService.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,245 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportquery;
+
+import com.google.common.base.Charsets;
+import fr.ifremer.echobase.EchoBaseTechnicalException;
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.ExportQueries;
+import fr.ifremer.echobase.entities.ExportQuery;
+import fr.ifremer.echobase.entities.ExportQueryDAO;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import org.apache.commons.lang3.StringUtils;
+import org.nuiton.csv.Export;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.pager.TopiaPagerBean;
+import org.nuiton.util.RecursiveProperties;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service to deal with sql export.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.1
+ */
+public class ExportQueryService extends EchoBaseServiceSupport {
+
+ public ExportQuery getExportQuery(String topiaId) throws ExportQueryNotFoundException {
+
+ ExportQuery exportQuery = getDAO().findByTopiaId(topiaId);
+
+ if (exportQuery == null) {
+ throw new ExportQueryNotFoundException();
+ }
+ ExportQuery entityToSave = newExportQuery();
+ entityToSave.setTopiaId(exportQuery.getTopiaId());
+ entityToSave.setName(exportQuery.getName());
+ entityToSave.setDescription(exportQuery.getDescription());
+ entityToSave.setSqlQuery(exportQuery.getSqlQuery());
+ entityToSave.setLastModifiedDate(exportQuery.getLastModifiedDate());
+ entityToSave.setLastModifiedUser(exportQuery.getLastModifiedUser());
+ return entityToSave;
+ }
+
+
+ public ExportQuery createOrUpdate(ExportQuery exportQuery,
+ EchoBaseUser user) throws ExportQueryNameAlreadyExistException, ExportQueryInvalidNameException {
+ try {
+
+ ExportQueryDAO dao = getDAO();
+
+ // No id, creating new one entity
+ String id = exportQuery.getTopiaId();
+
+ boolean mustCreate = StringUtils.isEmpty(id);
+
+ String queryName = exportQuery.getName();
+
+ if (!ExportQueries.isQueryNameValid(queryName)) {
+
+ // can not accept a non alpha numeric name
+ throw new ExportQueryInvalidNameException();
+ }
+
+ // check query does not already exists with this name
+ if (mustCreate) {
+
+ boolean queryExists = dao.isQueryExists(id, queryName);
+
+ if (queryExists) {
+ throw new ExportQueryNameAlreadyExistException();
+ }
+ }
+
+ ExportQuery entityToSave;
+
+ exportQuery.setLastModifiedDate(newDate());
+ exportQuery.setLastModifiedUser(user.getEmail());
+
+ if (mustCreate) {
+ entityToSave = dao.create(exportQuery);
+ } else {
+ entityToSave = dao.findByTopiaId(id);
+ entityToSave.setName(queryName);
+ entityToSave.setDescription(exportQuery.getDescription());
+ entityToSave.setSqlQuery(exportQuery.getSqlQuery());
+ entityToSave.setLastModifiedDate(exportQuery.getLastModifiedDate());
+ entityToSave.setLastModifiedUser(exportQuery.getLastModifiedUser());
+ }
+
+// dao.update(entityToSave);
+ getEchoBaseInternalPersistenceContext().commitTransaction();
+ return entityToSave;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public void delete(String topiaId) {
+ try {
+ ExportQueryDAO dao = getDAO();
+
+ ExportQuery entityToDelete = dao.findByTopiaId(topiaId);
+ dao.delete(entityToDelete);
+
+ getEchoBaseInternalPersistenceContext().commitTransaction();
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(eee);
+ }
+ }
+
+ public String getSqlQuery(String queryId) throws ExportQueryNotFoundException {
+
+ ExportQuery exportQuery = getExportQuery(queryId);
+
+ String result = getSafeSql(exportQuery.getSqlQuery());
+ return result;
+ }
+
+ protected String getSafeSql(String sql) {
+ RecursiveProperties sqls = new RecursiveProperties();
+ List<ExportQuery> queries = getEchoBaseInternalPersistenceContext().getExportQueryDAO().findAll();
+ for (ExportQuery query : queries) {
+ sqls.put(query.getName(), query.getSqlQuery());
+ }
+ if (!sqls.containsKey(sql)) {
+
+ sqls.put(sql, sql);
+ }
+
+ String result = sqls.getProperty(sql);
+ return result;
+ }
+
+ public void testSql(String sql) throws TopiaException {
+
+ String safeSql = getSafeSql(sql);
+ GenericSQLQuery sqlQuery = new GenericSQLQuery(safeSql, null);
+ getEchoBaseInternalPersistenceContext().findSingleResult(sqlQuery);
+ sqlQuery.getColumnNames();
+ }
+
+ public Map<String, Object>[] executeExportquery(String queryId,
+ TopiaPagerBean pager) throws ExportQueryNotFoundException {
+
+ String sql = getSqlQuery(queryId);
+
+ // get a query to count all rows for the request
+ GenericSQLQuery sqlQuery = new GenericSQLQuery(sql, pager);
+ try {
+ List<Map<String, Object>> result =
+ getEchoBaseInternalPersistenceContext().findMultipleResult(sqlQuery);
+ return result.toArray(new Map[result.size()]);
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not execute sql query", eee);
+ }
+ }
+
+ public String[] getColumnNames(String sql) {
+
+ String limitSql = sql.trim();
+ if (limitSql.endsWith(";")) {
+ limitSql = limitSql.substring(0, limitSql.length() - 1);
+ limitSql += " LIMIT 1";
+ }
+ try {
+ // do a limit query to one result and obtain the column names
+ // from the meta data of the result set
+ GenericSQLQuery sqlQuery = new GenericSQLQuery(limitSql, null);
+ getEchoBaseInternalPersistenceContext().findSingleResult(sqlQuery);
+ String[] result = sqlQuery.getColumnNames();
+ return result;
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not execute query " + limitSql + " for reason " + eee.getCause().getMessage(), eee);
+ } catch (Exception eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not execute query " + limitSql + " for reason " + eee.getMessage(), eee);
+ }
+ }
+
+ public String createCsvFileContent(String queryId) throws ExportQueryNotFoundException {
+
+ String sql = getSqlQuery(queryId);
+
+ GenericSQLQuery sqlQuery = new GenericSQLQuery(sql, null);
+ List<Map<String, Object>> rows;
+ try {
+ rows = getEchoBaseInternalPersistenceContext().findMultipleResult(sqlQuery);
+ } catch (TopiaException eee) {
+ throw new EchoBaseTechnicalException(
+ "Could not execute sql query", eee);
+ }
+ char csvSeparator = getConfiguration().getCsvSeparator();
+ ExportQueryCsvModel csvModel = sqlQuery.generateCsvModel(csvSeparator);
+ Export<Map<String, Object>> exporter = Export.newExport(csvModel, rows);
+ try {
+ String content = exporter.toString(Charsets.UTF_8);
+ return content;
+ } catch (Exception eee) {
+ throw new EchoBaseTechnicalException("Could not export sql", eee);
+ }
+ }
+
+ public ExportQuery newExportQuery() {
+ try {
+ return getDAO().newInstance();
+ } catch (TopiaException e) {
+ throw new EchoBaseTechnicalException(e);
+ }
+ }
+
+ public String processLibreOfficeSqlQuery(String libreOfficeQuery) {
+
+ String result = libreOfficeQuery.replaceAll("\\\"", "");
+ return result;
+ }
+
+ protected ExportQueryDAO getDAO() {
+ return getEchoBaseInternalPersistenceContext().getExportQueryDAO();
+ }
+}
Copied: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/GenericSQLQuery.java (from rev 839, trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/exportquery/GenericSQLQuery.java)
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/GenericSQLQuery.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/exportquery/GenericSQLQuery.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,138 @@
+package fr.ifremer.echobase.services.service.exportquery;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.framework.TopiaSQLQuery;
+import org.nuiton.util.PagerBean;
+import org.nuiton.util.PagerBeanUtil;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.0
+ */
+public class GenericSQLQuery extends TopiaSQLQuery<Map<String, Object>> {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(GenericSQLQuery.class);
+
+ protected String[] columnNames;
+
+ private final String sql;
+
+ private final PagerBean pager;
+
+ public GenericSQLQuery(String sql, PagerBean pager) {
+ this.sql = sql;
+ this.pager = pager;
+ }
+
+ public String[] getColumnNames() {
+ return columnNames;
+ }
+
+ public ExportQueryCsvModel generateCsvModel(char charSeparator) {
+ ExportQueryCsvModel model = new ExportQueryCsvModel(
+ charSeparator,
+ columnNames
+ );
+ return model;
+ }
+
+ public List<Map<String, Object>> getResult(TopiaContext tx) throws TopiaException {
+ List<Map<String, Object>> rows =
+ findMultipleResult(tx);
+ return rows;
+ }
+
+ public void testQuery(TopiaContext tx) throws TopiaException {
+ findSingleResult(tx);
+ }
+
+ public String[] getColumnNames(TopiaContext tx) throws TopiaException {
+ findSingleResult(tx);
+ return columnNames;
+ }
+
+ @Override
+ protected PreparedStatement prepareQuery(Connection connection) throws SQLException {
+ return connection.prepareStatement(
+ sql,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_READ_ONLY
+ );
+ }
+
+ @Override
+ protected void afterExecuteQuery(ResultSet set) throws SQLException {
+ super.afterExecuteQuery(set);
+
+ // obtain columnNames
+ columnNames = getColumnNames(set);
+
+ if (pager != null) {
+
+ // must count rows
+ long nbRows = getNbRows(set);
+ if (log.isInfoEnabled()) {
+ log.info("For request " + sql + ", nb rows = " + nbRows);
+ }
+ pager.setRecords(nbRows);
+ PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
+ }
+ }
+
+ @Override
+ protected Map<String, Object> prepareResult(ResultSet set) throws SQLException {
+
+ if (pager != null) {
+
+ // get row number (getRow() begins at 1)
+ int rowNumber = set.getRow() - 1;
+ if (rowNumber < pager.getRecordStartIndex() ||
+ rowNumber >= pager.getRecordEndIndex()) {
+
+ // out of pager bound, by returning null
+ // result will not be take in account
+ return null;
+ }
+ }
+
+ Map<String, Object> result = getRowAsMap(columnNames, set);
+ return result;
+ }
+
+}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AbstractImportConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/AbstractImportConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AbstractImportConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/AbstractImportDataService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
@@ -115,11 +115,16 @@
String result = computeResultAndLogBookEntry(configuration, user);
// do commit
- commitTransaction("Could not execute import " +
- getImportLabel(configuration));
+ getEchoBasePersistenceContext().commitTransaction();
- updatePostgisTable();
+ // revoke spatial data memory cache
+ getSpatialDataCache().onVoyageChanged(
+ serviceContext.getWorkgingDbUrl(),
+ configuration.getVoyageId());
+ // update sql spatial data
+ getSpatialService().updatePostgisTable();
+
s0 = TIME_LOG.log(s0, "postgis update");
TIME_LOG.log(s0, "importCommited");
@@ -173,13 +178,13 @@
}
String importText = buffer.toString().trim();
- ImportLog importLog = create(getDAO(ImportLog.class),
- ImportLog.PROPERTY_VOYAGE_ID, configuration.getVoyageId(),
- ImportLog.PROPERTY_IMPORT_TYPE, configuration.getImportType(),
- ImportLog.PROPERTY_IMPORT_USER, importUser,
- ImportLog.PROPERTY_IMPORT_DATE, importDate,
- ImportLog.PROPERTY_IMPORT_TEXT, importText,
- ImportLog.PROPERTY_IMPORT_ID, importIds
+ ImportLog importLog = getEchoBasePersistenceContext().getImportLogDAO().create(
+ ImportLog.PROPERTY_VOYAGE_ID, configuration.getVoyageId(),
+ ImportLog.PROPERTY_IMPORT_TYPE, configuration.getImportType(),
+ ImportLog.PROPERTY_IMPORT_USER, importUser,
+ ImportLog.PROPERTY_IMPORT_DATE, importDate,
+ ImportLog.PROPERTY_IMPORT_TEXT, importText,
+ ImportLog.PROPERTY_IMPORT_ID, importIds
);
return importLog;
}
@@ -196,12 +201,12 @@
String result = importLog.getImportText();
- create(getDAO(EntityModificationLog.class),
- EntityModificationLog.PROPERTY_ENTITY_TYPE, "Import",
- EntityModificationLog.PROPERTY_ENTITY_ID, importType,
- EntityModificationLog.PROPERTY_MODIFICATION_USER, importUser,
- EntityModificationLog.PROPERTY_MODIFICATION_DATE, importDate,
- EntityModificationLog.PROPERTY_MODIFICATION_TEXT, result
+ getEchoBasePersistenceContext().getEntityModificationLogDAO().create(
+ EntityModificationLog.PROPERTY_ENTITY_TYPE, "Import",
+ EntityModificationLog.PROPERTY_ENTITY_ID, importType,
+ EntityModificationLog.PROPERTY_MODIFICATION_USER, importUser,
+ EntityModificationLog.PROPERTY_MODIFICATION_DATE, importDate,
+ EntityModificationLog.PROPERTY_MODIFICATION_TEXT, result
);
return result;
}
@@ -239,7 +244,7 @@
protected <E extends TopiaEntity, K> Map<K, E> getEntitiesMap(
Class<E> entityType,
Function<E, K> function) {
- List<E> allVoyages = getEntities(entityType);
+ List<E> allVoyages = getEchoBasePersistenceContext().getDAO(entityType).findAll();
Map<K, E> voyageMap = Maps.uniqueIndex(
allVoyages, function);
return voyageMap;
@@ -255,35 +260,35 @@
}
}
- protected <E extends TopiaEntity> E create(TopiaDAO<E> dao) {
- try {
- E result = dao.create();
- return result;
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not create entity", e);
- }
- }
+// protected <E extends TopiaEntity> E create(TopiaDAO<E> dao) {
+// try {
+// E result = dao.create();
+// return result;
+// } catch (TopiaException e) {
+// throw new EchoBaseTechnicalException("Could not create entity", e);
+// }
+// }
- protected <E extends TopiaEntity> E create(TopiaDAO<E> dao, E entity) {
- try {
- E result = dao.create(entity);
- return result;
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not create entity", e);
- }
- }
+// protected <E extends TopiaEntity> E create(TopiaDAO<E> dao, E entity) {
+// try {
+// E result = dao.create(entity);
+// return result;
+// } catch (TopiaException e) {
+// throw new EchoBaseTechnicalException("Could not create entity", e);
+// }
+// }
- protected <E extends TopiaEntity> E findByProperties(TopiaDAO<E> dao,
- String propertyName,
- Object value,
- Object... others) {
- try {
- E result = dao.findByProperties(propertyName, value, others);
- return result;
- } catch (TopiaException e) {
- throw new EchoBaseTechnicalException("Could not obtain query db", e);
- }
- }
+// protected <E extends TopiaEntity> E findByProperties(TopiaDAO<E> dao,
+// String propertyName,
+// Object value,
+// Object... others) {
+// try {
+// E result = dao.findByProperties(propertyName, value, others);
+// return result;
+// } catch (TopiaException e) {
+// throw new EchoBaseTechnicalException("Could not obtain query db", e);
+// }
+// }
protected String getImportMessage(M configuration, InputFile inputFile) {
String message = l_(getLocale(), "echobase.importLabel.withFile",
@@ -298,7 +303,7 @@
if (rowNumber % 1000 == 0) {
// flush each 1000 imported rows
String message = getImportMessage(configuration, inputFile);
- flushTransaction("Could not flush transaction " + message);
+ getEchoBasePersistenceContext().flush();
}
}
@@ -323,8 +328,7 @@
// try to find it in db
- category = findByProperties(
- speciesCategoryDAO,
+ category = speciesCategoryDAO.findByProperties(
SpeciesCategory.PROPERTY_SPECIES, species,
SpeciesCategory.PROPERTY_AGE_CATEGORY, ageCategory,
SpeciesCategory.PROPERTY_SIZE_CATEGORY, sizeCategory,
@@ -335,11 +339,11 @@
// not found in db, create it
- category = create(speciesCategoryDAO,
- SpeciesCategory.PROPERTY_SPECIES, species,
- SpeciesCategory.PROPERTY_SIZE_CATEGORY, sizeCategory,
- SpeciesCategory.PROPERTY_AGE_CATEGORY, ageCategory,
- SpeciesCategory.PROPERTY_SEX_CATEGORY, sexCategory
+ category = speciesCategoryDAO.create(
+ SpeciesCategory.PROPERTY_SPECIES, species,
+ SpeciesCategory.PROPERTY_SIZE_CATEGORY, sizeCategory,
+ SpeciesCategory.PROPERTY_AGE_CATEGORY, ageCategory,
+ SpeciesCategory.PROPERTY_SEX_CATEGORY, sexCategory
);
importResult.incrementsNumberCreated(EchoBaseEntityEnum.SpeciesCategory);
}
@@ -392,8 +396,7 @@
// try to find it in db
- category = findByProperties(
- categoryDAO,
+ category = categoryDAO.findByProperties(
Category.PROPERTY_ECHOTYPE, echotype,
Category.PROPERTY_SPECIES_CATEGORY, speciesCategory
);
@@ -401,8 +404,7 @@
if (category == null) {
// not found in db, create it
- category = create(
- categoryDAO,
+ category = categoryDAO.create(
Category.PROPERTY_ECHOTYPE, echotype,
Category.PROPERTY_SPECIES_CATEGORY, speciesCategory
);
@@ -455,9 +457,8 @@
DataQuality dataQuality,
EchoBaseCsvFileImportResult importResult) {
- Data data = create(dao,
- Data.PROPERTY_DATA_METADATA, dataMetaData,
- Data.PROPERTY_DATA_VALUE, dataValue);
+ Data data = dao.create(Data.PROPERTY_DATA_METADATA, dataMetaData,
+ Data.PROPERTY_DATA_VALUE, dataValue);
cell.addData(data);
cell.setDataQuality(dataQuality);
@@ -479,7 +480,7 @@
result.setCategory(category);
result.setResultLabel(resultLabel);
- Result resultCreated = create(dao, result);
+ Result resultCreated = dao.create(result);
cell.addResult(resultCreated);
if (collecIds) {
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AcousticImportConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/AcousticImportConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AcousticImportConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.io.InputFile;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AcousticImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/AcousticImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/AcousticImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
@@ -33,7 +33,6 @@
import fr.ifremer.echobase.entities.EchoBaseUser;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.CellDAO;
-import fr.ifremer.echobase.entities.data.Data;
import fr.ifremer.echobase.entities.data.DataAcquisition;
import fr.ifremer.echobase.entities.data.DataAcquisitionDAO;
import fr.ifremer.echobase.entities.data.DataDAO;
@@ -48,8 +47,8 @@
import fr.ifremer.echobase.entities.references.DataQuality;
import fr.ifremer.echobase.entities.references.Vessel;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.AcousticImportModel;
-import fr.ifremer.echobase.services.importdata.csv.AcousticImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.AcousticImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.AcousticImportRow;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -85,19 +84,19 @@
EchoBaseUser user) throws ImportException {
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
- configuration.getVoyageId());
+ Voyage voyage = getEchoBasePersistenceContext().getVoyageDAO().findByTopiaId(
+ configuration.getVoyageId());
// get selected vessel
- Vessel vessel = getEntityById(Vessel.class,
- configuration.getVesselId());
+ Vessel vessel = getEchoBasePersistenceContext().getVesselDAO().findByTopiaId(
+ configuration.getVesselId());
- CellType esduCellType = getEntityByProperty(
- CellType.class, CellType.PROPERTY_ID, "Esdu");
+ CellType esduCellType = getEchoBasePersistenceContext().getCellTypeDAO().findByProperty(
+ CellType.PROPERTY_ID, "Esdu");
Preconditions.checkNotNull(esduCellType);
- CellType elementaryCellType = getEntityByProperty(
- CellType.class, CellType.PROPERTY_ID, "Elementary");
+ CellType elementaryCellType = getEchoBasePersistenceContext().getCellTypeDAO().findByProperty(
+ CellType.PROPERTY_ID, "Elementary");
Preconditions.checkNotNull(elementaryCellType);
EchoBaseCsvFileImportResult importResult =
@@ -163,11 +162,11 @@
getCsvSeparator(), instrumentsById, dataQualityMap);
DataAcquisitionDAO dataAcquisitionDAO =
- getDAO(DataAcquisition.class, DataAcquisitionDAO.class);
+ getEchoBasePersistenceContext().getDataAcquisitionDAO();
DataProcessingDAO dataProcessingDAO =
- getDAO(DataProcessing.class, DataProcessingDAO.class);
- CellDAO cellDAO = getDAO(Cell.class, CellDAO.class);
- DataDAO dataDAO = getDAO(Data.class, DataDAO.class);
+ getEchoBasePersistenceContext().getDataProcessingDAO();
+ CellDAO cellDAO = getEchoBasePersistenceContext().getCellDAO();
+ DataDAO dataDAO = getEchoBasePersistenceContext().getDataDAO();
boolean addDataAcquisition = configuration.isAddDataAcquisition();
@@ -354,9 +353,9 @@
// this is a esdu cell row
// create esdu cell
- Cell esduCell = create(cellDAO,
- Cell.PROPERTY_CELL_TYPE, esduCellType,
- Cell.PROPERTY_NAME, esduCellId
+ Cell esduCell = cellDAO.create(
+ Cell.PROPERTY_CELL_TYPE, esduCellType,
+ Cell.PROPERTY_NAME, esduCellId
);
esduCell.setDataQuality(dataQuality);
@@ -403,9 +402,9 @@
}
// create the elementary cell
- elementaryCell = create(cellDAO,
- Cell.PROPERTY_CELL_TYPE, elementaryCellType,
- Cell.PROPERTY_NAME, elementaryCellId
+ elementaryCell = cellDAO.create(
+ Cell.PROPERTY_CELL_TYPE, elementaryCellType,
+ Cell.PROPERTY_NAME, elementaryCellId
);
elementaryCell.setDataQuality(dataQuality);
@@ -456,8 +455,8 @@
// create Depth data
dataValue = row.getEsduCellDataDepth();
- createCellData(dao, cell, dataMetadatas, "DepthRefSurface" + suffix,
- dataValue, dataQuality, importResult);
+ createCellData(dao, cell, dataMetadatas, "DepthRefSurface" + suffix,
+ dataValue, dataQuality, importResult);
// create Time Start data
dataValue = cellDateFormat.format(row.getCellDateStart());
@@ -605,8 +604,7 @@
String loggedDataDatatype = configuration.getLoggedDataDatatype();
String pingDutyCycle = configuration.getPingDutyCycle();
- DataAcquisition dataAcquisition = create(
- dataAcquisitionDAO,
+ DataAcquisition dataAcquisition = dataAcquisitionDAO.create(
DataAcquisition.PROPERTY_ACOUSTIC_INSTRUMENT, instrument
);
@@ -666,8 +664,7 @@
String acousticDensityUnit = configuration.getAcousticDensityUnit();
String notes = configuration.getNotes();
- DataProcessing dataProcessing = create(
- dataProcessingDAO,
+ DataProcessing dataProcessing = dataProcessingDAO.create(
DataProcessing.PROPERTY_ID, id,
DataProcessing.PROPERTY_PROCESSING_TEMPLATE, processingTemplate
);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CatchesImportConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CatchesImportConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CatchesImportConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.io.InputFile;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CatchesImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CatchesImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CatchesImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Preconditions;
import com.google.common.collect.Collections2;
@@ -47,12 +47,12 @@
import fr.ifremer.echobase.entities.references.SpeciesCategory;
import fr.ifremer.echobase.entities.references.SpeciesCategoryDAO;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.BiometrySampleImportModel;
-import fr.ifremer.echobase.services.importdata.csv.BiometrySampleImportRow;
-import fr.ifremer.echobase.services.importdata.csv.SubSampleImportModel;
-import fr.ifremer.echobase.services.importdata.csv.SubSampleImportRow;
-import fr.ifremer.echobase.services.importdata.csv.TotalSampleImportModel;
-import fr.ifremer.echobase.services.importdata.csv.TotalSampleImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.BiometrySampleImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.BiometrySampleImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.SubSampleImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.SubSampleImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.TotalSampleImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.TotalSampleImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -81,7 +81,7 @@
protected void startImport(CatchesImportConfiguration configuration,
EchoBaseUser user) throws ImportException {
- Voyage voyage = getEntityById(Voyage.class,
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
configuration.getVoyageId());
// get all operation for this voyage and this vessel
@@ -171,24 +171,24 @@
sizeCategoryMap
);
- SampleDAO sampleDAO = getDAO(Sample.class, SampleDAO.class);
- SampleDataDAO sampleDataDAO = getDAO(SampleData.class, SampleDataDAO.class);
- SampleTypeDAO sampleTypeDAO = getDAO(SampleType.class, SampleTypeDAO.class);
- SampleDataTypeDAO sampleDataTypeDAO = getDAO(SampleDataType.class, SampleDataTypeDAO.class);
- SpeciesCategoryDAO speciesCategoryDAO = getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ SampleDAO sampleDAO = getEchoBasePersistenceContext().getSampleDAO();
+ SampleDataDAO sampleDataDAO = getEchoBasePersistenceContext().getSampleDataDAO();
+ SampleTypeDAO sampleTypeDAO = getEchoBasePersistenceContext().getSampleTypeDAO();
+ SampleDataTypeDAO sampleDataTypeDAO = getEchoBasePersistenceContext().getSampleDataTypeDAO();
+ SpeciesCategoryDAO speciesCategoryDAO = getEchoBasePersistenceContext().getSpeciesCategoryDAO();
- SampleType sampleTypeTotal = findByProperties(sampleTypeDAO, SampleType.PROPERTY_NAME, SampleTypeImpl.TOTAL_SAMPLE_TYPE);
+ SampleType sampleTypeTotal = sampleTypeDAO.findByProperties(SampleType.PROPERTY_NAME, SampleTypeImpl.TOTAL_SAMPLE_TYPE);
Preconditions.checkNotNull(sampleTypeTotal);
- SampleType sampleTypeUnsorted = findByProperties(sampleTypeDAO, SampleType.PROPERTY_NAME, SampleTypeImpl.UNSORTED_SAMPLE_TYPE);
+ SampleType sampleTypeUnsorted = sampleTypeDAO.findByProperties(SampleType.PROPERTY_NAME, SampleTypeImpl.UNSORTED_SAMPLE_TYPE);
Preconditions.checkNotNull(sampleTypeUnsorted);
- SampleType sampleTypeSorted = findByProperties(sampleTypeDAO, SampleType.PROPERTY_NAME, SampleTypeImpl.SORTED_SAMPLE_TYPE);
+ SampleType sampleTypeSorted = sampleTypeDAO.findByProperties(SampleType.PROPERTY_NAME, SampleTypeImpl.SORTED_SAMPLE_TYPE);
Preconditions.checkNotNull(sampleTypeSorted);
- SampleDataType sampleDataTypeMeanLength = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "MeanLengthcm");
+ SampleDataType sampleDataTypeMeanLength = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "MeanLengthcm");
Preconditions.checkNotNull(sampleDataTypeMeanLength);
- SampleDataType sampleDataTypeMeanWeight = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "MeanWeightg");
+ SampleDataType sampleDataTypeMeanWeight = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "MeanWeightg");
Preconditions.checkNotNull(sampleDataTypeMeanWeight);
- SampleDataType sampleDataTypeNoPerKg = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "NoPerKg");
+ SampleDataType sampleDataTypeNoPerKg = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "NoPerKg");
Preconditions.checkNotNull(sampleDataTypeNoPerKg);
Reader reader = getInputFileReader(inputFile);
@@ -332,22 +332,22 @@
sizeCategoryMap,
sexCategoryMap);
- SampleDAO sampleDAO = getDAO(Sample.class, SampleDAO.class);
- SampleDataDAO sampleDataDAO = getDAO(SampleData.class, SampleDataDAO.class);
- SampleTypeDAO sampleTypeDAO = getDAO(SampleType.class, SampleTypeDAO.class);
- SampleDataTypeDAO sampleDataTypeDAO = getDAO(SampleDataType.class, SampleDataTypeDAO.class);
- SpeciesCategoryDAO speciesCategoryDAO = getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ SampleDAO sampleDAO = getEchoBasePersistenceContext().getSampleDAO();
+ SampleDataDAO sampleDataDAO = getEchoBasePersistenceContext().getSampleDataDAO();
+ SampleTypeDAO sampleTypeDAO = getEchoBasePersistenceContext().getSampleTypeDAO();
+ SampleDataTypeDAO sampleDataTypeDAO = getEchoBasePersistenceContext().getSampleDataTypeDAO();
+ SpeciesCategoryDAO speciesCategoryDAO = getEchoBasePersistenceContext().getSpeciesCategoryDAO();
- SampleType sampleTypeSubsample = findByProperties(sampleTypeDAO, SampleType.PROPERTY_NAME, SampleTypeImpl.SUB_SAMPLE_TYPE);
+ SampleType sampleTypeSubsample = sampleTypeDAO.findByProperties(SampleType.PROPERTY_NAME, SampleTypeImpl.SUB_SAMPLE_TYPE);
Preconditions.checkNotNull(sampleTypeSubsample);
- SampleDataType sampleDataTypeNumberAtLength = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "NumberAtLength");
+ SampleDataType sampleDataTypeNumberAtLength = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "NumberAtLength");
Preconditions.checkNotNull(sampleDataTypeNumberAtLength);
- SampleDataType sampleDataTypeNumberAtLength05cm = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "LTcm0.5");
+ SampleDataType sampleDataTypeNumberAtLength05cm = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "LTcm0.5");
Preconditions.checkNotNull(sampleDataTypeNumberAtLength05cm);
- SampleDataType sampleDataTypeNumberAtLength1cm = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "LTcm1");
+ SampleDataType sampleDataTypeNumberAtLength1cm = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "LTcm1");
Preconditions.checkNotNull(sampleDataTypeNumberAtLength1cm);
- SampleDataType sampleDataTypeWeightAtLength = findByProperties(sampleDataTypeDAO, SampleDataType.PROPERTY_NAME, "WeightAtLengthkg");
+ SampleDataType sampleDataTypeWeightAtLength = sampleDataTypeDAO.findByProperties(SampleDataType.PROPERTY_NAME, "WeightAtLengthkg");
Preconditions.checkNotNull(sampleDataTypeWeightAtLength);
Reader reader = getInputFileReader(inputFile);
@@ -473,12 +473,12 @@
speciesMap,
sampleDataTypeMap);
- SampleDAO sampleDAO = getDAO(Sample.class, SampleDAO.class);
- SampleDataDAO sampleDataDAO = getDAO(SampleData.class, SampleDataDAO.class);
- SampleTypeDAO sampleTypeDAO = getDAO(SampleType.class, SampleTypeDAO.class);
- SpeciesCategoryDAO speciesCategoryDAO = getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ SampleDAO sampleDAO = getEchoBasePersistenceContext().getSampleDAO();
+ SampleDataDAO sampleDataDAO = getEchoBasePersistenceContext().getSampleDataDAO();
+ SampleTypeDAO sampleTypeDAO = getEchoBasePersistenceContext().getSampleTypeDAO();
+ SpeciesCategoryDAO speciesCategoryDAO = getEchoBasePersistenceContext().getSpeciesCategoryDAO();
- SampleType sampleTypeIndividual = findByProperties(sampleTypeDAO, SampleType.PROPERTY_NAME, SampleTypeImpl.INDIVIDUAL_SAMPLE_TYPE);
+ SampleType sampleTypeIndividual = sampleTypeDAO.findByProperties(SampleType.PROPERTY_NAME, SampleTypeImpl.INDIVIDUAL_SAMPLE_TYPE);
Preconditions.checkNotNull(sampleTypeIndividual);
Map<String, Sample> samples = Maps.newTreeMap();
@@ -538,7 +538,7 @@
SampleData sampleData = row.getSampleData();
- SampleData sampleDataCreated = create(sampleDataDAO, sampleData);
+ SampleData sampleDataCreated = sampleDataDAO.create(sampleData);
sample.addSampleData(sampleDataCreated);
importResult.incrementsNumberCreated(EchoBaseEntityEnum.SampleData);
}
@@ -557,7 +557,7 @@
EchoBaseCsvFileImportResult importResult) {
Preconditions.checkNotNull(operation);
Preconditions.checkNotNull(sample);
- Sample result = create(dao, sample);
+ Sample result = dao.create(sample);
operation.addSample(result);
// collect ids
@@ -571,8 +571,7 @@
float value,
Sample sample,
EchoBaseCsvFileImportResult importResult) {
- SampleData sampleData = create(
- dao,
+ SampleData sampleData = dao.create(
SampleData.PROPERTY_SAMPLE_DATA_TYPE, sampleDataType,
SampleData.PROPERTY_DATA_VALUE, value,
SampleData.PROPERTY_DATA_LABEL, label
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CellPositionReference.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CellPositionReference.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CellPositionReference.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.I18nAble;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CommonAllImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.EchoBaseFunctions;
import fr.ifremer.echobase.entities.EchoBaseUser;
@@ -47,13 +47,13 @@
EchoBaseCsvFileImportResult importResult;
- importResult = getService(CommonVoyageImportService.class).importFile(configuration);
+ importResult = newService(CommonVoyageImportService.class).importFile(configuration);
configuration.addResult(importResult);
- importResult = getService(CommonTransitImportService.class).importFile(configuration, false);
+ importResult = newService(CommonTransitImportService.class).importFile(configuration, false);
configuration.addResult(importResult);
- importResult = getService(CommonTransectImportService.class).importFile(vesselMap, configuration, false);
+ importResult = newService(CommonTransectImportService.class).importFile(vesselMap, configuration, false);
configuration.addResult(importResult);
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonImportConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CommonImportConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonImportConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.io.InputFile;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CommonImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Preconditions;
import fr.ifremer.echobase.EchoBaseTechnicalException;
@@ -50,19 +50,19 @@
switch (importMode) {
case COMMON_ALL:
- service = getService(CommonAllImportService.class);
+ service = newService(CommonAllImportService.class);
break;
case COMMON_VOYAGE:
- service = getService(CommonVoyageImportService.class);
+ service = newService(CommonVoyageImportService.class);
break;
case COMMON_TRANSIT:
- service = getService(CommonTransitImportService.class);
+ service = newService(CommonTransitImportService.class);
break;
case COMMON_TRANSECT:
- service = getService(CommonTransectImportService.class);
+ service = newService(CommonTransectImportService.class);
break;
default:
@@ -77,7 +77,7 @@
Preconditions.checkNotNull(mission);
try {
- MissionDAO dao = getDAO(Mission.class, MissionDAO.class);
+ MissionDAO dao = getEchoBasePersistenceContext().getMissionDAO();
// check mission name is unique
boolean exists = dao.existByProperties(Mission.PROPERTY_NAME,
@@ -86,8 +86,8 @@
if (exists) {
throw new MissionNameAlreadyExistException();
}
- Mission result = create(dao, mission);
- commitTransaction("Could not create mission " + mission.getName());
+ Mission result = getEchoBasePersistenceContext().getMissionDAO().create(mission);
+ getEchoBasePersistenceContext().commitTransaction();
return result;
} catch (TopiaException eee) {
throw new EchoBaseTechnicalException(eee);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CommonTransectImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.collect.Maps;
import fr.ifremer.echobase.EchoBaseFunctions;
@@ -33,8 +33,8 @@
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.Vessel;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.TransectImportModel;
-import fr.ifremer.echobase.services.importdata.csv.TransectImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.TransectImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.TransectImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -89,7 +89,7 @@
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
// get voyage
- Voyage voyage = getEntityById(Voyage.class,
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
configuration.getVoyageId());
// restrict voyage to use to this voyage
@@ -107,7 +107,7 @@
voyageMap,
vesselMap);
- TransectDAO dao = getDAO(Transect.class, TransectDAO.class);
+ TransectDAO dao = getEchoBasePersistenceContext().getTransectDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -137,7 +137,7 @@
geospatialVerticalPositive);
transect.setBinUnitsPingAxis(binUnitsPingAxis);
- Transect createdTransect = create(dao, transect);
+ Transect createdTransect = dao.create(transect);
transit.addTransect(createdTransect);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CommonTransitImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
/*
* #%L
@@ -31,8 +31,8 @@
import fr.ifremer.echobase.entities.data.TransitDAO;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.TransitImportModel;
-import fr.ifremer.echobase.services.importdata.csv.TransitImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.TransitImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.TransitImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -77,7 +77,7 @@
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
// get voyage
- Voyage voyage = getEntityById(Voyage.class,
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
configuration.getVoyageId());
// restrict voyage to use to this voyage
@@ -89,7 +89,7 @@
TransitImportModel csvModel =
new TransitImportModel(getCsvSeparator(), voyageMap);
- TransitDAO dao = getDAO(Transit.class, TransitDAO.class);
+ TransitDAO dao = getEchoBasePersistenceContext().getTransitDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -104,7 +104,7 @@
transit.setRelatedActivity(relatedActivity);
- Transit createdTransit = create(dao, transit);
+ Transit createdTransit = dao.create(transit);
voyage.addTransit(createdTransit);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/CommonVoyageImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
/*
* #%L
@@ -30,7 +30,7 @@
import fr.ifremer.echobase.entities.references.AreaOfOperation;
import fr.ifremer.echobase.entities.references.Mission;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.VoyageImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.VoyageImportModel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -75,10 +75,10 @@
inputFile.getFileName());
}
- Mission mission = getEntityById(Mission.class,
+ Mission mission = getEchoBasePersistenceContext().getEntityById(Mission.class,
configuration.getMissionId());
AreaOfOperation areaOfOperation =
- getEntityById(AreaOfOperation.class,
+ getEchoBasePersistenceContext().getEntityById(AreaOfOperation.class,
configuration.getAreaOfOperationId());
EchoBaseCsvFileImportResult result = newImportResult(inputFile);
@@ -86,7 +86,7 @@
String voyageDescription = configuration.getVoyageDescription();
String datum = configuration.getDatum();
- VoyageDAO dao = getDAO(Voyage.class, VoyageDAO.class);
+ VoyageDAO dao = getEchoBasePersistenceContext().getVoyageDAO();
ImportModel<Voyage> csvModel = new VoyageImportModel(getCsvSeparator());
@@ -106,7 +106,7 @@
voyage.setDescription(voyageDescription);
voyage.setDatum(datum);
- Voyage createdVoyage = create(dao, voyage);
+ Voyage createdVoyage = dao.create(voyage);
if (newVoyage == null) {
newVoyage = createdVoyage;
} else {
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/EchoBaseCsvFileImportResult.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/EchoBaseCsvFileImportResult.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/EchoBaseCsvFileImportResult.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ImportException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ImportException.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ImportException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.io.InputFile;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/MissionNameAlreadyExistException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/MissionNameAlreadyExistException.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/MissionNameAlreadyExistException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
/**
* TODO
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/OperationImportConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/OperationImportConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/OperationImportConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.io.InputFile;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/OperationImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/OperationImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/OperationImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.collect.Maps;
import fr.ifremer.echobase.EchoBaseFunctions;
@@ -42,12 +42,12 @@
import fr.ifremer.echobase.entities.references.OperationMetadata;
import fr.ifremer.echobase.entities.references.Vessel;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.GearMetadataValueImportModel;
-import fr.ifremer.echobase.services.importdata.csv.GearMetadataValueImportRow;
-import fr.ifremer.echobase.services.importdata.csv.OperationImportModel;
-import fr.ifremer.echobase.services.importdata.csv.OperationImportRow;
-import fr.ifremer.echobase.services.importdata.csv.OperationMetadataValueImportModel;
-import fr.ifremer.echobase.services.importdata.csv.OperationMetadataValueImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.GearMetadataValueImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.GearMetadataValueImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.OperationImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.OperationImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.OperationMetadataValueImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.OperationMetadataValueImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -76,7 +76,7 @@
EchoBaseUser user) throws ImportException {
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
configuration.getVoyageId());
// get usable vessels from the voyage by their name
@@ -139,7 +139,7 @@
gearMap,
depthStratumMap);
- OperationDAO dao = getDAO(Operation.class, OperationDAO.class);
+ OperationDAO dao = getEchoBasePersistenceContext().getOperationDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -162,7 +162,7 @@
Transect transect = transit.getTransect(vessel);
- Operation createdOperation = create(dao, operation);
+ Operation createdOperation = dao.create(operation);
// collect ids
importResult.addId(EchoBaseEntityEnum.Operation,
@@ -203,9 +203,8 @@
operationMetadatasByName,
operationMap);
- OperationMetadataValueDAO dao = getDAO(
- OperationMetadataValue.class,
- OperationMetadataValueDAO.class);
+ OperationMetadataValueDAO dao =
+ getEchoBasePersistenceContext().getOperationMetadataValueDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -221,8 +220,8 @@
OperationMetadataValue operationMetadataValueToCreate =
row.getOperationMetadataValue();
- OperationMetadataValue operationMetadataValue = create(
- dao, operationMetadataValueToCreate);
+ OperationMetadataValue operationMetadataValue = dao.create(
+ operationMetadataValueToCreate);
operation.addOperationMetadataValue(operationMetadataValue);
importResult.incrementsNumberCreated(EchoBaseEntityEnum.OperationMetadataValue);
@@ -261,8 +260,8 @@
gearMap,
operationMap);
- GearMetadataValueDAO dao = getDAO(GearMetadataValue.class,
- GearMetadataValueDAO.class);
+ GearMetadataValueDAO dao =
+ getEchoBasePersistenceContext().getGearMetadataValueDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -278,8 +277,8 @@
GearMetadataValue gearMetadataValuetoCreate =
row.getGearMetadataValue();
- GearMetadataValue gearMetadataValue = create(
- dao, gearMetadataValuetoCreate);
+ GearMetadataValue gearMetadataValue = dao.create(
+ gearMetadataValuetoCreate);
operation.addGearMetadataValue(gearMetadataValue);
importResult.incrementsNumberCreated(EchoBaseEntityEnum.GearMetadataValue);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsEsduCellImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.collect.Maps;
import fr.ifremer.echobase.EchoBaseFunctions;
@@ -32,7 +32,6 @@
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.DataProcessing;
import fr.ifremer.echobase.entities.data.Echotype;
-import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.ResultDAO;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.AgeCategory;
@@ -42,17 +41,16 @@
import fr.ifremer.echobase.entities.references.SizeCategory;
import fr.ifremer.echobase.entities.references.SizeCategoryDAO;
import fr.ifremer.echobase.entities.references.Species;
-import fr.ifremer.echobase.entities.references.SpeciesCategory;
import fr.ifremer.echobase.entities.references.SpeciesCategoryDAO;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultByEchotypeAndSpeciesCategoryImportModel;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultByEchotypeAndSpeciesCategoryImportRow;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultByEchotypeImportModel;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultByEchotypeImportRow;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultBySpeciesAndAgeCategoryImportModel;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultBySpeciesAndAgeCategoryImportRow;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultBySpeciesAndSizeCategoryImportModel;
-import fr.ifremer.echobase.services.importdata.csv.EsduResultBySpeciesAndSizeCategoryImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultByEchotypeAndSpeciesCategoryImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultByEchotypeAndSpeciesCategoryImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultByEchotypeImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultByEchotypeImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultBySpeciesAndAgeCategoryImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultBySpeciesAndAgeCategoryImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultBySpeciesAndSizeCategoryImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.EsduResultBySpeciesAndSizeCategoryImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -100,11 +98,11 @@
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
configuration.getVoyageId());
// get selected dataProcessing
- DataProcessing dataProcessing = getEntityById(
+ DataProcessing dataProcessing = getEchoBasePersistenceContext().getEntityById(
DataProcessing.class,
configuration.getDataProcessingId());
@@ -220,8 +218,8 @@
metas,
dataQualityMap);
- CategoryDAO categoryDAO = (CategoryDAO) getDAO(Category.class);
- ResultDAO dao = getDAO(Result.class, ResultDAO.class);
+ CategoryDAO categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ ResultDAO dao = getEchoBasePersistenceContext().getResultDAO();
String resultLabel = configuration.getResultLabel();
@@ -285,11 +283,12 @@
header);
SpeciesCategoryDAO speciesCategoryDAO =
- getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
- CategoryDAO categoryDAO = getDAO(Category.class, CategoryDAO.class);
+ CategoryDAO categoryDAO =
+ getEchoBasePersistenceContext().getCategoryDAO();
- ResultDAO dao = getDAO(Result.class, ResultDAO.class);
+ ResultDAO dao = getEchoBasePersistenceContext().getResultDAO();
EsduResultByEchotypeAndSpeciesCategoryImportModel csvModel = new EsduResultByEchotypeAndSpeciesCategoryImportModel(
getCsvSeparator(),
@@ -365,12 +364,11 @@
header);
SpeciesCategoryDAO speciesCategoryDAO =
- getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
SizeCategoryDAO sizeCategoryDAO =
- getDAO(SizeCategory.class, SizeCategoryDAO.class);
+ getEchoBasePersistenceContext().getSizeCategoryDAO();
- ResultDAO dao = getDAO(Result.class, ResultDAO.class);
EsduResultBySpeciesAndSizeCategoryImportModel csvModel = new EsduResultBySpeciesAndSizeCategoryImportModel(
getCsvSeparator(),
@@ -381,7 +379,8 @@
metas,
dataQualityMap);
- CategoryDAO categoryDAO = (CategoryDAO) getDAO(Category.class);
+ CategoryDAO categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ ResultDAO dao = getEchoBasePersistenceContext().getResultDAO();
String resultLabel = configuration.getResultLabel();
@@ -406,8 +405,7 @@
if (sizeCategory == null) {
// create a new sizeCategory
- sizeCategory = create(
- sizeCategoryDAO,
+ sizeCategory = sizeCategoryDAO.create(
SizeCategory.PROPERTY_NAME, sizeCategoryName,
SizeCategory.PROPERTY_MEANING, row.getSizeCategoryMeaning()
);
@@ -468,13 +466,12 @@
header);
SpeciesCategoryDAO speciesCategoryDAO =
- getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
AgeCategoryDAO ageCategoryDAO =
- getDAO(AgeCategory.class, AgeCategoryDAO.class);
- CategoryDAO categoryDAO = (CategoryDAO) getDAO(Category.class);
+ getEchoBasePersistenceContext().getAgeCategoryDAO();
+ CategoryDAO categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ ResultDAO dao = getEchoBasePersistenceContext().getResultDAO();
- ResultDAO dao = getDAO(Result.class, ResultDAO.class);
-
EsduResultBySpeciesAndAgeCategoryImportModel csvModel = new EsduResultBySpeciesAndAgeCategoryImportModel(
getCsvSeparator(),
voyageMap,
@@ -507,8 +504,7 @@
if (ageCategory == null) {
// create a new sizeCategory
- ageCategory = create(
- ageCategoryDAO,
+ ageCategory = ageCategoryDAO.create(
AgeCategory.PROPERTY_NAME, ageCategoryName,
AgeCategory.PROPERTY_MEANING, row.getAgeCategoryMeaning()
);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsImportConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsImportConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsImportConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import fr.ifremer.echobase.io.InputFile;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.collect.Maps;
import fr.ifremer.echobase.EchoBaseTechnicalException;
@@ -32,7 +32,7 @@
import fr.ifremer.echobase.entities.data.Transect;
import fr.ifremer.echobase.entities.data.Transit;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.DecoratorService;
+import fr.ifremer.echobase.services.service.DecoratorService;
import org.nuiton.decorator.Decorator;
import java.util.Map;
@@ -56,27 +56,27 @@
switch (importMode) {
case RESULT_VOYAGE:
- service = getService(ResultsVoyageImportService.class);
+ service = newService(ResultsVoyageImportService.class);
break;
case RESULT_ESDU:
- service = getService(ResultsEsduCellImportService.class);
+ service = newService(ResultsEsduCellImportService.class);
break;
case RESULT_REGION:
- service = getService(ResultsRegionCellImportService.class);
+ service = newService(ResultsRegionCellImportService.class);
break;
case RESULT_MAP_FISH:
- service = getService(ResultsMapFishCellImportService.class);
+ service = newService(ResultsMapFishCellImportService.class);
break;
case RESULT_MAP_OTHER:
- service = getService(ResultsMapOtherCellImportService.class);
+ service = newService(ResultsMapOtherCellImportService.class);
break;
default:
throw new EchoBaseTechnicalException(
@@ -89,7 +89,7 @@
Map<String, String> result = Maps.newLinkedHashMap();
- DecoratorService service = getService(DecoratorService.class);
+ DecoratorService service = getDecoratorService();
Decorator<Transit> transitDecorator = service.getDecorator(getLocale(), Transit.class, null);
Decorator<Transect> transectDecorator = service.getDecorator(getLocale(), Transect.class, null);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsMapFishCellImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
@@ -32,22 +32,21 @@
import fr.ifremer.echobase.entities.data.CategoryDAO;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.CellDAO;
-import fr.ifremer.echobase.entities.data.Data;
import fr.ifremer.echobase.entities.data.DataDAO;
-import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.ResultDAO;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.AgeCategory;
import fr.ifremer.echobase.entities.references.CellType;
+import fr.ifremer.echobase.entities.references.CellTypeDAO;
import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.entities.references.DataMetadataDAO;
import fr.ifremer.echobase.entities.references.DataQuality;
import fr.ifremer.echobase.entities.references.SizeCategory;
import fr.ifremer.echobase.entities.references.Species;
-import fr.ifremer.echobase.entities.references.SpeciesCategory;
import fr.ifremer.echobase.entities.references.SpeciesCategoryDAO;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.MapCellImportModel;
-import fr.ifremer.echobase.services.importdata.csv.MapCellImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.MapCellImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.MapCellImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -77,8 +76,8 @@
EchoBaseUser user) throws ImportException {
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
- configuration.getVoyageId());
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
+ configuration.getVoyageId());
EchoBaseCsvFileImportResult importResult;
importResult = importMapFile(configuration, voyage);
@@ -98,32 +97,28 @@
String resultLabel = configuration.getResultLabel();
- CellType cellType = getEntityByProperty(
- CellType.class, CellType.PROPERTY_ID, "Map");
+ CellTypeDAO cellTypeDAO = getEchoBasePersistenceContext().getCellTypeDAO();
+ CellType cellType = cellTypeDAO.findById("Map");
Preconditions.checkNotNull(cellType);
- DataMetadata dataLongitudeMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridCellLongitude");
+ DataMetadataDAO dataMetadataDAO =
+ getEchoBasePersistenceContext().getDataMetadataDAO();
+ DataMetadata dataLongitudeMeta = dataMetadataDAO.findByName("GridCellLongitude");
Preconditions.checkNotNull(dataLongitudeMeta);
- DataMetadata dataLatitudeMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridCellLatitude");
+ DataMetadata dataLatitudeMeta = dataMetadataDAO.findByName("GridCellLatitude");
Preconditions.checkNotNull(dataLatitudeMeta);
- DataMetadata dataDepthMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridCellDepth");
+ DataMetadata dataDepthMeta = dataMetadataDAO.findByName("GridCellDepth");
Preconditions.checkNotNull(dataDepthMeta);
- DataMetadata dataLongitudeLagMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridLongitudeLag");
+ DataMetadata dataLongitudeLagMeta = dataMetadataDAO.findByName("GridLongitudeLag");
Preconditions.checkNotNull(dataLongitudeLagMeta);
- DataMetadata dataLatitudeLagMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridLatitudeLag");
+ DataMetadata dataLatitudeLagMeta = dataMetadataDAO.findByName("GridLatitudeLag");
Preconditions.checkNotNull(dataLatitudeLagMeta);
- DataMetadata dataDepthLagMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridDepthLag");
+ DataMetadata dataDepthLagMeta = dataMetadataDAO.findByName("GridDepthLag");
Preconditions.checkNotNull(dataDepthLagMeta);
// authorize only the selected voyage to be imported
@@ -168,13 +163,17 @@
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
- CellDAO dao = getDAO(Cell.class, CellDAO.class);
- DataDAO dataDao = getDAO(Data.class, DataDAO.class);
- ResultDAO resultDao = getDAO(Result.class, ResultDAO.class);
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
SpeciesCategoryDAO speciesCategoryDAO =
- getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
- CategoryDAO categoryDAO = getDAO(Category.class, CategoryDAO.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
+ CategoryDAO categoryDAO =
+ getEchoBasePersistenceContext().getCategoryDAO();
+
+
+ DataDAO dataDao = getEchoBasePersistenceContext().getDataDAO();
+ ResultDAO resultDao = getEchoBasePersistenceContext().getResultDAO();
+
Reader reader = getInputFileReader(inputFile);
try {
Import<MapCellImportRow> importer =
@@ -187,7 +186,7 @@
doFlushTransaction(++rowNumber, inputFile, configuration);
- Cell cell = create(dao, row.getCell());
+ Cell cell = dao.create(row.getCell());
voyage.addPostCell(cell);
// collect ids
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsMapOtherCellImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
/*
* #%L
@@ -30,17 +30,17 @@
import fr.ifremer.echobase.entities.EchoBaseUser;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.CellDAO;
-import fr.ifremer.echobase.entities.data.Data;
import fr.ifremer.echobase.entities.data.DataDAO;
-import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.ResultDAO;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.CellType;
+import fr.ifremer.echobase.entities.references.CellTypeDAO;
import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.entities.references.DataMetadataDAO;
import fr.ifremer.echobase.entities.references.DataQuality;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.MapCellImportModel;
-import fr.ifremer.echobase.services.importdata.csv.MapCellImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.MapCellImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.MapCellImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -70,8 +70,8 @@
EchoBaseUser user) throws ImportException {
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
- configuration.getVoyageId());
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
+ configuration.getVoyageId());
EchoBaseCsvFileImportResult importResult;
importResult = importMapFile(configuration, voyage);
@@ -91,32 +91,29 @@
String resultLabel = configuration.getResultLabel();
- CellType cellType = getEntityByProperty(
- CellType.class, CellType.PROPERTY_ID, "Map");
+ CellTypeDAO cellTypeDAO = getEchoBasePersistenceContext().getCellTypeDAO();
+ CellType cellType = cellTypeDAO.findById("Map");
Preconditions.checkNotNull(cellType);
- DataMetadata dataLongitudeMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridCellLongitude");
+ DataMetadataDAO dataMetadataDAO =
+ getEchoBasePersistenceContext().getDataMetadataDAO();
+
+ DataMetadata dataLongitudeMeta = dataMetadataDAO.findByName("GridCellLongitude");
Preconditions.checkNotNull(dataLongitudeMeta);
- DataMetadata dataLatitudeMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridCellLatitude");
+ DataMetadata dataLatitudeMeta = dataMetadataDAO.findByName("GridCellLatitude");
Preconditions.checkNotNull(dataLatitudeMeta);
- DataMetadata dataDepthMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridCellDepth");
+ DataMetadata dataDepthMeta = dataMetadataDAO.findByName("GridCellDepth");
Preconditions.checkNotNull(dataDepthMeta);
- DataMetadata dataLongitudeLagMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridLongitudeLag");
+ DataMetadata dataLongitudeLagMeta = dataMetadataDAO.findByName("GridLongitudeLag");
Preconditions.checkNotNull(dataLongitudeLagMeta);
- DataMetadata dataLatitudeLagMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridLatitudeLag");
+ DataMetadata dataLatitudeLagMeta = dataMetadataDAO.findByName("GridLatitudeLag");
Preconditions.checkNotNull(dataLatitudeLagMeta);
- DataMetadata dataDepthLagMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "GridDepthLag");
+ DataMetadata dataDepthLagMeta = dataMetadataDAO.findByName("GridDepthLag");
Preconditions.checkNotNull(dataDepthLagMeta);
// authorize only the selected voyage to be imported
@@ -147,9 +144,9 @@
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
- CellDAO dao = getDAO(Cell.class, CellDAO.class);
- DataDAO dataDao = getDAO(Data.class, DataDAO.class);
- ResultDAO resultDao = getDAO(Result.class, ResultDAO.class);
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
+ DataDAO dataDao = getEchoBasePersistenceContext().getDataDAO();
+ ResultDAO resultDao = getEchoBasePersistenceContext().getResultDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -163,7 +160,7 @@
doFlushTransaction(++rowNumber, inputFile, configuration);
- Cell cell = create(dao, row.getCell());
+ Cell cell = dao.create(row.getCell());
voyage.addPostCell(cell);
// collect ids
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsRegionCellImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
@@ -32,26 +32,25 @@
import fr.ifremer.echobase.entities.data.CategoryDAO;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.CellDAO;
-import fr.ifremer.echobase.entities.data.Data;
import fr.ifremer.echobase.entities.data.DataDAO;
import fr.ifremer.echobase.entities.data.Echotype;
-import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.ResultDAO;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.CellType;
+import fr.ifremer.echobase.entities.references.CellTypeDAO;
import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.entities.references.DataMetadataDAO;
import fr.ifremer.echobase.entities.references.DataQuality;
import fr.ifremer.echobase.entities.references.SizeCategory;
import fr.ifremer.echobase.entities.references.Species;
-import fr.ifremer.echobase.entities.references.SpeciesCategory;
import fr.ifremer.echobase.entities.references.SpeciesCategoryDAO;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.RegionCellAssociationImportModel;
-import fr.ifremer.echobase.services.importdata.csv.RegionCellAssociationImportRow;
-import fr.ifremer.echobase.services.importdata.csv.RegionCellImportModel;
-import fr.ifremer.echobase.services.importdata.csv.RegionCellImportRow;
-import fr.ifremer.echobase.services.importdata.csv.RegionCellResultImportModel;
-import fr.ifremer.echobase.services.importdata.csv.RegionCellResultImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.RegionCellAssociationImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.RegionCellAssociationImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.RegionCellImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.RegionCellImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.RegionCellResultImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.RegionCellResultImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.csv.Import;
@@ -81,8 +80,8 @@
EchoBaseUser user) throws ImportException {
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
- configuration.getVoyageId());
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
+ configuration.getVoyageId());
Map<String, DataQuality> dataQualityMap = getEntitiesMap(
DataQuality.class, EchoBaseFunctions.DATA_QUALITY_NAME);
@@ -106,21 +105,21 @@
InputFile inputFile = configuration.getRegionsFile();
- CellType cellSurfaceType = getEntityByProperty(
- CellType.class, CellType.PROPERTY_ID, "RegionSURF");
+ CellTypeDAO cellTypeDAO = getEchoBasePersistenceContext().getCellTypeDAO();
+
+ CellType cellSurfaceType = cellTypeDAO.findById("RegionSURF");
Preconditions.checkNotNull(cellSurfaceType);
- CellType cellBottomType = getEntityByProperty(
- CellType.class, CellType.PROPERTY_ID, "RegionCLAS");
+ CellType cellBottomType = cellTypeDAO.findById("RegionCLAS");
Preconditions.checkNotNull(cellBottomType);
- DataMetadata dataCoordinateMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME,
- "RegionEnvCoordinates");
+ DataMetadataDAO dataMetadataDAO =
+ getEchoBasePersistenceContext().getDataMetadataDAO();
+
+ DataMetadata dataCoordinateMeta = dataMetadataDAO.findByName("RegionEnvCoordinates");
Preconditions.checkNotNull(dataCoordinateMeta);
- DataMetadata dataSurfaceMeta = getEntityByProperty(
- DataMetadata.class, DataMetadata.PROPERTY_NAME, "Surface");
+ DataMetadata dataSurfaceMeta = dataMetadataDAO.findByName("Surface");
Preconditions.checkNotNull(dataSurfaceMeta);
// authorize only the selected voyage to be imported
@@ -146,8 +145,8 @@
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
- CellDAO dao = getDAO(Cell.class, CellDAO.class);
- DataDAO dataDao = getDAO(Data.class, DataDAO.class);
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
+ DataDAO dataDao = getEchoBasePersistenceContext().getDataDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -163,9 +162,9 @@
doFlushTransaction(++rowNumber, inputFile, configuration);
if (cell == null || !row.getName().equals(cell.getName())) {
- cell = create(dao,
- Cell.PROPERTY_CELL_TYPE, row.getCellType(),
- Cell.PROPERTY_NAME, row.getName()
+ cell = dao.create(
+ Cell.PROPERTY_CELL_TYPE, row.getCellType(),
+ Cell.PROPERTY_NAME, row.getName()
);
voyage.addPostCell(cell);
@@ -218,12 +217,14 @@
Map<String, Cell> regionsMap = Maps.uniqueIndex(
voyage.getRegionCells(), EchoBaseFunctions.CELL_BY_NAME);
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
+
RegionCellAssociationImportModel csvModel = new RegionCellAssociationImportModel(
getCsvSeparator(),
voyage,
voyageMap,
regionsMap,
- getDAO(Cell.class, CellDAO.class));
+ dao);
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
@@ -310,9 +311,9 @@
EchoBaseCsvFileImportResult importResult = newImportResult(inputFile);
SpeciesCategoryDAO speciesCategoryDAO =
- getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
- CategoryDAO categoryDAO = getDAO(Category.class, CategoryDAO.class);
- ResultDAO dao = getDAO(Result.class, ResultDAO.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
+ CategoryDAO categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ ResultDAO dao = getEchoBasePersistenceContext().getResultDAO();
Reader reader = getInputFileReader(inputFile);
try {
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/ResultsVoyageImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata;
+package fr.ifremer.echobase.services.service.importdata;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
@@ -42,17 +42,17 @@
import fr.ifremer.echobase.entities.references.SpeciesCategoryDAO;
import fr.ifremer.echobase.entities.references.Strata;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.csv.EchotypeImportModel;
-import fr.ifremer.echobase.services.importdata.csv.EchotypeImportRow;
-import fr.ifremer.echobase.services.importdata.csv.LengthAgeKeyImportModel;
-import fr.ifremer.echobase.services.importdata.csv.LengthAgeKeyImportRow;
-import fr.ifremer.echobase.services.importdata.csv.LengthWeightKeyImportModel;
-import fr.ifremer.echobase.services.importdata.csv.LengthWeightKeyImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.EchotypeImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.EchotypeImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.LengthAgeKeyImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.LengthAgeKeyImportRow;
+import fr.ifremer.echobase.services.service.importdata.csv.LengthWeightKeyImportModel;
+import fr.ifremer.echobase.services.service.importdata.csv.LengthWeightKeyImportRow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.csv.Import;
import org.nuiton.csv.ImportRuntimeException;
+import org.nuiton.topia.persistence.TopiaDAO;
import java.io.Reader;
import java.util.Arrays;
@@ -83,7 +83,7 @@
Strata.class, EchoBaseFunctions.STRATA_BY_NAME);
// get selected voyage
- Voyage voyage = getEntityById(Voyage.class,
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class,
configuration.getVoyageId());
// authorize only the selected voyage to be imported
@@ -159,11 +159,10 @@
sizeCategoryMap,
speciesMap);
- LengthWeightKeyDAO dao = getDAO(LengthWeightKey.class,
- LengthWeightKeyDAO.class);
+ LengthWeightKeyDAO dao = getEchoBasePersistenceContext().getLengthWeightKeyDAO();
SpeciesCategoryDAO speciesCategoryDAO =
- getDAO(SpeciesCategory.class, SpeciesCategoryDAO.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
Reader reader = getInputFileReader(inputFile);
@@ -191,7 +190,7 @@
LengthWeightKey toCreate = row.getLengthWeightKey();
toCreate.setSpeciesCategory(speciesCategory);
- LengthWeightKey lengthWeightKey = create(dao, toCreate);
+ LengthWeightKey lengthWeightKey = dao.create(toCreate);
//TODO should we import it ?
//lengthWeightKey.setMetadata(row.getMetadata());
@@ -232,7 +231,7 @@
strataMap,
speciesMap);
- TopiaDAO<LengthAgeKey> dao = getDAO(LengthAgeKey.class);
+ TopiaDAO<LengthAgeKey> dao = getEchoBasePersistenceContext().getLengthAgeKeyDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -249,7 +248,7 @@
Voyage voyage = row.getVoyage();
LengthAgeKey lengthAgeKeyToCreate = row.getLengthAgeKey();
- LengthAgeKey lengthAgeKey = create(dao, lengthAgeKeyToCreate);
+ LengthAgeKey lengthAgeKey = dao.create(lengthAgeKeyToCreate);
// attach it to voyage
voyage.addLengthAgeKey(lengthAgeKey);
@@ -289,7 +288,7 @@
depthStratumMap,
speciesMap);
- TopiaDAO<Echotype> dao = getDAO(Echotype.class);
+ TopiaDAO<Echotype> dao = getEchoBasePersistenceContext().getEchotypeDAO();
Reader reader = getInputFileReader(inputFile);
try {
@@ -325,7 +324,7 @@
if (echotype == null) {
// creates it
- echotype = create(dao, rowEchotype);
+ echotype = dao.create(rowEchotype);
// attach it to voyage
voyage.addEchotype(echotype);
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/AcousticImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/AcousticImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/AcousticImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/AcousticImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/AcousticImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/AcousticImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.references.AcousticInstrument;
import fr.ifremer.echobase.entities.references.DataQuality;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/BiometrySampleImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/BiometrySampleImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/BiometrySampleImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Operation;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/BiometrySampleImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/BiometrySampleImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/BiometrySampleImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Operation;
import fr.ifremer.echobase.entities.data.SampleData;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EchotypeImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EchotypeImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EchotypeImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Echotype;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EchotypeImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EchotypeImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EchotypeImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Echotype;
import fr.ifremer.echobase.entities.data.EchotypeImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeAndSpeciesCategoryImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultByEchotypeImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultByEchotypeImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultByEchotypeImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndAgeCategoryImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/EsduResultBySpeciesAndSizeCategoryImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/GearMetadataValueImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/GearMetadataValueImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/GearMetadataValueImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.GearMetadataValue;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/GearMetadataValueImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/GearMetadataValueImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/GearMetadataValueImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.GearMetadataValue;
import fr.ifremer.echobase.entities.data.GearMetadataValueImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthAgeKeyImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/LengthAgeKeyImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthAgeKeyImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.LengthAgeKey;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthAgeKeyImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/LengthAgeKeyImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthAgeKeyImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.LengthAgeKey;
import fr.ifremer.echobase.entities.data.LengthAgeKeyImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthWeightKeyImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/LengthWeightKeyImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthWeightKeyImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.LengthWeightKey;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthWeightKeyImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/LengthWeightKeyImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/LengthWeightKeyImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.LengthWeightKey;
import fr.ifremer.echobase.entities.data.LengthWeightKeyImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/MapCellImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/MapCellImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/MapCellImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Voyage;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/MapCellImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/MapCellImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/MapCellImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/OperationImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Operation;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/OperationImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Operation;
import fr.ifremer.echobase.entities.data.OperationImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationMetadataValueImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/OperationMetadataValueImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationMetadataValueImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Operation;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationMetadataValueImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/OperationMetadataValueImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/OperationMetadataValueImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Operation;
import fr.ifremer.echobase.entities.data.OperationMetadataValue;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellAssociationImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/RegionCellAssociationImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellAssociationImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellAssociationImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/RegionCellAssociationImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellAssociationImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.Voyage;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/RegionCellImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Voyage;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/RegionCellImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.CellType;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellResultImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/RegionCellResultImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellResultImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Cell;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellResultImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/RegionCellResultImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/RegionCellResultImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import com.google.common.collect.Lists;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/SubSampleImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/SubSampleImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/SubSampleImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Operation;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/SubSampleImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/SubSampleImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/SubSampleImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Operation;
import fr.ifremer.echobase.entities.data.Sample;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TotalSampleImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/TotalSampleImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TotalSampleImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Operation;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TotalSampleImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/TotalSampleImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TotalSampleImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Operation;
import fr.ifremer.echobase.entities.data.Sample;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransectImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/TransectImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransectImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Transect;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransectImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/TransectImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransectImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Transect;
import fr.ifremer.echobase.entities.data.TransectImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransitImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/TransitImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransitImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Transit;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransitImportRow.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/TransitImportRow.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/TransitImportRow.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.entities.data.Transit;
import fr.ifremer.echobase.entities.data.TransitImpl;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/VoyageImportModel.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdata/csv/VoyageImportModel.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdata/csv/VoyageImportModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdata.csv;
+package fr.ifremer.echobase.services.service.importdata.csv;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.data.Voyage;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/EchoBaseImportModelFactory.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/EchoBaseImportModelFactory.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/EchoBaseImportModelFactory.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdb;
+package fr.ifremer.echobase.services.service.importdb;
/*
* #%L
@@ -24,7 +24,7 @@
*/
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.services.EchoBaseServiceSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.csv.EntityCsvModel;
@@ -48,7 +48,7 @@
public static ImportModelFactory<EchoBaseEntityEnum> newFactory(EchoBaseServiceSupport service) {
return new EchoBaseImportModelFactory(
- service.getService(DbEditorService.class),
+ service.getDbEditorService(),
service.getConfiguration().getCsvSeparator()
);
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/ImportDbConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,7 +21,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdb;
+package fr.ifremer.echobase.services.service.importdb;
import fr.ifremer.echobase.io.InputFile;
import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbMode.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/ImportDbMode.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbMode.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdb;
+package fr.ifremer.echobase.services.service.importdb;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/ImportDbService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportDbService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,15 +21,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdb;
+package fr.ifremer.echobase.services.service.importdb;
import fr.ifremer.echobase.EchoBaseTechnicalException;
import fr.ifremer.echobase.entities.EchoBaseUser;
import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.importdata.ImportException;
-import fr.ifremer.echobase.services.importdb.strategy.AbstractImportDbStrategy;
-import fr.ifremer.echobase.services.importdb.strategy.FreeImportDbStrategy;
-import fr.ifremer.echobase.services.importdb.strategy.ReferentialImportDbStrategy;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdb.strategy.AbstractImportDbStrategy;
+import fr.ifremer.echobase.services.service.importdb.strategy.FreeImportDbStrategy;
+import fr.ifremer.echobase.services.service.importdb.strategy.ReferentialImportDbStrategy;
import org.nuiton.topia.TopiaException;
import java.io.IOException;
@@ -51,10 +51,10 @@
switch (importDbMode) {
case REFERENTIAL:
- strategy = getService(ReferentialImportDbStrategy.class);
+ strategy = newService(ReferentialImportDbStrategy.class);
break;
case FREE:
- strategy = getService(FreeImportDbStrategy.class);
+ strategy = newService(FreeImportDbStrategy.class);
break;
default:
throw new EchoBaseTechnicalException(
@@ -71,8 +71,12 @@
if (ImportDbMode.REFERENTIAL != importDbMode) {
+ // revoke all spatial data cache for all this db
+ getSpatialDataCache().onDbChanged(
+ serviceContext.getWorkgingDbUrl());
+
// let's update postgis table
- updatePostgisTable();
+ getSpatialService().updatePostgisTable();
}
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/ImportService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/ImportService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,14 +21,14 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-package fr.ifremer.echobase.services.importdb;
+package fr.ifremer.echobase.services.service.importdb;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import fr.ifremer.echobase.EchoBaseTechnicalException;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.services.EchoBaseServiceSupport;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
@@ -64,7 +64,7 @@
ImportModelFactory<EchoBaseEntityEnum> importModelFactory =
EchoBaseImportModelFactory.newFactory(this);
- DbEditorService service = getService(DbEditorService.class);
+ DbEditorService service = getDbEditorService();
TableMeta<EchoBaseEntityEnum> meta = service.getTableMeta(entityType);
ImportModel<TopiaEntity> csvModel = importModelFactory.buildForImport(meta);
@@ -104,7 +104,7 @@
bf.close();
- commitTransaction("Could not commit transaction");
+ getEchoBasePersistenceContext().commitTransaction();
} catch (EchoBaseTechnicalException eee) {
throw eee;
} catch (Exception eee) {
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/AbstractImportDbStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/strategy/AbstractImportDbStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/AbstractImportDbStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdb.strategy;
+package fr.ifremer.echobase.services.service.importdb.strategy;
/*
* #%L
@@ -33,9 +33,9 @@
import fr.ifremer.echobase.io.EchoBaseIOUtil;
import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.importdata.ImportException;
-import fr.ifremer.echobase.services.importdb.EchoBaseImportModelFactory;
-import fr.ifremer.echobase.services.importdb.ImportDbConfiguration;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdb.EchoBaseImportModelFactory;
+import fr.ifremer.echobase.services.service.importdb.ImportDbConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -118,8 +118,7 @@
ImportStrategy<EchoBaseEntityEnum> strategy = new EchoBaseImportStrategy(
EchoBaseImportModelFactory.newFactory(this),
- getTransaction(),
- dbMeta.getPersistenceHelper(),
+ getEchoBasePersistenceContext(),
1000
);
@@ -139,19 +138,19 @@
if (importedVoyages != null &&
!Iterables.isEmpty(importedVoyages)) {
- createImportLogEntry(getDAO(ImportLog.class),
+ createImportLogEntry(getEchoBasePersistenceContext().getImportLogDAO(),
user,
file,
importedVoyages);
}
- createLogBookEntry(getDAO(EntityModificationLog.class),
+ createLogBookEntry(getEchoBasePersistenceContext().getEntityModificationLogDAO(),
user,
file);
zipFile.close();
- commitTransaction("Could not commit db import from file " + file);
+ getEchoBasePersistenceContext().commitTransaction();
} finally {
@@ -223,19 +222,17 @@
s0 = TIME_LOG.log(s0, "importFile::done");
- flushTransaction("Could not flush " + entryDef + " to db.");
+ getEchoBasePersistenceContext().flush();
TIME_LOG.log(s0, "importFile::flushTransaction");
reader.close();
} finally {
IOUtils.closeQuietly(reader);
if (commitAfterEachFile) {
- commitTransaction(
- "Could not commit db import from file " +
- zipFile.getName() + "#" + entryDef.getFilename());
+ getEchoBasePersistenceContext().commitTransaction();
}
- clearCache();
+ getEchoBasePersistenceContext().clear();
}
}
@@ -277,7 +274,7 @@
s0 = TIME_LOG.log(s0, "importFile::done");
- flushTransaction("Could not flush associations to db.");
+ getEchoBasePersistenceContext().flush();
TIME_LOG.log(s0, "importFile::flushTransaction");
} finally {
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/EchoBaseImportStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/strategy/EchoBaseImportStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/EchoBaseImportStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdb.strategy;
+package fr.ifremer.echobase.services.service.importdb.strategy;
/*
* #%L
@@ -24,10 +24,9 @@
*/
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.persistence.EchoBasePersistenceHelper;
+import fr.ifremer.echobase.entities.EchoBasePersistenceContext;
import org.nuiton.csv.Import;
import org.nuiton.csv.ImportToMap;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.TopiaEntity;
@@ -50,20 +49,24 @@
*/
public class EchoBaseImportStrategy implements ImportStrategy<EchoBaseEntityEnum> {
- private final TopiaContext tx;
+ private final EchoBasePersistenceContext persistenceContext;
- private final EchoBasePersistenceHelper persistenceHelper;
+// private final TopiaContext tx;
+// private final EchoBasePersistenceHelper persistenceHelper;
+
private final int nbRowBuffer;
private final ImportModelFactory<EchoBaseEntityEnum> modelFactory;
public EchoBaseImportStrategy(ImportModelFactory<EchoBaseEntityEnum> modelFactory,
- TopiaContext tx,
- EchoBasePersistenceHelper persistenceHelper,
+ EchoBasePersistenceContext persistenceContext,
+// TopiaContext tx,
+// EchoBasePersistenceHelper persistenceHelper,
int nbRowBuffer) {
- this.tx = tx;
- this.persistenceHelper = persistenceHelper;
+ this.persistenceContext = persistenceContext;
+// this.tx = tx;
+// this.persistenceHelper = persistenceHelper;
this.nbRowBuffer = nbRowBuffer;
this.modelFactory = modelFactory;
}
@@ -76,7 +79,7 @@
public <E extends TopiaEntity> void importTable(TableMeta<EchoBaseEntityEnum> meta,
Import<E> importer,
CsvImportResult<EchoBaseEntityEnum> csvResult) throws TopiaException {
- TopiaDAO<E> dao = persistenceHelper.getDAO(tx, meta.getSource());
+ TopiaDAO<E> dao = (TopiaDAO<E>) persistenceContext.getDAO(meta.getSource().getContract());
if (meta.getSource() == EchoBaseEntityEnum.Category) {
@@ -92,7 +95,7 @@
public <E extends TopiaEntity> Iterable<E> importTableAndReturnThem(TableMeta<EchoBaseEntityEnum> meta,
Import<E> importer,
CsvImportResult<EchoBaseEntityEnum> csvResult) throws TopiaException {
- TopiaDAO<E> dao = persistenceHelper.getDAO(tx, meta.getSource());
+ TopiaDAO<E> dao = (TopiaDAO<E>) persistenceContext.getDAO(meta.getSource().getContract());
Iterable<E> result = TopiaCsvImports.importAllEntitiesAndReturnThem(
dao, meta, importer, csvResult);
@@ -106,13 +109,13 @@
CsvImportResult<EchoBaseEntityEnum> csvResult) throws TopiaException {
if (getModelFactory().isNMAssociationMeta(meta)) {
- TopiaCsvImports.importNMAssociation(tx,
+ TopiaCsvImports.importNMAssociation(persistenceContext.getContext(),
meta,
importer,
csvResult,
nbRowBuffer);
} else {
- TopiaCsvImports.importAssociation(tx,
+ TopiaCsvImports.importAssociation(persistenceContext.getContext(),
meta,
importer,
csvResult,
@@ -126,7 +129,7 @@
CsvImportResult<T> csvResult,
int nbRowBuffer) throws TopiaException {
- TopiaContext context = dao.getTopiaContext();
+// TopiaContext context = dao.getTopiaContext();
CsvProgressModel progressModel = csvResult == null ? null :
csvResult.getProgressModel();
@@ -144,8 +147,7 @@
compt++;
if (compt % nbRowBuffer == 0) {
// flush it
- persistenceHelper.flushTransaction(
- context, "could not flush transaction");
+ persistenceContext.getContext().getHibernateSession().flush();
}
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/FreeImportDbStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/strategy/FreeImportDbStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/FreeImportDbStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdb.strategy;
+package fr.ifremer.echobase.services.service.importdb.strategy;
/*
* #%L
@@ -30,13 +30,12 @@
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
-import fr.ifremer.echobase.services.DecoratorService;
-import fr.ifremer.echobase.services.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
+import org.nuiton.decorator.Decorator;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.metadata.AssociationMeta;
import org.nuiton.topia.persistence.metadata.TableMeta;
-import org.nuiton.decorator.Decorator;
import java.io.File;
import java.util.Date;
@@ -70,7 +69,8 @@
Iterable<Voyage> importedVoyages) throws TopiaException {
Date date = newDate();
- Decorator<Voyage> decorator = getService(DecoratorService.class).getDecorator(getLocale(), Voyage.class, null);
+ Decorator<Voyage> decorator = getDecoratorService().getDecorator(
+ getLocale(), Voyage.class, null);
for (Voyage importedVoyage : importedVoyages) {
// create a importLog entry
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/ReferentialImportDbStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/importdb/strategy/ReferentialImportDbStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/importdb/strategy/ReferentialImportDbStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.importdb.strategy;
+package fr.ifremer.echobase.services.service.importdb.strategy;
/*
* #%L
@@ -30,7 +30,7 @@
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
-import fr.ifremer.echobase.services.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.metadata.AssociationMeta;
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/RemoveDataConfiguration.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/RemoveDataConfiguration.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/RemoveDataConfiguration.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata;
+package fr.ifremer.echobase.services.service.removedata;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/RemoveDataService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/RemoveDataService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/RemoveDataService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata;
+package fr.ifremer.echobase.services.service.removedata;
/*
* #%L
@@ -32,22 +32,21 @@
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.DecoratorService;
import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.removedata.strategy.AbstractRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.AcousticRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.CatchesRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.CommonAllRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.CommonTransectRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.CommonTransitRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.CommonVoyageRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.LegacyVoyageRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.OperationRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.ResultEsduRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.ResultMapFishRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.ResultMapOtherRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.ResultRegionRemoveDataStrategy;
-import fr.ifremer.echobase.services.removedata.strategy.ResultVoyageRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.AbstractRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.AcousticRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.CatchesRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonAllRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonTransectRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonTransitRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonVoyageRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.LegacyVoyageRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.OperationRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultEsduRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultMapFishRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultMapOtherRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultRegionRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultVoyageRemoveDataStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.decorator.Decorator;
@@ -121,13 +120,13 @@
Maps.newTreeMap(IMPORT_LOG_COMPARATOR);
for (String id : model.getImportLogIds()) {
- ImportLog importLog = getEntityById(ImportLog.class, id);
+ ImportLog importLog = getEchoBasePersistenceContext().getEntityById(ImportLog.class, id);
Class<? extends AbstractRemoveDataStrategy> strategyType =
getStrategy(importLog);
- AbstractRemoveDataStrategy strategy = getService(strategyType);
+ AbstractRemoveDataStrategy strategy = newService(strategyType);
strategy.setProgressModel(model);
- Voyage voyage = getEntityById(Voyage.class, importLog.getVoyageId());
+ Voyage voyage = getWorkingDbPersistenceService().getVoyageDAO().findByTopiaId(importLog.getVoyageId());
long l = strategy.computeNbSteps(voyage, importLog);
ImportContext importContext = new ImportContext(id, l + 3, strategy, voyage);
toTreat.put(importLog, importContext);
@@ -151,8 +150,7 @@
EchoBaseUser user) {
// check that importLog still exists
- ImportLog importLog = getEntityById(ImportLog.class,
- importContext.importLogId);
+ ImportLog importLog = getWorkingDbPersistenceService().getImportLogDAO().findByTopiaId(importContext.importLogId);
AbstractRemoveDataStrategy strategy = importContext.strategy;
@@ -185,7 +183,7 @@
strategy.incrementOp("Log book entry for " + importLog.getTopiaId());
// do commit
- commitTransaction("Could not remove import " + strategy.getImportLabel());
+ getEchoBasePersistenceContext().commitTransaction();
strategy.incrementOp("Commit importLog " + importLog.getTopiaId());
TIME_LOG.log(s0, "Commit importLog " + importLog.getTopiaId());
return result;
@@ -199,7 +197,7 @@
Set<ImportType> possibleSubImportType =
strategy.getPossibleSubImportType();
- TopiaDAO<ImportLog> dao = getDAO(ImportLog.class);
+ TopiaDAO<ImportLog> dao = getEchoBasePersistenceContext().getImportLogDAO();
for (ImportLog logEntry : dao) {
@@ -207,7 +205,7 @@
// for sure remove me
// but do not add to result
- delete(dao, logEntry);
+ dao.delete(logEntry);
continue;
}
@@ -232,7 +230,7 @@
logEntry.getImportType() + ": " + logEntry.getTopiaId());
}
- delete(dao, logEntry);
+ dao.delete(logEntry);
// add it in result
result.add(logEntry);
@@ -270,7 +268,7 @@
List<ImportLog> obsoleteImportLogs,
EchoBaseUser user) {
- Decorator<ImportLog> decorator = getService(DecoratorService.class).
+ Decorator<ImportLog> decorator = getDecoratorService().
getDecorator(getLocale(), ImportLog.class, null);
StringBuilder buffer = new StringBuilder();
@@ -287,12 +285,12 @@
if (log.isDebugEnabled()) {
log.debug("Log text: " + result);
}
- create(getDAO(EntityModificationLog.class),
- EntityModificationLog.PROPERTY_ENTITY_TYPE, "Removed Import",
- EntityModificationLog.PROPERTY_ENTITY_ID, importLog.getTopiaId(),
- EntityModificationLog.PROPERTY_MODIFICATION_USER, user.getEmail(),
- EntityModificationLog.PROPERTY_MODIFICATION_DATE, newDate(),
- EntityModificationLog.PROPERTY_MODIFICATION_TEXT, result
+ getEchoBasePersistenceContext().getEntityModificationLogDAO().create(
+ EntityModificationLog.PROPERTY_ENTITY_TYPE, "Removed Import",
+ EntityModificationLog.PROPERTY_ENTITY_ID, importLog.getTopiaId(),
+ EntityModificationLog.PROPERTY_MODIFICATION_USER, user.getEmail(),
+ EntityModificationLog.PROPERTY_MODIFICATION_DATE, newDate(),
+ EntityModificationLog.PROPERTY_MODIFICATION_TEXT, result
);
return result;
}
@@ -309,9 +307,9 @@
protected <E extends TopiaEntity> TopiaDAO<E> getDAOFromId(String id) {
try {
- TopiaIdFactory topiaIdFactory = getTransaction().getTopiaIdFactory();
+ TopiaIdFactory topiaIdFactory = getEchoBasePersistenceContext().getTopiaIdFactory();
Class<E> className = topiaIdFactory.getClassName(id);
- return getDAO(className);
+ return getEchoBasePersistenceContext().getDAO(className);
} catch (TopiaNotFoundException e) {
throw new EchoBaseTechnicalException(
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/AbstractRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/AbstractRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/AbstractRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -31,13 +31,9 @@
import fr.ifremer.echobase.entities.data.CategoryDAO;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.CellDAO;
-import fr.ifremer.echobase.entities.data.DataProcessing;
import fr.ifremer.echobase.entities.data.DataProcessingDAO;
-import fr.ifremer.echobase.entities.data.Echotype;
import fr.ifremer.echobase.entities.data.EchotypeDAO;
-import fr.ifremer.echobase.entities.data.LengthAgeKey;
import fr.ifremer.echobase.entities.data.LengthAgeKeyDAO;
-import fr.ifremer.echobase.entities.data.LengthWeightKey;
import fr.ifremer.echobase.entities.data.LengthWeightKeyDAO;
import fr.ifremer.echobase.entities.data.Result;
import fr.ifremer.echobase.entities.data.ResultDAO;
@@ -98,14 +94,14 @@
@Override
public void setServiceContext(EchoBaseServiceContext serviceContext) {
super.setServiceContext(serviceContext);
- dataProcessingDAO = getDAO(DataProcessing.class, DataProcessingDAO.class);
- cellDAO = getDAO(Cell.class, CellDAO.class);
- echotypeDAO = getDAO(Echotype.class, EchotypeDAO.class);
- voyageDao = getDAO(Voyage.class, VoyageDAO.class);
- lengthAgeKeyDAO = getDAO(LengthAgeKey.class, LengthAgeKeyDAO.class);
- lengthWeightKeyDAO = getDAO(LengthWeightKey.class, LengthWeightKeyDAO.class);
- categoryDAO = getDAO(Category.class, CategoryDAO.class);
- resultDAO = getDAO(Result.class, ResultDAO.class);
+ dataProcessingDAO = getEchoBasePersistenceContext().getDataProcessingDAO();
+ cellDAO = getEchoBasePersistenceContext().getCellDAO();
+ echotypeDAO = getEchoBasePersistenceContext().getEchotypeDAO();
+ voyageDao = getEchoBasePersistenceContext().getVoyageDAO();
+ lengthAgeKeyDAO = getEchoBasePersistenceContext().getLengthAgeKeyDAO();
+ lengthWeightKeyDAO = getEchoBasePersistenceContext().getLengthWeightKeyDAO();
+ categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ resultDAO = getEchoBasePersistenceContext().getResultDAO();
}
public void setProgressModel(ProgressModel progressModel) {
@@ -123,7 +119,7 @@
removePreDataInVoyage(voyage);
- flushTransaction("Could not flush transaction");
+ getEchoBasePersistenceContext().flush();
for (String importId : importLog.getImportId()) {
@@ -136,11 +132,11 @@
incrementOp("ImportLog " + importId + "Removed");
}
- flushTransaction("Could not flush transaction");
+ getEchoBasePersistenceContext().flush();
removePostDataInVoyage(voyage);
- flushTransaction("Could not flush transaction");
+ getEchoBasePersistenceContext().flush();
}
long opIndex;
@@ -170,7 +166,7 @@
}
// delete it
- delete(voyageDao, entity);
+ voyageDao.delete(entity);
// remove obsolete categories
for (Category category : categories) {
@@ -227,7 +223,7 @@
}
};
- List<String> cellIds = query.findMultipleResult(getTransaction());
+ List<String> cellIds = getEchoBasePersistenceContext().findMultipleResult(query);
// remove all result of cells
@@ -271,7 +267,7 @@
}
};
try {
- Long result = query.findSingleResult(getTransaction());
+ Long result = getEchoBasePersistenceContext().findSingleResult(query);
return result;
} catch (TopiaException e) {
throw new EchoBaseTechnicalException(e);
@@ -295,7 +291,7 @@
}
};
- List<String> cellIds = query.findMultipleResult(getTransaction());
+ List<String> cellIds = getEchoBasePersistenceContext().findMultipleResult(query);
for (String cellId : cellIds) {
Cell cell = cellDAO.findByTopiaId(cellId);
@@ -330,7 +326,7 @@
}
};
try {
- Long result = query.findSingleResult(getTransaction());
+ Long result = getEchoBasePersistenceContext().findSingleResult(query);
return result;
} catch (TopiaException e) {
throw new EchoBaseTechnicalException(e);
@@ -359,7 +355,7 @@
public void incrementOp(String message) {
opIndex++;
if (opIndex % 1000 == 0) {
- flushTransaction("Could not flush transaction");
+ getEchoBasePersistenceContext().flush();
}
progressModel.incrementsProgress();
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/AcousticRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/AcousticRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/AcousticRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -62,8 +62,8 @@
public void setServiceContext(EchoBaseServiceContext serviceContext) {
super.setServiceContext(serviceContext);
- dataAcquisitionDAO = getDAO(DataAcquisition.class, DataAcquisitionDAO.class);
- transectDAO = getDAO(Transect.class, TransectDAO.class);
+ dataAcquisitionDAO = getEchoBasePersistenceContext().getDataAcquisitionDAO();
+ transectDAO = getEchoBasePersistenceContext().getTransectDAO();
}
@Override
@@ -112,7 +112,7 @@
transect.removeDataAcquisition(dataAcquisition);
// remove dataAcquisition
- delete(dataAcquisitionDAO, dataAcquisition);
+ dataAcquisitionDAO.delete(dataAcquisition);
if (log.isDebugEnabled()) {
log.debug(dataAcquisition.getTopiaId() + " was removed");
}
@@ -129,7 +129,7 @@
dataProcessing.removeCell(cell);
// remove cell
- delete(cellDAO, cell);
+ cellDAO.delete(cell);
if (log.isDebugEnabled()) {
log.debug(cell.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CatchesRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/CatchesRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CatchesRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -59,8 +59,8 @@
@Override
public void setServiceContext(EchoBaseServiceContext serviceContext) {
super.setServiceContext(serviceContext);
- sampleDAO = getDAO(Sample.class, SampleDAO.class);
- operationDAO = getDAO(Operation.class, OperationDAO.class);
+ sampleDAO = getEchoBasePersistenceContext().getSampleDAO();
+ operationDAO = getEchoBasePersistenceContext().getOperationDAO();
}
@Override
@@ -82,7 +82,7 @@
operation.removeSample(sample);
// remove sample
- delete(sampleDAO, sample);
+ sampleDAO.delete( sample);
if (log.isDebugEnabled()) {
log.debug(sample.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonAllRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/CommonAllRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonAllRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonTransectRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/CommonTransectRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonTransectRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -60,8 +60,8 @@
public void setServiceContext(EchoBaseServiceContext serviceContext) {
super.setServiceContext(serviceContext);
- transectDAO = getDAO(Transect.class, TransectDAO.class);
- transitDAO = getDAO(Transit.class, TransitDAO.class);
+ transectDAO = getEchoBasePersistenceContext().getTransectDAO();
+ transitDAO = getEchoBasePersistenceContext().getTransitDAO();
}
@Override
@@ -110,7 +110,7 @@
transit.removeTransect(transect);
// delete it
- delete(transectDAO, transect);
+ transectDAO.delete( transect);
if (log.isDebugEnabled()) {
log.debug(transect.getTopiaId() + " was removed");
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonTransitRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/CommonTransitRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonTransitRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -26,7 +26,6 @@
import com.google.common.collect.Sets;
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.ImportType;
-import fr.ifremer.echobase.entities.data.Transect;
import fr.ifremer.echobase.entities.data.TransectDAO;
import fr.ifremer.echobase.entities.data.Transit;
import fr.ifremer.echobase.entities.data.TransitDAO;
@@ -60,8 +59,8 @@
public void setServiceContext(EchoBaseServiceContext serviceContext) {
super.setServiceContext(serviceContext);
- transectDAO = getDAO(Transect.class, TransectDAO.class);
- transitDAO = getDAO(Transit.class, TransitDAO.class);
+ transectDAO = getEchoBasePersistenceContext().getTransectDAO();
+ transitDAO = getEchoBasePersistenceContext().getTransitDAO();
}
@Override
@@ -111,7 +110,7 @@
entity.removeTransit(transit);
// delete it
- delete(transitDAO, transit);
+ transitDAO.delete( transit);
if (log.isDebugEnabled()) {
log.debug(transit.getTopiaId() + " was removed");
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonVoyageRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/CommonVoyageRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/CommonVoyageRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/LegacyVoyageRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/LegacyVoyageRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/LegacyVoyageRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/OperationRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/OperationRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/OperationRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -60,8 +60,8 @@
public void setServiceContext(EchoBaseServiceContext serviceContext) {
super.setServiceContext(serviceContext);
- operationDAO = getDAO(Operation.class, OperationDAO.class);
- transectDAO = getDAO(Transect.class, TransectDAO.class);
+ operationDAO = getEchoBasePersistenceContext().getOperationDAO();
+ transectDAO = getEchoBasePersistenceContext().getTransectDAO();
}
@Override
@@ -84,7 +84,7 @@
transect.removeOperation(operation);
// remove it
- delete(operationDAO, operation);
+ operationDAO.delete( operation);
if (log.isDebugEnabled()) {
log.debug(operation.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultEsduRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/ResultEsduRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultEsduRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -69,7 +69,7 @@
cell.removeResult(result);
// remove result
- delete(resultDAO, result);
+ resultDAO.delete( result);
if (log.isDebugEnabled()) {
log.debug(result.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultMapFishRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/ResultMapFishRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultMapFishRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -70,7 +70,7 @@
voyage.removePostCell(cell);
// remove cell
- delete(cellDAO, cell);
+ cellDAO.delete( cell);
if (log.isDebugEnabled()) {
log.debug(cell.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultMapOtherRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/ResultMapOtherRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultMapOtherRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -70,7 +70,7 @@
voyage.removePostCell(cell);
// remove cell
- delete(cellDAO, cell);
+ cellDAO.delete(cell);
if (log.isDebugEnabled()) {
log.debug(cell.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultRegionRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/ResultRegionRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultRegionRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
@@ -70,7 +70,7 @@
voyage.removePostCell(cell);
// remove cell
- delete(cellDAO, cell);
+ cellDAO.delete(cell);
if (log.isDebugEnabled()) {
log.debug(cell.getTopiaId() + " was removed");
}
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultVoyageRemoveDataStrategy.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/removedata/strategy/ResultVoyageRemoveDataStrategy.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/removedata/strategy/ResultVoyageRemoveDataStrategy.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.removedata.strategy;
+package fr.ifremer.echobase.services.service.removedata.strategy;
/*
* #%L
Added: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java (rev 0)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,311 @@
+package fr.ifremer.echobase.services.service.spatial;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.base.Predicates;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import fr.ifremer.echobase.EchoBaseFunctions;
+import fr.ifremer.echobase.entities.data.Category;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.CellDAO;
+import fr.ifremer.echobase.entities.data.DataAcquisition;
+import fr.ifremer.echobase.entities.data.DataProcessing;
+import fr.ifremer.echobase.entities.data.Echotype;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.data.ResultDAO;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.entities.references.Species;
+import fr.ifremer.echobase.entities.spatial.CellPoint;
+import fr.ifremer.echobase.entities.spatial.SpatialConfiguration;
+import fr.ifremer.echobase.entities.spatial.SpatialData;
+import fr.ifremer.echobase.entities.spatial.SpatialDataCache;
+import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.decorator.Decorator;
+import org.nuiton.topia.persistence.TopiaEntities;
+import org.nuiton.util.TimeLog;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class SpatialService extends EchoBaseServiceSupport {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(SpatialService.class);
+
+ public static final TimeLog TILE_LOG = new TimeLog(SpatialService.class);
+
+ public Map<String, String> getDataMetadatas(Voyage voyage) {
+
+ Map<String, String> result = Maps.newLinkedHashMap();
+
+ DecoratorService service = getDecoratorService();
+
+ Decorator<DataMetadata> decorator = service.getDecorator(getLocale(), DataMetadata.class, null);
+
+ addResult(voyage.getPostCell(), result, decorator);
+
+ if (!voyage.isTransitEmpty()) {
+
+ for (Transit transit : voyage.getTransit()) {
+
+ if (!transit.isTransectEmpty()) {
+ for (Transect transect : transit.getTransect()) {
+
+
+ if (!transect.isDataAcquisitionEmpty()) {
+
+ for (DataAcquisition dataAcquisition : transect.getDataAcquisition()) {
+
+
+ if (!dataAcquisition.isDataProcessingEmpty()) {
+ for (DataProcessing dataProcessing : dataAcquisition.getDataProcessing()) {
+
+ addResult(dataProcessing.getCell(), result, decorator);
+
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ public Set<SpatialData> getSpatialData(SpatialConfiguration model) {
+
+ SpatialDataCache cache = getSpatialDataCache();
+
+ Set<SpatialData> result = cache.get(model);
+
+ if (result == null) {
+
+ String voyageId = model.getVoyageId();
+
+ String dataMetadataId = model.getDataMetadataId();
+
+ String speciesId = model.getSpeciesId();
+ String echotypeId = model.getEchotypeId();
+
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class, voyageId);
+
+ Preconditions.checkNotNull(
+ voyage,
+ "Could not find voyage with id " + voyageId);
+
+ DataMetadata dataMetadata =
+ getEchoBasePersistenceContext().getEntityById(DataMetadata.class, dataMetadataId);
+
+ Preconditions.checkNotNull(
+ dataMetadata,
+ "Could not find dataMetadata with id " + dataMetadataId);
+
+ Species species =
+ getEchoBasePersistenceContext().getEntityOrNullById(Species.class, speciesId);
+
+ Echotype echotype =
+ getEchoBasePersistenceContext().getEntityOrNullById(Echotype.class, echotypeId);
+
+ List<Predicate<Category>> predicates = Lists.newArrayList();
+ if (species != null) {
+ predicates.add(newSpeciesCategoryPredicate(species));
+ }
+ if (echotype != null) {
+ predicates.add(newEchotypeCategoryPredicate(echotype));
+ }
+
+ Predicate<Category> acceptPredicate = Predicates.or(predicates);
+
+ result = getSpatialData(voyage, dataMetadata, acceptPredicate);
+
+ cache.put(model, result);
+ }
+
+ return result;
+ }
+
+ protected Set<SpatialData> getSpatialData(Voyage voyage,
+ DataMetadata requiredDataMetadata,
+ Predicate<Category> acceptPredicate) {
+
+ long s0 = TimeLog.getTime();
+
+ // get possible category
+ List<String> categoryIds = Lists.newArrayList(
+ Iterables.transform(
+ Iterables.filter(
+ getEchoBasePersistenceContext().getCategoryDAO(),
+ acceptPredicate),
+ TopiaEntities.GET_TOPIA_ID));
+
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
+ ResultDAO resultDao = getEchoBasePersistenceContext().getResultDAO();
+
+ boolean filterByCategory = CollectionUtils.isNotEmpty(categoryIds);
+
+ // get all cell with spatial points
+ List<CellPoint> voyageCellPoints = dao.getVoyageCellPoints(voyage);
+
+ int nbCells = voyageCellPoints.size();
+ s0 = TILE_LOG.log(s0, String.format("Get cell points (%s)", nbCells));
+
+ final Map<String, CellPoint> cellPointById = Maps.uniqueIndex(voyageCellPoints, EchoBaseFunctions.CELL_POINT_CELL_ID_FUNCTION);
+
+ Set<String> cellIds = Sets.newHashSet(cellPointById.keySet());
+
+ s0 = TILE_LOG.log(s0, String.format("Get cell points list and map (%s)", nbCells));
+
+ String query = resultDao.createSimpleQuery(null) + " WHERE cell.id IN :cell AND dataMetadata = :dataMetadata";
+
+ List<Result> results;
+
+ if (filterByCategory) {
+ results = resultDao.findAllByQuery(
+ query + " AND category.id IN :category",
+ Result.PROPERTY_CELL, cellIds,
+ Result.PROPERTY_DATA_METADATA, requiredDataMetadata,
+ Result.PROPERTY_CATEGORY, categoryIds);
+ } else {
+ results = resultDao.findAllByQuery(
+ query + " AND category IS NULL",
+ Result.PROPERTY_CELL, cellIds,
+ Result.PROPERTY_DATA_METADATA, requiredDataMetadata);
+ }
+
+
+ s0 = TILE_LOG.log(s0, String.format("Get all matching results (%s)", results.size()));
+
+ Set<SpatialData> result = Sets.newHashSet(
+ Iterables.transform(
+ results, new Function<Result, SpatialData>() {
+ @Override
+ public SpatialData apply(Result input) {
+ SpatialData data = new SpatialData();
+ data.setResult(input);
+ CellPoint cellPoint = cellPointById.get(input.getCell().getTopiaId());
+ data.setPoint(cellPoint);
+ return data;
+ }
+ }));
+
+ s0 = TILE_LOG.log(s0, String.format("Loaded %s result of cell points (%s)", result.size(), nbCells));
+
+ return result;
+ }
+
+
+ protected Predicate<Category> newSpeciesCategoryPredicate(final Species species) {
+ Predicate<Category> speciesPredicate = new Predicate<Category>() {
+ @Override
+ public boolean apply(Category input) {
+ return input.getSpeciesCategory() != null && species.equals(input.getSpeciesCategory().getSpecies());
+ }
+ };
+ return speciesPredicate;
+ }
+
+ protected Predicate<Category> newEchotypeCategoryPredicate(final Echotype echotype) {
+ Predicate<Category> speciesPredicate = new Predicate<Category>() {
+ @Override
+ public boolean apply(Category input) {
+ return echotype.equals(input.getEchotype());
+ }
+ };
+ return speciesPredicate;
+ }
+
+ protected void addResult(Collection<Cell> cells,
+ Map<String, String> result,
+ Decorator<DataMetadata> decorator) {
+
+ if (CollectionUtils.isNotEmpty(cells)) {
+ for (Cell cell : cells) {
+ if (!cell.isResultEmpty()) {
+
+ for (Result result1 : cell.getResult()) {
+
+ DataMetadata dataMetadata = result1.getDataMetadata();
+ String key = dataMetadata.getTopiaId();
+ if (!result.containsKey(key)) {
+ String value = decorator.toString(dataMetadata);
+ result.put(key, value);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ public boolean isSpatialAware() {
+ boolean result = getEchoBasePersistenceContext().isSpatialAware();
+ return result;
+ }
+
+ /**
+ * To update the {@code echobase_cell_spatial} table from the filled
+ * table {@code echobase_cell_sptaial_temp}.
+ *
+ * @since 2.2
+ */
+ public void updatePostgisTable() {
+
+ if (isSpatialAware()) {
+
+ // try the update only for postgresql
+ try {
+ if (log.isInfoEnabled()) {
+ log.info("Will try to compute spatial data from temp table...");
+ }
+ getEchoBasePersistenceContext().executeSQL("SELECT echobase_fill_cell_spatial_table();");
+ getEchoBasePersistenceContext().commitTransaction();
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("Could not compute spatial data", e);
+ }
+ }
+ }
+ }
+}
Property changes on: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/spatial/SpatialService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationAlreadyExistException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/workingDb/WorkingDbConfigurationAlreadyExistException.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationAlreadyExistException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.workingDb;
+package fr.ifremer.echobase.services.service.workingDb;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationNotFoundException.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/workingDb/WorkingDbConfigurationNotFoundException.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationNotFoundException.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.workingDb;
+package fr.ifremer.echobase.services.service.workingDb;
/*
* #%L
Modified: trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationService.java
===================================================================
--- trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/workingDb/WorkingDbConfigurationService.java 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/echobase-services/src/main/java/fr/ifremer/echobase/services/service/workingDb/WorkingDbConfigurationService.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,4 +1,4 @@
-package fr.ifremer.echobase.services.workingDb;
+package fr.ifremer.echobase.services.service.workingDb;
/*
* #%L
@@ -78,7 +78,7 @@
WorkingDbConfiguration result = getDAO().create(conf);
- commitInternalTransaction("Could not create working db configuration");
+ getEchoBaseInternalPersistenceContext().commitTransaction();
return result;
} catch (TopiaException eee) {
throw new EchoBaseTechnicalException(eee);
@@ -89,7 +89,7 @@
try {
WorkingDbConfiguration entity = getExistingConf(id);
getDAO().delete(entity);
- commitInternalTransaction("Could not delete working db configuration");
+ getEchoBaseInternalPersistenceContext().commitTransaction();
} catch (TopiaException eee) {
throw new EchoBaseTechnicalException(eee);
}
@@ -129,8 +129,7 @@
}
protected WorkingDbConfiguration getExistingConf(String id) throws WorkingDbConfigurationNotFoundException {
- WorkingDbConfiguration entity =
- getEntityById(WorkingDbConfiguration.class, id);
+ WorkingDbConfiguration entity = getDAO().findByTopiaId(id);
if (entity == null) {
throw new WorkingDbConfigurationNotFoundException();
}
@@ -138,7 +137,6 @@
}
protected WorkingDbConfigurationDAO getDAO() {
- return getDAO(WorkingDbConfiguration.class,
- WorkingDbConfigurationDAO.class);
+ return getEchoBaseInternalPersistenceContext().getWorkingDbConfigurationDAO();
}
}
\ No newline at end of file
Deleted: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/DecoratorServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/DecoratorServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/DecoratorServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,74 +0,0 @@
-/*
- * #%L
- * EchoBase :: Entities
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services;
-
-import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import org.junit.Assert;
-import org.junit.Test;
-import org.nuiton.decorator.Decorator;
-
-import java.util.List;
-import java.util.Locale;
-
-/**
- * To test the {@link DecoratorService}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class DecoratorServiceTest extends EchoBaseTestServiceSupport {
-
- @Override
- protected FakeEchoBaseServiceContext initContext() {
- return new FakeEchoBaseServiceContext(null);
- }
-
- @Test
- public void getDecoratorForReferences() throws Exception {
- Locale locale = serviceContext.getLocale();
- DecoratorService service = getService(DecoratorService.class);
- List<EchoBaseEntityEnum> expectedTypes = serviceContext.getDbMeta().getReferenceTypes();
-
- for (EchoBaseEntityEnum type : expectedTypes) {
- Decorator<?> decorator =
- service.getDecorator(locale, type.getContract(), null);
- Assert.assertNotNull("Missing decorator for type : " + type, decorator);
- }
- }
-
- @Test
- public void getDecoratorForData() throws Exception {
- Locale locale = serviceContext.getLocale();
- DecoratorService service = getService(DecoratorService.class);
- List<EchoBaseEntityEnum> expectedTypes =
- serviceContext.getDbMeta().getDataTypes();
-
- for (EchoBaseEntityEnum type : expectedTypes) {
- Decorator<?> decorator =
- service.getDecorator(locale, type.getContract(), null);
- Assert.assertNotNull("Missing decorator for type : " + type, decorator);
- }
- }
-
-}
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/EchoBaseTestServiceSupport.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/EchoBaseTestServiceSupport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/EchoBaseTestServiceSupport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -31,14 +31,14 @@
import fr.ifremer.echobase.entities.data.Transit;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.exportdb.ExportDbConfiguration;
-import fr.ifremer.echobase.services.exportdb.ExportDbMode;
-import fr.ifremer.echobase.services.exportdb.ExportDbService;
-import fr.ifremer.echobase.services.importdata.EchoBaseCsvFileImportResult;
-import fr.ifremer.echobase.services.importdata.ImportException;
-import fr.ifremer.echobase.services.importdb.ImportDbConfiguration;
-import fr.ifremer.echobase.services.importdb.ImportDbMode;
-import fr.ifremer.echobase.services.importdb.ImportDbService;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbConfiguration;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbMode;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbService;
+import fr.ifremer.echobase.services.service.importdata.EchoBaseCsvFileImportResult;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdb.ImportDbConfiguration;
+import fr.ifremer.echobase.services.service.importdb.ImportDbMode;
+import fr.ifremer.echobase.services.service.importdb.ImportDbService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
@@ -213,7 +213,7 @@
protected <E extends TopiaEntity> void assertNbEntities(Class<E> entityType,
int expectedNumber) throws TopiaException {
- long count = getDAO(entityType).count();
+ long count = getEchoBasePersistenceContext().getDAO(entityType).count();
Assert.assertEquals(count, expectedNumber);
}
@@ -224,14 +224,14 @@
}
protected String getVoyageId() {
- Voyage voyage = getEntities(Voyage.class).get(0);
+ Voyage voyage = getEchoBasePersistenceContext().getVoyageDAO().findAll().get(0);
Preconditions.checkNotNull(voyage);
return voyage.getTopiaId();
}
protected String getTransitId(String voyageId) {
Preconditions.checkNotNull(voyageId);
- Voyage voyage = getEntityById(Voyage.class, voyageId);
+ Voyage voyage = getEchoBasePersistenceContext().getVoyageDAO().findByTopiaId(voyageId);
Preconditions.checkArgument(!voyage.isTransitEmpty());
List<Transit> transits = voyage.getTransit();
Transit transit = transits.get(0);
@@ -239,14 +239,14 @@
}
protected String getDataProcessingId() {
- DataProcessing dataProcessing = getEntities(DataProcessing.class).get(0);
+ DataProcessing dataProcessing = getEchoBasePersistenceContext().getDataProcessingDAO().findAll().get(0);
Preconditions.checkNotNull(dataProcessing);
return dataProcessing.getTopiaId();
}
protected void importdb(ImportDbMode mode, String path) throws IOException, ImportException {
- ImportDbService service = getService(ImportDbService.class);
+ ImportDbService service = getImportDbService();
ImportDbConfiguration conf = new ImportDbConfiguration(getLocale());
@@ -266,7 +266,7 @@
protected void exportDb(Voyage voyage, String exportFilename) throws IOException {
- ExportDbService service = getService(ExportDbService.class);
+ ExportDbService service = getExportDbService();
ExportDbConfiguration conf = new ExportDbConfiguration();
conf.setVoyageIds(new String[]{voyage.getTopiaId()});
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FakeEchoBaseServiceContext.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FakeEchoBaseServiceContext.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FakeEchoBaseServiceContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,9 +24,12 @@
package fr.ifremer.echobase.services;
import com.google.common.base.Preconditions;
-import fr.ifremer.echobase.EchoBaseConfiguration;
-import fr.ifremer.echobase.EchoBaseConfigurationOption;
import fr.ifremer.echobase.EchoBaseTechnicalException;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfigurationOption;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.entities.spatial.SpatialDataCache;
import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
import fr.ifremer.echobase.persistence.JdbcConfiguration;
@@ -37,13 +40,14 @@
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.util.FileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
@@ -66,24 +70,20 @@
protected final String initDb;
- protected final DefaultEchoBaseServiceContext.ServiceFactory serviceFactory;
-
protected TopiaContext rootContext;
- protected TopiaContext internalTransaction;
-
- protected TopiaContext transaction;
-
protected Date fakeCurrentTime;
protected File testDir;
+ protected TopiaEchoBasePersistenceContext echoBasePersistenceContext;
+
+ protected TopiaEchoBaseInternalPersistenceContext echoBaseInternalPersistenceContext;
+
protected EchoBaseConfiguration configuration;
public FakeEchoBaseServiceContext(String initDb) {
this.initDb = initDb;
- this.serviceFactory =
- new DefaultEchoBaseServiceContext.ServiceFactory();
}
protected File getTestSpecificDirectory(Description description) {
@@ -143,12 +143,15 @@
}
}
+ // init configuration
+
Properties defaultProps = new Properties();
defaultProps.put(EchoBaseConfigurationOption.DATA_DIRECTORY.getKey(), testDir);
configuration = new EchoBaseConfiguration(defaultProps);
JdbcConfiguration dbConf = JdbcConfiguration.newEmbeddedConfig(testDir);
rootContext = EchobaseTopiaContexts.newWorkingDb(dbConf);
+
}
@Override
@@ -159,32 +162,42 @@
}
}
- /** May be used in test to get a fresh transaction. */
@Override
- public TopiaContext getTransaction() {
- if (transaction == null) {
- transaction = rootContext.beginTransaction();
+ public TopiaEchoBasePersistenceContext getEchoBasePersistenceContext() {
+ if (echoBasePersistenceContext == null) {
+ echoBasePersistenceContext =
+ new TopiaEchoBasePersistenceContext(rootContext.beginTransaction());
}
- return transaction;
+ return echoBasePersistenceContext;
}
- public TopiaContext getInternalTransaction() {
- return internalTransaction;
+ @Override
+ public void setEchoBasePersistenceContext(TopiaEchoBasePersistenceContext echoBasePersistenceContext) {
+ this.echoBasePersistenceContext = echoBasePersistenceContext;
}
- public void setInternalTransaction(TopiaContext internalTransaction) {
- this.internalTransaction = internalTransaction;
+ @Override
+ public TopiaEchoBaseInternalPersistenceContext getEchoBaseInternalPersistenceContext() {
+ return echoBaseInternalPersistenceContext;
}
- public TopiaContext newTransaction() throws TopiaException {
- return rootContext.beginTransaction();
+ @Override
+ public void setEchoBaseInternalPersistenceContext(TopiaEchoBaseInternalPersistenceContext echoBaseInternalPersistenceContext) {
+ this.echoBaseInternalPersistenceContext = echoBaseInternalPersistenceContext;
}
@Override
- public void setTransaction(TopiaContext transaction) {
+ public String getWorkgingDbUrl() {
+ String result = rootContext.getConfig().getProperty(TopiaContextFactory.CONFIG_URL);
+ return result;
}
@Override
+ public SpatialDataCache getSpatialDataCache() {
+ return null;
+ }
+
+ @Override
public Locale getLocale() {
return Locale.FRANCE;
}
@@ -200,8 +213,24 @@
}
@Override
- public final <E extends EchoBaseService> E getService(Class<E> serviceClass) {
- return serviceFactory.getService(serviceClass, this);
+ public <S extends EchoBaseService> S newService(Class<S> serviceClass) {
+ // instantiate service using empty constructor
+ S service;
+ try {
+ service = serviceClass.getConstructor().newInstance();
+ } catch (InstantiationException e) {
+ throw new EchoBaseTechnicalException(e);
+ } catch (IllegalAccessException e) {
+ throw new EchoBaseTechnicalException(e);
+ } catch (InvocationTargetException e) {
+ throw new EchoBaseTechnicalException(e);
+ } catch (NoSuchMethodException e) {
+ throw new EchoBaseTechnicalException(e);
+ }
+
+ service.setServiceContext(this);
+
+ return service;
}
@Override
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FixCellsIT.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FixCellsIT.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/FixCellsIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -28,11 +28,10 @@
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.Data;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.entities.references.Mission;
-import fr.ifremer.echobase.services.importdata.AcousticImportConfiguration;
-import fr.ifremer.echobase.services.importdata.AcousticImportService;
-import fr.ifremer.echobase.services.importdata.CellPositionReference;
-import fr.ifremer.echobase.services.importdata.ImportException;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportService;
+import fr.ifremer.echobase.services.service.importdata.CellPositionReference;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
@@ -164,7 +163,7 @@
System.gc();
- AcousticImportService service = getService(AcousticImportService.class);
+ AcousticImportService service = newService(AcousticImportService.class);
// AcousticImportService.POSSIBLE_YEARS.clear();
//
@@ -181,7 +180,7 @@
protected void fixCellDatas() throws TopiaException, ParseException {
int nb = 0;
- TopiaDAO<Cell> cellDAO = getDAO(Cell.class);
+ TopiaDAO<Cell> cellDAO = getEchoBasePersistenceContext().getCellDAO();
long nbCells = cellDAO.count();
for (Cell cell : cellDAO) {
@@ -206,23 +205,24 @@
if (log.isInfoEnabled()) {
log.info("Flush at " + nb + "/" + nbCells);
}
- flushTransaction("Do flush");
+ getEchoBasePersistenceContext().flush();
}
}
- commitTransaction("Do commit!");
+ getEchoBasePersistenceContext().commitTransaction();
}
private void exportDatabase() throws TopiaException, IOException {
- TopiaDAO<Voyage> voyageDAO = getDAO(Voyage.class);
+ TopiaDAO<Voyage> voyageDAO = getEchoBasePersistenceContext().getVoyageDAO();
Voyage voyage;
if (voyageDAO.count() == 0) {
// crate voyage
- voyage = voyageDAO.create(Voyage.PROPERTY_MISSION, getEntities(Mission.class).get(0),
+
+ voyage = voyageDAO.create(Voyage.PROPERTY_MISSION, getEchoBasePersistenceContext().getMissionDAO().findAll().get(0),
Voyage.PROPERTY_NAME, "name",
Voyage.PROPERTY_START_DATE, newDate(),
Voyage.PROPERTY_END_DATE, newDate(),
@@ -232,12 +232,12 @@
Voyage.PROPERTY_DATUM, "datum"
);
- commitTransaction("Do commit!");
+ getEchoBasePersistenceContext().commitTransaction();
} else {
voyage = voyageDAO.findAll().get(0);
}
- commitTransaction("Do commit!");
+ getEchoBasePersistenceContext().commitTransaction();
exportDb(voyage, "fixCells");
Deleted: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationServiceIT.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationServiceIT.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,72 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.embeddedapplication;
-
-import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
-import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationConfiguration;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationService;
-import org.apache.commons.io.FileUtils;
-import org.junit.Assert;
-import org.junit.Test;
-import org.nuiton.util.FileUtil;
-
-import java.io.File;
-
-/**
- * Test {@link EmbeddedApplicationService}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.2
- */
-public class EmbeddedApplicationServiceIT extends EchoBaseTestServiceSupport {
-
- protected FakeEchoBaseServiceContext initContext() {
- return new FakeEchoBaseServiceContext(
- fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
- }
-
- @Test
- public void testCreateEmbeddedApplication() throws Exception {
- EmbeddedApplicationConfiguration conf = new EmbeddedApplicationConfiguration();
- conf.setVoyageIds(new String[]{getVoyageId()});
-
- File workingDirectory = new File(getTestDir(), "work-dir");
- FileUtil.createDirectoryIfNecessary(workingDirectory);
- conf.setWorkingDirectory(workingDirectory);
- File warLocation = new File(workingDirectory, "echobase.war");
- FileUtils.write(warLocation, "dummy!");
- conf.setWarLocation(warLocation);
- conf.setFileName("echobase");
- EmbeddedApplicationService service =
- getService(EmbeddedApplicationService.class);
-
- File zipFile = service.createEmbeddedApplication(conf);
-
- Assert.assertTrue(zipFile.exists());
- Assert.assertEquals(100f, conf.getProgress(), 1);
-
- // TODO Test that embedded db has exactly same number of data than in incoming db
- }
-}
Deleted: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportdb/ExportDbServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportdb/ExportDbServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportdb/ExportDbServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,304 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportdb;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.entities.data.Category;
-import fr.ifremer.echobase.entities.data.Cell;
-import fr.ifremer.echobase.entities.data.Data;
-import fr.ifremer.echobase.entities.data.DataAcquisition;
-import fr.ifremer.echobase.entities.data.DataProcessing;
-import fr.ifremer.echobase.entities.data.Result;
-import fr.ifremer.echobase.entities.data.Transect;
-import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.entities.references.AcousticInstrument;
-import fr.ifremer.echobase.entities.references.CellType;
-import fr.ifremer.echobase.entities.references.DataMetadata;
-import fr.ifremer.echobase.entities.references.Species;
-import fr.ifremer.echobase.entities.references.SpeciesCategory;
-import fr.ifremer.echobase.io.EchoBaseIOUtil;
-import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
-import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Assert;
-import org.junit.Test;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.csv.in.TopiaCsvImports;
-import org.nuiton.topia.persistence.metadata.TableMeta;
-import org.nuiton.util.FileUtil;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Map;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipFile;
-
-/**
- * Test {@link ExportDbService}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
-public class ExportDbServiceTest extends EchoBaseTestServiceSupport {
-
- protected FakeEchoBaseServiceContext initContext() {
- return new FakeEchoBaseServiceContext(
- fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
- }
-
- /** Logger. */
- private static final Log log = LogFactory.getLog(ExportDbServiceTest.class);
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
-
- TopiaDAO<DataProcessing> dataProcessingDAO = getDAO(DataProcessing.class);
- TopiaDAO<DataAcquisition> dataAcquisitionDAO = getDAO(DataAcquisition.class);
- TopiaDAO<Cell> cellDAO = getDAO(Cell.class);
- TopiaDAO<Category> categoryDAO = getDAO(Category.class);
- TopiaDAO<Result> resultDAO = getDAO(Result.class);
- TopiaDAO<SpeciesCategory> speciesCategoryDAO = getDAO(SpeciesCategory.class);
- TopiaDAO<Data> dataDAO = getDAO(Data.class);
-
-
- Voyage voyage = getEntityById(Voyage.class, getVoyageId());
- Assert.assertNotNull(voyage);
-
- Transect transect = voyage.getTransit().get(0).getTransect().get(0);
- Assert.assertNotNull(transect);
-
- List<AcousticInstrument> acousticInstruments = getEntities(AcousticInstrument.class);
- Assert.assertTrue(CollectionUtils.isNotEmpty(acousticInstruments));
- AcousticInstrument acousticInstrument = acousticInstruments.get(0);
- DataAcquisition dataAcquisition = dataAcquisitionDAO.create(
- DataAcquisition.PROPERTY_ACOUSTIC_INSTRUMENT, acousticInstrument
- );
- transect.addDataAcquisition(dataAcquisition);
- DataProcessing dataProcessing = dataProcessingDAO.create(
- DataProcessing.PROPERTY_ID, "id",
- DataProcessing.PROPERTY_PROCESSING_TEMPLATE, "processingtemplate"
- );
- dataAcquisition.addDataProcessing(dataProcessing);
-
- List<Species> speciesList = getEntities(Species.class);
- Assert.assertTrue(CollectionUtils.isNotEmpty(speciesList));
- Species species = speciesList.get(0);
-
- List<DataMetadata> dataMetadatas = getEntities(DataMetadata.class);
- Assert.assertTrue(CollectionUtils.isNotEmpty(dataMetadatas));
- DataMetadata dataMetadata = dataMetadatas.get(0);
-
- SpeciesCategory speciesCategory = speciesCategoryDAO.create(
- SpeciesCategory.PROPERTY_SPECIES, species
- );
-
- Category category = categoryDAO.create(
- Category.PROPERTY_SPECIES_CATEGORY, speciesCategory
- );
-
- List<CellType> cellTypes = getEntities(CellType.class);
- Assert.assertTrue(CollectionUtils.isNotEmpty(cellTypes));
- CellType cellType = cellTypes.get(0);
-
- Cell cell = cellDAO.create(
- Cell.PROPERTY_NAME, "cellName",
- Cell.PROPERTY_CELL_TYPE, cellType
- );
- if (log.isInfoEnabled()) {
- log.info("cell:" + cell.getTopiaId());
- }
- dataProcessing.addCell(cell);
-
- Data cellData = dataDAO.create(
- Data.PROPERTY_DATA_METADATA, dataMetadata,
- Data.PROPERTY_DATA_VALUE, "cellDataValue"
- );
- cell.addData(cellData);
- Result cellResult = resultDAO.create(
- Result.PROPERTY_CATEGORY, category,
- Result.PROPERTY_DATA_METADATA, dataMetadata,
- Result.PROPERTY_RESULT_LABEL, "cellResultLabel",
- Result.PROPERTY_RESULT_VALUE, "cellResultValue"
- );
- cell.addResult(cellResult);
-
- Cell childCell = cellDAO.create(
- Cell.PROPERTY_NAME, "childCell",
- Cell.PROPERTY_CELL_TYPE, cellType
- );
- cell.addChilds(childCell);
-
- Data childCellData = dataDAO.create(
- Data.PROPERTY_DATA_METADATA, dataMetadata,
- Data.PROPERTY_DATA_VALUE, "childCellDataValue"
- );
- childCell.addData(childCellData);
-
- Result childCellResult = resultDAO.create(
- Result.PROPERTY_CATEGORY, category,
- Result.PROPERTY_DATA_METADATA, dataMetadata,
- Result.PROPERTY_RESULT_LABEL, "childCellResultLabel",
- Result.PROPERTY_RESULT_VALUE, "childCellResultValue"
- );
- childCell.addResult(childCellResult);
-
- Cell postCell = cellDAO.create(
- Cell.PROPERTY_NAME, "postCellcellName",
- Cell.PROPERTY_CELL_TYPE, cellType
- );
-
- postCell.addChilds(cell);
- voyage.addPostCell(postCell);
-
-
- Data postCellData = dataDAO.create(
- Data.PROPERTY_DATA_METADATA, dataMetadata,
- Data.PROPERTY_DATA_VALUE, "postCellDataValue"
- );
- postCell.addData(postCellData);
-
- Result postCellResult = resultDAO.create(
- Result.PROPERTY_CATEGORY, category,
- Result.PROPERTY_DATA_METADATA, dataMetadata,
- Result.PROPERTY_RESULT_LABEL, "postCellResultLabel",
- Result.PROPERTY_RESULT_VALUE, "postCellResultValue"
- );
- postCell.addResult(postCellResult);
-
- commitTransaction("Create cells");
- }
-
- @Test
- public void exportReferential() throws IOException {
-
- ExportDbService service = getService(ExportDbService.class);
-
- ExportDbConfiguration conf = new ExportDbConfiguration();
-
- File workingDirectory = new File(getTestDir(), "work-dir");
- FileUtil.createDirectoryIfNecessary(workingDirectory);
- conf.setWorkingDirectory(workingDirectory);
- conf.setFileName("echobase-referential");
- conf.setComputeSteps(true);
- conf.setExportDbMode(ExportDbMode.REFERENTIAL);
- service.doExport(conf);
- File exportFile = conf.getExportFile();
- Assert.assertNotNull(exportFile);
- Assert.assertTrue(exportFile.exists());
-
- // check all tables (referential) where exported
- ZipFile zipFile = new ZipFile(exportFile);
-
- Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables =
- TopiaCsvImports.discoverEntries(
- "echobase/", getDbMeta().getReferenceTables(),
- zipFile, Lists.<String>newArrayList());
-
- checkAllTablesExported(zipFile, tables);
- }
-
- @Test
- public void exportReferentialAndData() throws IOException {
-
- ExportDbService service = getService(ExportDbService.class);
-
- ExportDbConfiguration conf = new ExportDbConfiguration();
-
- conf.setVoyageIds(new String[]{getVoyageId()});
-
- File workingDirectory = new File(getTestDir(), "work-dir");
- FileUtil.createDirectoryIfNecessary(workingDirectory);
- conf.setWorkingDirectory(workingDirectory);
- conf.setFileName("echobase-referentialAndData");
- conf.setComputeSteps(true);
- conf.setExportDbMode(ExportDbMode.REFERENTIAL_AND_DATA);
- service.doExport(conf);
- File exportFile = conf.getExportFile();
- Assert.assertNotNull(exportFile);
- Assert.assertTrue(exportFile.exists());
-
-
- // check all tables (referential + data) where exported
- ZipFile zipFile = new ZipFile(exportFile);
-
- Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables =
- TopiaCsvImports.discoverEntries(
- "echobase/", getDbMeta().getAllTables(),
- zipFile, Lists.<String>newArrayList());
-
- checkAllTablesExported(zipFile, tables);
- }
-
- @Test
- public void exportAll() throws IOException {
-
- ExportDbService service = getService(ExportDbService.class);
-
- ExportDbConfiguration conf = new ExportDbConfiguration();
- conf.setVoyageIds(new String[]{getVoyageId()});
-
- File workingDirectory = new File(getTestDir(), "work-dir");
- FileUtil.createDirectoryIfNecessary(workingDirectory);
- conf.setWorkingDirectory(workingDirectory);
- conf.setFileName("echobase-all");
- conf.setComputeSteps(true);
- conf.setExportDbMode(ExportDbMode.ALL);
- service.doExport(conf);
- File exportFile = conf.getExportFile();
- Assert.assertNotNull(exportFile);
- Assert.assertTrue(exportFile.exists());
-
-
- // check all tables (referential + data) where exported
- ZipFile zipFile = new ZipFile(exportFile);
-
- Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables =
- TopiaCsvImports.discoverEntries(
- "echobase/", getDbMeta().getAllTables(),
- zipFile, Lists.<String>newArrayList());
-
- checkAllTablesExported(zipFile, tables);
- }
-
- private void checkAllTablesExported(ZipFile zipFile, Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables) throws IOException {
- for (Map.Entry<TableMeta<EchoBaseEntityEnum>, ZipEntry> entry : tables.entrySet()) {
- TableMeta<EchoBaseEntityEnum> type = entry.getKey();
- if (type.getSource() == EchoBaseEntityEnum.Gear) {
- // there is some extra lines so can not count from here...
- //FIXME should use a csv import to read entries nstead
- continue;
- }
- ZipEntry zipEntry = entry.getValue();
- long nbCells = EchoBaseIOUtil.countLines(zipFile, Sets.newHashSet(zipEntry));
- Assert.assertEquals(1 + getEntities(type.getEntityType()).size(), nbCells);
- }
- }
-
-}
Deleted: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportquery/ExportQueryServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportquery/ExportQueryServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportquery/ExportQueryServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,73 +0,0 @@
-/*
- * #%L
- * EchoBase :: Services
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 - 2012 Ifremer, Codelutin
- * %%
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- * #L%
- */
-package fr.ifremer.echobase.services.exportquery;
-
-import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
-import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * To test {@link ExportQueryService}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 0.3
- */
-public class ExportQueryServiceTest extends EchoBaseTestServiceSupport {
- @Override
- protected FakeEchoBaseServiceContext initContext() {
- return new FakeEchoBaseServiceContext(null);
- }
-
- ExportQueryService service;
-
- @Before
- public void setup() {
- service = getService(ExportQueryService.class);
- }
-
- @Ignore
- @Test
- public void processLibreOfficeSqlQuery() throws Exception {
-
- processLibreOfficeSqlQuery("select \"t\".name FROM \"t\" WHERE rien;",
- "select t.name FROM t WHERE rien;");
-
- processLibreOfficeSqlQuery("select \"t\".name, \"s\".name FROM \"t\", \"s\" WHERE rien;",
- "select t.name, s.name FROM t, s WHERE rien;");
-
- processLibreOfficeSqlQuery("select \"t\".name FROM \"t\" WHERE (select \"s\".name FROM \"s\" WHERE rien2);",
- "select t.name FROM t WHERE (select s.name FROM s WHERE rien2);");
- }
-
- protected void processLibreOfficeSqlQuery(String libreOfficeQuery,
- String expected) {
-
- String actual = service.processLibreOfficeSqlQuery(libreOfficeQuery);
- Assert.assertEquals(expected, actual);
- }
-}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/DecoratorServiceTest.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/DecoratorServiceTest.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/DecoratorServiceTest.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/DecoratorServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,76 @@
+/*
+ * #%L
+ * EchoBase :: Entities
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service;
+
+import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
+import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.decorator.Decorator;
+
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * To test the {@link DecoratorService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class DecoratorServiceTest extends EchoBaseTestServiceSupport {
+
+ @Override
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(null);
+ }
+
+ @Test
+ public void getDecoratorForReferences() throws Exception {
+ Locale locale = serviceContext.getLocale();
+ DecoratorService service = getDecoratorService();
+ List<EchoBaseEntityEnum> expectedTypes = serviceContext.getDbMeta().getReferenceTypes();
+
+ for (EchoBaseEntityEnum type : expectedTypes) {
+ Decorator<?> decorator =
+ service.getDecorator(locale, type.getContract(), null);
+ Assert.assertNotNull("Missing decorator for type : " + type, decorator);
+ }
+ }
+
+ @Test
+ public void getDecoratorForData() throws Exception {
+ Locale locale = serviceContext.getLocale();
+ DecoratorService service = getDecoratorService();
+ List<EchoBaseEntityEnum> expectedTypes =
+ serviceContext.getDbMeta().getDataTypes();
+
+ for (EchoBaseEntityEnum type : expectedTypes) {
+ Decorator<?> decorator =
+ service.getDecorator(locale, type.getContract(), null);
+ Assert.assertNotNull("Missing decorator for type : " + type, decorator);
+ }
+ }
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/embeddedapplication/EmbeddedApplicationServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/embeddedapplication/EmbeddedApplicationServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,70 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.embeddedapplication;
+
+import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.apache.commons.io.FileUtils;
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.util.FileUtil;
+
+import java.io.File;
+
+/**
+ * Test {@link EmbeddedApplicationService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class EmbeddedApplicationServiceIT extends EchoBaseTestServiceSupport {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
+ }
+
+ @Test
+ public void testCreateEmbeddedApplication() throws Exception {
+ EmbeddedApplicationConfiguration conf = new EmbeddedApplicationConfiguration();
+ conf.setVoyageIds(new String[]{getVoyageId()});
+
+ File workingDirectory = new File(getTestDir(), "work-dir");
+ FileUtil.createDirectoryIfNecessary(workingDirectory);
+ conf.setWorkingDirectory(workingDirectory);
+ File warLocation = new File(workingDirectory, "echobase.war");
+ FileUtils.write(warLocation, "dummy!");
+ conf.setWarLocation(warLocation);
+ conf.setFileName("echobase");
+ EmbeddedApplicationService service =
+ newService(EmbeddedApplicationService.class);
+
+ File zipFile = service.createEmbeddedApplication(conf);
+
+ Assert.assertTrue(zipFile.exists());
+ Assert.assertEquals(100f, conf.getProgress(), 1);
+
+ // TODO Test that embedded db has exactly same number of data than in incoming db
+ }
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportdb/ExportDbServiceTest.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportdb/ExportDbServiceTest.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportdb/ExportDbServiceTest.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportdb/ExportDbServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,304 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportdb;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
+import fr.ifremer.echobase.entities.data.Category;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.DataAcquisition;
+import fr.ifremer.echobase.entities.data.DataProcessing;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.references.AcousticInstrument;
+import fr.ifremer.echobase.entities.references.CellType;
+import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.entities.references.Species;
+import fr.ifremer.echobase.entities.references.SpeciesCategory;
+import fr.ifremer.echobase.io.EchoBaseIOUtil;
+import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.csv.in.TopiaCsvImports;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.util.FileUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * Test {@link ExportDbService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ExportDbServiceTest extends EchoBaseTestServiceSupport {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
+ }
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(ExportDbServiceTest.class);
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+
+ TopiaDAO<DataProcessing> dataProcessingDAO = getEchoBasePersistenceContext().getDataProcessingDAO();
+ TopiaDAO<DataAcquisition> dataAcquisitionDAO = getEchoBasePersistenceContext().getDataAcquisitionDAO();
+ TopiaDAO<Cell> cellDAO = getEchoBasePersistenceContext().getCellDAO();
+ TopiaDAO<Category> categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ TopiaDAO<Result> resultDAO = getEchoBasePersistenceContext().getResultDAO();
+ TopiaDAO<SpeciesCategory> speciesCategoryDAO = getEchoBasePersistenceContext().getSpeciesCategoryDAO();
+ TopiaDAO<Data> dataDAO = getEchoBasePersistenceContext().getDataDAO();
+
+
+ Voyage voyage = getEchoBasePersistenceContext().getEntityById(Voyage.class, getVoyageId());
+ Assert.assertNotNull(voyage);
+
+ Transect transect = voyage.getTransit().get(0).getTransect().get(0);
+ Assert.assertNotNull(transect);
+
+ List<AcousticInstrument> acousticInstruments = getEchoBasePersistenceContext().getAcousticInstrumentDAO().findAll();
+ Assert.assertTrue(CollectionUtils.isNotEmpty(acousticInstruments));
+ AcousticInstrument acousticInstrument = acousticInstruments.get(0);
+ DataAcquisition dataAcquisition = dataAcquisitionDAO.create(
+ DataAcquisition.PROPERTY_ACOUSTIC_INSTRUMENT, acousticInstrument
+ );
+ transect.addDataAcquisition(dataAcquisition);
+ DataProcessing dataProcessing = dataProcessingDAO.create(
+ DataProcessing.PROPERTY_ID, "id",
+ DataProcessing.PROPERTY_PROCESSING_TEMPLATE, "processingtemplate"
+ );
+ dataAcquisition.addDataProcessing(dataProcessing);
+
+ List<Species> speciesList = getEchoBasePersistenceContext().getSpeciesDAO().findAll();
+ Assert.assertTrue(CollectionUtils.isNotEmpty(speciesList));
+ Species species = speciesList.get(0);
+
+ List<DataMetadata> dataMetadatas = getEchoBasePersistenceContext().getDataMetadataDAO().findAll();
+ Assert.assertTrue(CollectionUtils.isNotEmpty(dataMetadatas));
+ DataMetadata dataMetadata = dataMetadatas.get(0);
+
+ SpeciesCategory speciesCategory = speciesCategoryDAO.create(
+ SpeciesCategory.PROPERTY_SPECIES, species
+ );
+
+ Category category = categoryDAO.create(
+ Category.PROPERTY_SPECIES_CATEGORY, speciesCategory
+ );
+
+ List<CellType> cellTypes = getEchoBasePersistenceContext().getCellTypeDAO().findAll();
+ Assert.assertTrue(CollectionUtils.isNotEmpty(cellTypes));
+ CellType cellType = cellTypes.get(0);
+
+ Cell cell = cellDAO.create(
+ Cell.PROPERTY_NAME, "cellName",
+ Cell.PROPERTY_CELL_TYPE, cellType
+ );
+ if (log.isInfoEnabled()) {
+ log.info("cell:" + cell.getTopiaId());
+ }
+ dataProcessing.addCell(cell);
+
+ Data cellData = dataDAO.create(
+ Data.PROPERTY_DATA_METADATA, dataMetadata,
+ Data.PROPERTY_DATA_VALUE, "cellDataValue"
+ );
+ cell.addData(cellData);
+ Result cellResult = resultDAO.create(
+ Result.PROPERTY_CATEGORY, category,
+ Result.PROPERTY_DATA_METADATA, dataMetadata,
+ Result.PROPERTY_RESULT_LABEL, "cellResultLabel",
+ Result.PROPERTY_RESULT_VALUE, "cellResultValue"
+ );
+ cell.addResult(cellResult);
+
+ Cell childCell = cellDAO.create(
+ Cell.PROPERTY_NAME, "childCell",
+ Cell.PROPERTY_CELL_TYPE, cellType
+ );
+ cell.addChilds(childCell);
+
+ Data childCellData = dataDAO.create(
+ Data.PROPERTY_DATA_METADATA, dataMetadata,
+ Data.PROPERTY_DATA_VALUE, "childCellDataValue"
+ );
+ childCell.addData(childCellData);
+
+ Result childCellResult = resultDAO.create(
+ Result.PROPERTY_CATEGORY, category,
+ Result.PROPERTY_DATA_METADATA, dataMetadata,
+ Result.PROPERTY_RESULT_LABEL, "childCellResultLabel",
+ Result.PROPERTY_RESULT_VALUE, "childCellResultValue"
+ );
+ childCell.addResult(childCellResult);
+
+ Cell postCell = cellDAO.create(
+ Cell.PROPERTY_NAME, "postCellcellName",
+ Cell.PROPERTY_CELL_TYPE, cellType
+ );
+
+ postCell.addChilds(cell);
+ voyage.addPostCell(postCell);
+
+
+ Data postCellData = dataDAO.create(
+ Data.PROPERTY_DATA_METADATA, dataMetadata,
+ Data.PROPERTY_DATA_VALUE, "postCellDataValue"
+ );
+ postCell.addData(postCellData);
+
+ Result postCellResult = resultDAO.create(
+ Result.PROPERTY_CATEGORY, category,
+ Result.PROPERTY_DATA_METADATA, dataMetadata,
+ Result.PROPERTY_RESULT_LABEL, "postCellResultLabel",
+ Result.PROPERTY_RESULT_VALUE, "postCellResultValue"
+ );
+ postCell.addResult(postCellResult);
+
+ getEchoBasePersistenceContext().commitTransaction();
+ }
+
+ @Test
+ public void exportReferential() throws IOException {
+
+ ExportDbService service = getExportDbService();
+
+ ExportDbConfiguration conf = new ExportDbConfiguration();
+
+ File workingDirectory = new File(getTestDir(), "work-dir");
+ FileUtil.createDirectoryIfNecessary(workingDirectory);
+ conf.setWorkingDirectory(workingDirectory);
+ conf.setFileName("echobase-referential");
+ conf.setComputeSteps(true);
+ conf.setExportDbMode(ExportDbMode.REFERENTIAL);
+ service.doExport(conf);
+ File exportFile = conf.getExportFile();
+ Assert.assertNotNull(exportFile);
+ Assert.assertTrue(exportFile.exists());
+
+ // check all tables (referential) where exported
+ ZipFile zipFile = new ZipFile(exportFile);
+
+ Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables =
+ TopiaCsvImports.discoverEntries(
+ "echobase/", getDbMeta().getReferenceTables(),
+ zipFile, Lists.<String>newArrayList());
+
+ checkAllTablesExported(zipFile, tables);
+ }
+
+ @Test
+ public void exportReferentialAndData() throws IOException {
+
+ ExportDbService service = getExportDbService();
+
+ ExportDbConfiguration conf = new ExportDbConfiguration();
+
+ conf.setVoyageIds(new String[]{getVoyageId()});
+
+ File workingDirectory = new File(getTestDir(), "work-dir");
+ FileUtil.createDirectoryIfNecessary(workingDirectory);
+ conf.setWorkingDirectory(workingDirectory);
+ conf.setFileName("echobase-referentialAndData");
+ conf.setComputeSteps(true);
+ conf.setExportDbMode(ExportDbMode.REFERENTIAL_AND_DATA);
+ service.doExport(conf);
+ File exportFile = conf.getExportFile();
+ Assert.assertNotNull(exportFile);
+ Assert.assertTrue(exportFile.exists());
+
+
+ // check all tables (referential + data) where exported
+ ZipFile zipFile = new ZipFile(exportFile);
+
+ Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables =
+ TopiaCsvImports.discoverEntries(
+ "echobase/", getDbMeta().getAllTables(),
+ zipFile, Lists.<String>newArrayList());
+
+ checkAllTablesExported(zipFile, tables);
+ }
+
+ @Test
+ public void exportAll() throws IOException {
+
+ ExportDbService service = getExportDbService();
+
+ ExportDbConfiguration conf = new ExportDbConfiguration();
+ conf.setVoyageIds(new String[]{getVoyageId()});
+
+ File workingDirectory = new File(getTestDir(), "work-dir");
+ FileUtil.createDirectoryIfNecessary(workingDirectory);
+ conf.setWorkingDirectory(workingDirectory);
+ conf.setFileName("echobase-all");
+ conf.setComputeSteps(true);
+ conf.setExportDbMode(ExportDbMode.ALL);
+ service.doExport(conf);
+ File exportFile = conf.getExportFile();
+ Assert.assertNotNull(exportFile);
+ Assert.assertTrue(exportFile.exists());
+
+
+ // check all tables (referential + data) where exported
+ ZipFile zipFile = new ZipFile(exportFile);
+
+ Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables =
+ TopiaCsvImports.discoverEntries(
+ "echobase/", getDbMeta().getAllTables(),
+ zipFile, Lists.<String>newArrayList());
+
+ checkAllTablesExported(zipFile, tables);
+ }
+
+ private void checkAllTablesExported(ZipFile zipFile, Map<TableMeta<EchoBaseEntityEnum>, ZipEntry> tables) throws IOException {
+ for (Map.Entry<TableMeta<EchoBaseEntityEnum>, ZipEntry> entry : tables.entrySet()) {
+ TableMeta<EchoBaseEntityEnum> type = entry.getKey();
+ if (type.getSource() == EchoBaseEntityEnum.Gear) {
+ // there is some extra lines so can not count from here...
+ //FIXME should use a csv import to read entries nstead
+ continue;
+ }
+ ZipEntry zipEntry = entry.getValue();
+ long nbCells = EchoBaseIOUtil.countLines(zipFile, Sets.newHashSet(zipEntry));
+ Assert.assertEquals(1 + getEchoBasePersistenceContext().getDAO(type.getEntityType()).count(), nbCells);
+ }
+ }
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryServiceTest.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/exportquery/ExportQueryServiceTest.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryServiceTest.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/exportquery/ExportQueryServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,72 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.exportquery;
+
+import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * To test {@link ExportQueryService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ExportQueryServiceTest extends EchoBaseTestServiceSupport {
+ @Override
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(null);
+ }
+
+ ExportQueryService service;
+
+ @Before
+ public void setup() {
+ service = getExportQueryService();
+ }
+
+ @Ignore
+ @Test
+ public void processLibreOfficeSqlQuery() throws Exception {
+
+ processLibreOfficeSqlQuery("select \"t\".name FROM \"t\" WHERE rien;",
+ "select t.name FROM t WHERE rien;");
+
+ processLibreOfficeSqlQuery("select \"t\".name, \"s\".name FROM \"t\", \"s\" WHERE rien;",
+ "select t.name, s.name FROM t, s WHERE rien;");
+
+ processLibreOfficeSqlQuery("select \"t\".name FROM \"t\" WHERE (select \"s\".name FROM \"s\" WHERE rien2);",
+ "select t.name FROM t WHERE (select s.name FROM s WHERE rien2);");
+ }
+
+ protected void processLibreOfficeSqlQuery(String libreOfficeQuery,
+ String expected) {
+
+ String actual = service.processLibreOfficeSqlQuery(libreOfficeQuery);
+ Assert.assertEquals(expected, actual);
+ }
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/AbstractImportDataServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AbstractImportDataServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,298 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Sets;
+import fr.ifremer.echobase.EchoBaseFunctions;
+import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.CellDAO;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.DataAcquisition;
+import fr.ifremer.echobase.entities.data.DataProcessing;
+import fr.ifremer.echobase.entities.data.Echotype;
+import fr.ifremer.echobase.entities.data.GearMetadataValue;
+import fr.ifremer.echobase.entities.data.LengthAgeKey;
+import fr.ifremer.echobase.entities.data.LengthWeightKey;
+import fr.ifremer.echobase.entities.data.Operation;
+import fr.ifremer.echobase.entities.data.OperationMetadataValue;
+import fr.ifremer.echobase.entities.data.Sample;
+import fr.ifremer.echobase.entities.data.SampleData;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.references.CellType;
+import fr.ifremer.echobase.entities.references.CellTypeDAO;
+import fr.ifremer.echobase.io.InputFile;
+import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.nuiton.csv.Import;
+import org.nuiton.csv.ext.CsvReaders;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.csv.in.AbstractImportModel;
+import org.nuiton.util.TimeLog;
+
+import java.io.File;
+import java.io.Reader;
+import java.util.List;
+import java.util.Set;
+import java.util.regex.Matcher;
+
+/**
+ * Abstrac import data test.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public abstract class AbstractImportDataServiceIT extends EchoBaseTestServiceSupport {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(AbstractImportDataServiceIT.class);
+
+ public static final TimeLog TIME_LOG = new TimeLog(AbstractImportDataServiceIT.class);
+
+ public void assertImportCommonData() throws TopiaException {
+ assertNbEntities(Voyage.class, fixtures.NB_VOYAGE());
+ assertNbEntities(Transit.class, fixtures.NB_TRANSIT());
+ assertNbEntities(Transect.class, fixtures.NB_TRANSECT());
+ }
+
+ public void assertImportOperations() throws TopiaException {
+ assertNbEntities(Operation.class, fixtures.NB_OPERATION());
+ assertNbEntities(OperationMetadataValue.class, fixtures.NB_OPERATION_METADATAVALUE());
+ assertNbEntities(GearMetadataValue.class, fixtures.NB_GEAR_METADATAVALUE());
+ }
+
+ public void assertImportSampleDatas() throws TopiaException {
+ assertNbEntities(Sample.class, fixtures.NB_SAMPLE());
+ assertNbEntities(SampleData.class, fixtures.NB_SAMPLE_DATA());
+ }
+
+ public void assertImportAcousticDatas() throws TopiaException {
+ assertNbEntities(DataAcquisition.class, fixtures.NB_DATA_ACQUISITION());
+ assertNbEntities(DataProcessing.class, fixtures.NB_DATA_PROCESSING());
+ assertNbEntities(Cell.class, fixtures.NB_CELL());
+ assertNbEntities(Data.class, fixtures.NB_DATA());
+ }
+
+ public void assertImportVoyageResult() throws TopiaException {
+ assertNbEntities(LengthAgeKey.class, fixtures.NB_LENGTH_AGE_KEY());
+ assertNbEntities(LengthWeightKey.class, fixtures.NB_LENGTH_WEIGHT_KEY());
+ assertNbEntities(Echotype.class, fixtures.NB_ECHOTYPE());
+ }
+
+ protected <M extends AbstractImportConfiguration, S extends AbstractImportDataService<M>>
+ List<EchoBaseCsvFileImportResult> doImport(M conf,
+ Class<S> serviceType,
+ int nbResults) throws ImportException {
+
+ S service = newService(serviceType);
+
+ EchoBaseUser fakeUser = createFakeUser();
+
+ long s0 = TimeLog.getTime();
+
+ String resume = service.doImport(conf, fakeUser);
+
+ TIME_LOG.log(s0, "doImport");
+
+ List<EchoBaseCsvFileImportResult> result = conf.getImportResults();
+
+ Assert.assertNotNull(result);
+ Assert.assertEquals(nbResults, result.size());
+ assertConfProgressionToEnd(conf);
+
+ if (log.isInfoEnabled()) {
+ if (log.isInfoEnabled()) {
+ log.info('\n' + resume);
+ }
+ }
+
+ return result;
+ }
+
+// protected <E extends TopiaEntity> E create(TopiaDAO<E> dao,
+// Object... properties) {
+// try {
+// E result = dao.create(properties);
+// return result;
+// } catch (TopiaException e) {
+// throw new EchoBaseTechnicalException("Could not create entity", e);
+// }
+// }
+
+ protected void addMissingEsduCells(String esduColumnName,
+ String voyageId,
+ InputFile inputFile) throws TopiaException {
+
+ ResultsImportService service = newService(ResultsImportService.class);
+ Voyage voyage = getWorkingDbPersistenceService().getVoyageDAO().findByTopiaId(voyageId);
+ Transit transit;
+ Transect transect;
+ DataAcquisition dataAcquisition;
+ DataProcessing dataProcessing;
+
+ if (voyage.isTransitEmpty()) {
+
+ // create a fake transit
+ transit = getEchoBasePersistenceContext().getTransitDAO().create();
+ voyage.addTransit(transit);
+ } else {
+ transit = voyage.getTransit().get(0);
+ }
+
+ if (transit.isTransectEmpty()) {
+
+ // create a fake transect
+ transect = getEchoBasePersistenceContext().getTransectDAO().create();
+ transit.addTransect(transect);
+ } else {
+ transect = transit.getTransect().get(0);
+ }
+
+ if (transect.isDataAcquisitionEmpty()) {
+
+ // create a fake dataAcquisition
+ dataAcquisition = getEchoBasePersistenceContext().getDataAcquisitionDAO().create(
+ DataAcquisition.PROPERTY_ACOUSTIC_INSTRUMENT,
+ getEchoBasePersistenceContext().getAcousticInstrumentDAO().findAll().get(0));
+ transect.addDataAcquisition(dataAcquisition);
+ } else {
+ dataAcquisition = transect.getDataAcquisition().iterator().next();
+ }
+
+ if (dataAcquisition.isDataProcessingEmpty()) {
+
+ // creates a fake dataProcessing
+ dataProcessing = getEchoBasePersistenceContext().getDataProcessingDAO().create(
+ DataProcessing.PROPERTY_ID, "id",
+ DataProcessing.PROPERTY_PROCESSING_TEMPLATE, "pt"
+ );
+ dataAcquisition.addDataProcessing(dataProcessing);
+ } else {
+ dataProcessing = dataAcquisition.getDataProcessing().iterator().next();
+ }
+
+ CellDAO dao = getEchoBasePersistenceContext().getCellDAO();
+
+ Set<String> cellsNames;
+
+ if (dataProcessing.isCellEmpty()) {
+ cellsNames = Sets.newHashSet();
+ } else {
+ cellsNames = Sets.newHashSet(Collections2.transform(
+ dataProcessing.getCell(), EchoBaseFunctions.CELL_BY_NAME));
+ }
+
+ ResultEdsuImportMockImportModel csvModel = new ResultEdsuImportMockImportModel(
+ getCsvSeparator(),
+ esduColumnName,
+ inputFile.getFile());
+
+ CellTypeDAO cellTypeDAO = getEchoBasePersistenceContext().getCellTypeDAO();
+
+ CellType esduCellType = cellTypeDAO.findById("Esdu");
+ Preconditions.checkNotNull(esduCellType);
+
+ Reader reader = service.getInputFileReader(inputFile);
+ try {
+ Import<ResultEdsuImportMockImportModelRow> importer =
+ Import.newImport(csvModel, reader);
+
+ for (ResultEdsuImportMockImportModelRow row : importer) {
+
+ String esduCellId = row.getName();
+
+ if (!cellsNames.contains(esduCellId)) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Adding missing esdu cell with name " +
+ esduCellId);
+ }
+
+ Cell cell = dao.create(Cell.PROPERTY_NAME, esduCellId,
+ Cell.PROPERTY_CELL_TYPE, esduCellType);
+ dataProcessing.addCell(cell);
+ cellsNames.add(esduCellId);
+ }
+ }
+
+ getEchoBasePersistenceContext().flush();
+ } finally {
+
+
+ service.closeReader(reader, inputFile);
+ }
+ }
+
+ public static class ResultEdsuImportMockImportModel extends AbstractImportModel<ResultEdsuImportMockImportModelRow> {
+
+ public ResultEdsuImportMockImportModel(char separator,
+ String esduColumnName,
+ File file) {
+ super(separator);
+
+ newMandatoryColumn(esduColumnName, EchoBaseCsvUtil.CELL_NAME);
+
+ String[] header = CsvReaders.getHeader(file, separator);
+
+ for (String columnHeader : header) {
+
+ if (!esduColumnName.equals(columnHeader) &&
+ !("\"" + esduColumnName + "\"").equals(columnHeader)) {
+ Matcher matcher = AbstractImportDataService.REMOVE_DOUBLE_QUOTES_PATTERN.matcher(columnHeader);
+ if (matcher.matches()) {
+ newIgnoredColumn(matcher.group(1));
+ } else {
+ newIgnoredColumn(columnHeader);
+ }
+ }
+ }
+ }
+
+ @Override
+ public ResultEdsuImportMockImportModelRow newEmptyInstance() {
+ return new ResultEdsuImportMockImportModelRow();
+ }
+ }
+
+ public static class ResultEdsuImportMockImportModelRow {
+
+ protected String name;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AcousticImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/AcousticImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AcousticImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/AcousticImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,99 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.DataAcquisition;
+import fr.ifremer.echobase.entities.data.DataProcessing;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link AcousticImportService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class AcousticImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(fixtures.IMPORT_DATA_ECHOBASE_CATCHES());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "acoustic", filename};
+ }
+
+ @Test
+ public void doImport() throws Exception {
+
+ assertImportCommonData();
+
+ assertNoEntities(DataAcquisition.class,
+ DataProcessing.class,
+ Cell.class,
+ Data.class);
+
+ AcousticImportConfiguration conf =
+ new AcousticImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+ conf.setVesselId(fixtures.VESSEL_ID());
+ conf.setAcousticDensityUnit("acousticDensityUnit");
+ conf.setAcquisitionSoftwareVersionER60("acquisitionSoftwareVersionER60");
+ conf.setAcquisitionSoftwareVersionME70("acquisitionSoftwareVersionME70");
+ conf.setAddDataAcquisition(false);
+ conf.setTransceiverAcquisitionAbsorptionDescription("transceiverAcquisitionAbsorptionDescription");
+ conf.setCellPositionReference(CellPositionReference.START);
+ conf.setDigitThreshold(1.5f);
+ conf.setLoggedDataDatatype("loggedDataDatatype");
+ conf.setLoggedDataFormat("loggedDataFormat");
+ conf.setNotes("notes");
+ conf.setPingDutyCycle("pingDutyCycle");
+ conf.setProcessingDescription("processingDescription");
+ conf.setProcessingTemplate("processingTemplate");
+ conf.setSoundSpeedCalculationsER60("soundSpeedCalculationsER60");
+ conf.setSoundSpeedCalculationsME70("soundSpeedCalculationsME70");
+ conf.setTransceiverAcquisitionAbsorptionDescription("transceiverAcquisitionAbsorptionDescription");
+
+ prepareInputFile(conf.getMoviesFile(), getImportPath("movies.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, AcousticImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_CELL());
+
+ assertCsvImportResult(result, 0, DataAcquisition.class, fixtures.NB_DATA_ACQUISITION());
+ assertCsvImportResult(result, 0, DataProcessing.class, fixtures.NB_DATA_PROCESSING());
+ assertCsvImportResult(result, 0, Cell.class, fixtures.NB_CELL());
+ assertCsvImportResult(result, 0, Data.class, fixtures.NB_DATA());
+
+ assertImportAcousticDatas();
+ }
+
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CatchesImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/CatchesImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CatchesImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CatchesImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,163 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.data.Sample;
+import fr.ifremer.echobase.entities.data.SampleData;
+import fr.ifremer.echobase.entities.references.SpeciesCategory;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link CatchesImportService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class CatchesImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(fixtures.IMPORT_DATA_ECHOBASE_OPERATION());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "catches", filename};
+ }
+
+ @Test
+ public void doImportAllSamples() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertNoEntities(Sample.class, SampleData.class);
+
+ CatchesImportConfiguration conf =
+ new CatchesImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+
+ prepareInputFile(conf.getTotalSampleFile(),
+ getImportPath("totalsample.csv.gz"));
+ prepareInputFile(conf.getSubSampleFile(),
+ getImportPath("subsample.csv.gz"));
+ prepareInputFile(conf.getBiometrySampleFile(),
+ getImportPath("biometrysample.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CatchesImportService.class, 3);
+
+ assertNbIDs(result, 0, fixtures.NB_SAMPLE_TOTAL());
+
+ assertCsvImportResult(result, 0, Sample.class, fixtures.NB_SAMPLE_TOTAL(), 0, fixtures.NB_SAMPLE());
+ assertCsvImportResult(result, 0, SampleData.class, fixtures.NB_SAMPLE_DATA_TOTAL(), 0, fixtures.NB_SAMPLE_DATA());
+ assertCsvImportResult(result, 0, SpeciesCategory.class, 4, 0, 456);
+
+ assertNbIDs(result, 1, fixtures.NB_SAMPLE_UNSORTED());
+ assertCsvImportResult(result, 1, Sample.class, fixtures.NB_SAMPLE_UNSORTED(), 0, fixtures.NB_SAMPLE());
+ assertCsvImportResult(result, 1, SampleData.class, fixtures.NB_SAMPLE_DATA_UNSORTED(), 0, fixtures.NB_SAMPLE_DATA());
+ assertCsvImportResult(result, 1, SpeciesCategory.class, 9, 0, 456);
+
+ assertNbIDs(result, 2, fixtures.NB_SAMPLE_BIOMETRY());
+ assertCsvImportResult(result, 2, Sample.class, fixtures.NB_SAMPLE_BIOMETRY(), 0, fixtures.NB_SAMPLE());
+ assertCsvImportResult(result, 2, SampleData.class, fixtures.NB_SAMPLE_DATA_BIOMETRY(), 0, fixtures.NB_SAMPLE_DATA());
+
+ assertImportSampleDatas();
+ }
+
+ @Ignore
+ @Test
+ public void doImportTotalSample() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertNoEntities(Sample.class, SampleData.class);
+
+ CatchesImportConfiguration conf =
+ new CatchesImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+
+ prepareInputFile(conf.getTotalSampleFile(),
+ getImportPath("totalsample.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CatchesImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_SAMPLE_TOTAL());
+ assertCsvImportResult(result, 0, Sample.class, fixtures.NB_SAMPLE_TOTAL());
+ assertCsvImportResult(result, 0, SampleData.class, fixtures.NB_SAMPLE_DATA_TOTAL());
+ }
+
+ @Ignore
+ @Test
+ public void doImportSubSample() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertNoEntities(Sample.class, SampleData.class);
+
+ CatchesImportConfiguration conf =
+ new CatchesImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+
+ prepareInputFile(conf.getSubSampleFile(),
+ getImportPath("subsample.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CatchesImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_SAMPLE_UNSORTED());
+ assertCsvImportResult(result, 0, Sample.class, fixtures.NB_SAMPLE_UNSORTED());
+ assertCsvImportResult(result, 0, SampleData.class, fixtures.NB_SAMPLE_DATA_UNSORTED());
+ }
+
+ @Ignore
+ @Test
+ public void doImportBiometrySample() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertNoEntities(Sample.class, SampleData.class);
+
+ CatchesImportConfiguration conf =
+ new CatchesImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+
+ prepareInputFile(conf.getBiometrySampleFile(),
+ getImportPath("biometrysample.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CatchesImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_SAMPLE_BIOMETRY());
+ assertCsvImportResult(result, 0, Sample.class, fixtures.NB_SAMPLE_BIOMETRY());
+ assertCsvImportResult(result, 0, SampleData.class, fixtures.NB_SAMPLE_DATA_BIOMETRY());
+ }
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/CommonAllImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonAllImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,95 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link CommonImportService} with {@link ImportType#COMMON_ALL} mode.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class CommonAllImportServiceIT extends AbstractImportDataServiceIT {
+
+ @Override
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_NO_DATA());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "common", filename};
+ }
+
+ @Test
+ public void doImport() throws Exception {
+
+ // no data in db
+
+ assertNoEntities(Voyage.class, Transit.class, Transect.class);
+
+ // import with mode all (voyage / transit / transect)
+
+ CommonImportConfiguration conf =
+ new CommonImportConfiguration(getLocale());
+
+ conf.setAreaOfOperationId(fixtures.AREA_OF_OPERATION_ID());
+ conf.setDatum(fixtures.DATUM());
+ conf.setMissionId(fixtures.MISSION_ID());
+ conf.setTransectBinUnitsPingAxis(fixtures.TRANSECT_BIN_UNITS_PING_AXIS());
+ conf.setTransectGeospatialVerticalPositive(fixtures.TRANSECT_GEOSPATIAL_VERTICLA_POSITIVE());
+ conf.setTransectLicence(fixtures.TRANSECT_LICENSE());
+ conf.setTransitRelatedActivity(fixtures.TRANSIT_RELATED_ACTIVITY());
+ conf.setVoyageDescription(fixtures.VOYAGE_DESCRIPTION());
+
+ prepareInputFile(conf.getVoyageFile(), getImportPath("voyage.csv.gz"));
+ prepareInputFile(conf.getTransitFile(), getImportPath("transit.csv.gz"));
+ prepareInputFile(conf.getTransectFile(), getImportPath("transect.csv.gz"));
+
+ conf.setImportType(ImportType.COMMON_ALL);
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CommonAllImportService.class, 3);
+
+ assertNbIDs(result, 0, fixtures.NB_VOYAGE());
+ assertCsvImportResult(result, 0, Voyage.class, fixtures.NB_VOYAGE());
+
+ assertNbIDs(result, 1, 0);
+ assertCsvImportResult(result, 1, Transit.class, fixtures.NB_TRANSIT());
+
+ assertNbIDs(result, 2, 0);
+ assertCsvImportResult(result, 2, Transect.class, fixtures.NB_TRANSECT());
+
+ assertImportCommonData();
+ }
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/CommonTransectImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransectImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,85 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link CommonImportService} with {@link ImportType#COMMON_TRANSECT} mode.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class CommonTransectImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "common", filename};
+ }
+
+ @Test
+ public void doImport() throws Exception {
+
+ // import common data with mode transect
+
+ assertImportCommonData();
+
+ CommonImportConfiguration conf =
+ new CommonImportConfiguration(getLocale());
+
+ conf.setDatum(fixtures.DATUM());
+ conf.setVoyageId(getVoyageId());
+ conf.setTransectBinUnitsPingAxis(fixtures.TRANSECT_BIN_UNITS_PING_AXIS());
+ conf.setTransectGeospatialVerticalPositive(fixtures.TRANSECT_GEOSPATIAL_VERTICLA_POSITIVE());
+ conf.setTransectLicence(fixtures.TRANSECT_LICENSE());
+
+ prepareInputFile(conf.getTransectFile(), getImportPath("transect.csv.gz"));
+
+ conf.setImportType(ImportType.COMMON_TRANSECT);
+
+ // let's delete every transects
+ for (Transit transit : getEchoBasePersistenceContext().getTransitDAO()) {
+ transit.clearTransect();
+ }
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CommonTransectImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_TRANSECT());
+ assertCsvImportResult(result, 0, Transect.class, fixtures.NB_TRANSECT());
+
+ assertImportCommonData();
+ }
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/CommonTransitImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonTransitImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,89 @@
+package fr.ifremer.echobase.services.service.importdata;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link CommonImportService} with {@link ImportType#COMMON_TRANSIT} mode.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class CommonTransitImportServiceIT extends AbstractImportDataServiceIT {
+
+ @Override
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "common", filename};
+ }
+
+ @Test
+ public void doImport() throws Exception {
+
+ // import common data with mode transit
+
+ assertImportCommonData();
+
+ // let's delete every transits
+ for (Voyage voyage : getEchoBasePersistenceContext().getVoyageDAO()) {
+ voyage.clearTransit();
+ }
+
+ // import common data with mode transit
+
+ CommonImportConfiguration conf =
+ new CommonImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+ conf.setTransitRelatedActivity(fixtures.TRANSIT_RELATED_ACTIVITY());
+
+ prepareInputFile(conf.getTransitFile(), getImportPath("transit.csv.gz"));
+
+ conf.setImportType(ImportType.COMMON_TRANSIT);
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CommonTransitImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_TRANSIT());
+ assertCsvImportResult(result, 0, Transit.class, fixtures.NB_TRANSIT());
+
+
+ assertNbEntities(Voyage.class, fixtures.NB_VOYAGE());
+ assertNbEntities(Transit.class, fixtures.NB_TRANSIT());
+ assertNbEntities(Transect.class, 0);
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/CommonVoyageImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/CommonVoyageImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,85 @@
+package fr.ifremer.echobase.services.service.importdata;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Transect;
+import fr.ifremer.echobase.entities.data.Transit;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link CommonImportService} with {@link ImportType#COMMON_VOYAGE} mode.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class CommonVoyageImportServiceIT extends AbstractImportDataServiceIT {
+
+ @Override
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_NO_DATA());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "common", filename};
+ }
+
+ @Test
+ public void doImport() throws Exception {
+
+ // no data in db
+
+ assertNoEntities(Voyage.class, Transit.class, Transect.class);
+
+ // import with mode voyage
+
+ CommonImportConfiguration conf =
+ new CommonImportConfiguration(getLocale());
+
+ conf.setAreaOfOperationId(fixtures.AREA_OF_OPERATION_ID());
+ conf.setDatum(fixtures.DATUM());
+ conf.setMissionId(fixtures.MISSION_ID());
+ conf.setVoyageDescription(fixtures.VOYAGE_DESCRIPTION());
+
+ prepareInputFile(conf.getVoyageFile(), getImportPath("voyage.csv.gz"));
+
+ conf.setImportType(ImportType.COMMON_VOYAGE);
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, CommonVoyageImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_VOYAGE());
+ assertCsvImportResult(result, 0, Voyage.class, fixtures.NB_VOYAGE());
+
+ assertNbEntities(Voyage.class, fixtures.NB_VOYAGE());
+ assertNbEntities(Transit.class, 0);
+ assertNbEntities(Transect.class, 0);
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/OperationImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/OperationImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/OperationImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/OperationImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,86 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.data.GearMetadataValue;
+import fr.ifremer.echobase.entities.data.Operation;
+import fr.ifremer.echobase.entities.data.OperationMetadataValue;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Tests {@link OperationImportService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class OperationImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_COMMON_DATA());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "operation", filename};
+ }
+
+ @Test
+ public void doImport() throws Exception {
+
+ assertImportCommonData();
+
+ assertNoEntities(Operation.class,
+ OperationMetadataValue.class,
+ GearMetadataValue.class);
+
+ OperationImportConfiguration conf =
+ new OperationImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+
+ prepareInputFile(conf.getOperationFile(),
+ getImportPath("operation.csv.gz"));
+ prepareInputFile(conf.getOperationMetadataFile(),
+ getImportPath("operationmetadatavalue.csv.gz"));
+ prepareInputFile(conf.getGearMetadataFile(),
+ getImportPath("gearmetadatavalue.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, OperationImportService.class, 3);
+
+ assertNbIDs(result, 0, fixtures.NB_OPERATION());
+ assertCsvImportResult(result, 0, Operation.class, fixtures.NB_OPERATION());
+
+ assertNbIDs(result, 1, 0);
+ assertCsvImportResult(result, 1, OperationMetadataValue.class, fixtures.NB_OPERATION_METADATAVALUE());
+
+ assertNbIDs(result, 2, 0);
+ assertCsvImportResult(result, 2, GearMetadataValue.class, fixtures.NB_GEAR_METADATAVALUE());
+
+ assertImportOperations();
+ }
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/ResultsEsduCellImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsEsduCellImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,194 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Category;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.references.AgeCategory;
+import fr.ifremer.echobase.entities.references.SizeCategory;
+import fr.ifremer.echobase.entities.references.SpeciesCategory;
+import fr.ifremer.echobase.io.InputFile;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * Test import of esdu results.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ResultsEsduCellImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_CATCHES_AND_VOYAGE_RESULT());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "result", "esdu", filename};
+ }
+
+ @Test
+ public void doImportByEchotype() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_ESDU);
+
+ InputFile inputFile = conf.getEsduByEchotypeFile();
+ prepareInputFile(inputFile, getImportPath("byEchotype.csv.gz"));
+
+ addMissingEsduCells(EchoBaseCsvUtil.CELL_NAME, conf.getVoyageId(), inputFile);
+
+ conf.setDataProcessingId(getDataProcessingId());
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsEsduCellImportService.class, 1);
+
+ assertNbIDs(result, 0, 43533);
+
+ assertCsvImportResult(result, 0, Result.class, 43533);
+ assertCsvImportResult(result, 0, Category.class, 7);
+ }
+
+ @Test
+ public void doImportByEchotypeAndSpecies() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_ESDU);
+
+ InputFile inputFile = conf.getEsduByEchotypeAndSpeciesCategoryFile();
+ prepareInputFile(inputFile,
+ getImportPath("byEchotypeAndSpeciesCategory.csv.gz"));
+
+ addMissingEsduCells(EchoBaseCsvUtil.CELL_NAME, conf.getVoyageId(), inputFile);
+
+ conf.setDataProcessingId(getDataProcessingId());
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsEsduCellImportService.class, 1);
+
+ assertNbIDs(result, 0, 357291);
+
+ assertCsvImportResult(result, 0, Result.class, 357291);
+ assertCsvImportResult(result, 0, Category.class, 27);
+ assertCsvImportResult(result, 0, SpeciesCategory.class, 1, 0, 457);
+ }
+
+ @Test
+ public void doImportBySpeciesAndSizeCategory() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_ESDU);
+
+ InputFile intputFile = conf.getEsduBySpeciesAndSizeCategoryFile();
+ prepareInputFile(intputFile,
+ getImportPath("bySpeciesAndSizeCategory.csv.gz"));
+
+ addMissingEsduCells(EchoBaseCsvUtil.CELL_NAME, conf.getVoyageId(), intputFile);
+
+ conf.setDataProcessingId(getDataProcessingId());
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsEsduCellImportService.class, 1);
+
+ assertNbIDs(result, 0, 68108);
+ assertCsvImportResult(result, 0, Result.class, 68108);
+ assertCsvImportResult(result, 0, Category.class, 129);
+ assertCsvImportResult(result, 0, SpeciesCategory.class, 129, 0, 585);
+ assertCsvImportResult(result, 0, SizeCategory.class, 62, 0, 69);
+ }
+
+ @Test
+ public void doImportBySpeciesAndAgeCategory() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_ESDU);
+
+ InputFile inputFile = conf.getEsduBySpeciesAndAgeCategoryFile();
+ prepareInputFile(inputFile,
+ getImportPath("bySpeciesAndAgeCategory.csv.gz"));
+
+ addMissingEsduCells(EchoBaseCsvUtil.CELL_NAME, conf.getVoyageId(), inputFile);
+
+ conf.setDataProcessingId(getDataProcessingId());
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsEsduCellImportService.class, 1);
+
+ assertNbIDs(result, 0, 10021);
+ assertCsvImportResult(result, 0, Category.class, 14);
+ assertCsvImportResult(result, 0, Result.class, 10021);
+ assertCsvImportResult(result, 0, AgeCategory.class, 6, 0, 10);
+ assertCsvImportResult(result, 0, SpeciesCategory.class, 14, 0, 470);
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/ResultsMapFishCellImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapFishCellImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,83 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Category;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * To test the {@link ResultsMapFishCellImportService} service.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ResultsMapFishCellImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_CATCHES_AND_VOYAGE_RESULT());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "result", "map", filename};
+ }
+
+ @Test
+ public void doImportMap() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class, Data.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_MAP_FISH);
+
+ prepareInputFile(conf.getMapsFile(), getImportPath("mapsFish.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsMapFishCellImportService.class, 1);
+
+ assertNbIDs(result, 0, 380);
+
+ assertCsvImportResult(result, 0, Cell.class, 380);
+ assertCsvImportResult(result, 0, Data.class, 2280);
+ assertCsvImportResult(result, 0, Result.class, 380);
+ assertCsvImportResult(result, 0, Category.class, 1);
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/ResultsMapOtherCellImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsMapOtherCellImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,81 @@
+package fr.ifremer.echobase.services.service.importdata;
+
+/*
+ * #%L
+ * EchoBase :: Services
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * To test the {@link ResultsMapOtherCellImportService} service.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class ResultsMapOtherCellImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_CATCHES_AND_VOYAGE_RESULT());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "result", "map", filename};
+ }
+
+ @Test
+ public void doImportMap() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class, Data.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_MAP_OTHER);
+
+ prepareInputFile(conf.getMapsFile(), getImportPath("mapsOther.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsMapOtherCellImportService.class, 1);
+
+ assertNbIDs(result, 0, 380);
+
+ assertCsvImportResult(result, 0, Cell.class, 380);
+ assertCsvImportResult(result, 0, Data.class, 2280);
+ assertCsvImportResult(result, 0, Result.class, 380);
+ }
+
+}
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/ResultsRegionCellImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsRegionCellImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,95 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Category;
+import fr.ifremer.echobase.entities.data.Cell;
+import fr.ifremer.echobase.entities.data.Data;
+import fr.ifremer.echobase.entities.data.Result;
+import fr.ifremer.echobase.entities.references.SpeciesCategory;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * To test the {@link ResultsRegionCellImportService} service.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ResultsRegionCellImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(
+ fixtures.IMPORT_DATA_ECHOBASE_CATCHES_AND_VOYAGE_RESULT());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "result", "region", filename};
+ }
+
+ @Test
+ public void doImportRegion() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+ assertImportVoyageResult();
+
+ assertNoEntities(Result.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setResultLabel("resultLabel");
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_REGION);
+
+ prepareInputFile(conf.getRegionsFile(),
+ getImportPath("regions.csv.gz"));
+ prepareInputFile(conf.getRegionAssociationFile(),
+ getImportPath("regionAssociations.csv.gz"));
+ prepareInputFile(conf.getRegionResultFile(),
+ getImportPath("regionResults.csv.gz"));
+
+ addMissingEsduCells("esduName",
+ conf.getVoyageId(),
+ conf.getRegionAssociationFile());
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsRegionCellImportService.class, 3);
+
+ assertNbIDs(result, 0, 10);
+
+ assertCsvImportResult(result, 0, Cell.class, 10, 0, 2083);
+ assertCsvImportResult(result, 0, Data.class, 238);
+ assertCsvImportResult(result, 1, Cell.class, 0, 4146, 2083);
+ assertCsvImportResult(result, 2, Result.class, 2128);
+ assertCsvImportResult(result, 2, Category.class, 27);
+ assertCsvImportResult(result, 2, SpeciesCategory.class, 1, 0, 457);
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportServiceIT.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdata/ResultsVoyageImportServiceIT.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportServiceIT.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdata/ResultsVoyageImportServiceIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,165 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdata;
+
+import fr.ifremer.echobase.entities.ImportType;
+import fr.ifremer.echobase.entities.data.Echotype;
+import fr.ifremer.echobase.entities.data.LengthAgeKey;
+import fr.ifremer.echobase.entities.data.LengthWeightKey;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.util.List;
+
+/**
+ * To test the {@link ResultsVoyageImportService} service.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ResultsVoyageImportServiceIT extends AbstractImportDataServiceIT {
+
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(fixtures.IMPORT_DATA_ECHOBASE_CATCHES());
+ }
+
+ protected String[] getImportPath(String filename) {
+ return new String[]{"/import-data", "result", "voyage", filename};
+ }
+
+ @Test
+ public void doImportResultByVoyage() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+
+ assertNoEntities(LengthAgeKey.class);
+ assertNoEntities(LengthWeightKey.class);
+ assertNoEntities(Echotype.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_VOYAGE);
+
+ prepareInputFile(conf.getLengthAgeKeyFile(),
+ getImportPath("lengthAgeKey.csv.gz"));
+ prepareInputFile(conf.getLengthWeightKeyFile(),
+ getImportPath("lengthWeightKey.csv.gz"));
+ prepareInputFile(conf.getEchotypeFile(), getImportPath("echotype.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsVoyageImportService.class, 3);
+
+ assertNbIDs(result, 0, fixtures.NB_LENGTH_AGE_KEY());
+ assertCsvImportResult(result, 0, LengthAgeKey.class, fixtures.NB_LENGTH_AGE_KEY());
+
+ assertNbIDs(result, 1, fixtures.NB_LENGTH_WEIGHT_KEY());
+ assertCsvImportResult(result, 1, LengthWeightKey.class, fixtures.NB_LENGTH_WEIGHT_KEY());
+
+ assertNbIDs(result, 2, fixtures.NB_ECHOTYPE());
+ assertCsvImportResult(result, 2, Echotype.class, fixtures.NB_ECHOTYPE());
+ }
+
+ @Ignore
+ @Test
+ public void doImportLengthAgeKey() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+
+ assertNoEntities(LengthAgeKey.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_VOYAGE);
+
+ prepareInputFile(conf.getLengthAgeKeyFile(),
+ getImportPath("lengthAgeKey.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsVoyageImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_LENGTH_AGE_KEY());
+ assertCsvImportResult(result, 0, LengthAgeKey.class, fixtures.NB_LENGTH_AGE_KEY());
+ }
+
+ @Ignore
+ @Test
+ public void doImportLengthWeightKey() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+
+ assertNoEntities(LengthWeightKey.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_VOYAGE);
+
+ prepareInputFile(conf.getLengthWeightKeyFile(),
+ getImportPath("lengthWeightKey.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsVoyageImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_LENGTH_WEIGHT_KEY());
+ assertCsvImportResult(result, 0, LengthWeightKey.class, fixtures.NB_LENGTH_WEIGHT_KEY());
+ }
+
+ @Ignore
+ @Test
+ public void doImportEchotype() throws Exception {
+
+ assertImportCommonData();
+ assertImportOperations();
+ assertImportSampleDatas();
+
+ assertNoEntities(Echotype.class);
+
+ ResultsImportConfiguration conf =
+ new ResultsImportConfiguration(getLocale());
+
+ conf.setVoyageId(getVoyageId());
+ conf.setImportType(ImportType.RESULT_VOYAGE);
+
+ prepareInputFile(conf.getEchotypeFile(), getImportPath("echotype.csv.gz"));
+
+ List<EchoBaseCsvFileImportResult> result;
+ result = doImport(conf, ResultsVoyageImportService.class, 1);
+
+ assertNbIDs(result, 0, fixtures.NB_ECHOTYPE());
+ assertCsvImportResult(result, 0, Echotype.class, fixtures.NB_ECHOTYPE());
+ }
+
+}
\ No newline at end of file
Copied: trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdb/ImportDbServiceTest.java (from rev 839, trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/importdb/ImportDbServiceTest.java)
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdb/ImportDbServiceTest.java (rev 0)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/services/service/importdb/ImportDbServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,76 @@
+/*
+ * #%L
+ * EchoBase :: Services
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2012 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+package fr.ifremer.echobase.services.service.importdb;
+
+import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.EchoBaseUserImpl;
+import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
+import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
+import fr.ifremer.echobase.services.service.importdata.ImportException;
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.util.FileUtil;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Tests the {@link ImportDbService}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.3
+ */
+public class ImportDbServiceTest extends EchoBaseTestServiceSupport {
+
+ public static final String DB_VERSION = "1.2";
+
+ @Override
+ protected FakeEchoBaseServiceContext initContext() {
+ return new FakeEchoBaseServiceContext(null);
+ }
+
+ @Test
+ public void importDb() throws IOException, ImportException {
+
+ ImportDbService service = getImportDbService();
+
+ ImportDbConfiguration conf = new ImportDbConfiguration(getLocale());
+
+ File workingDirectory = new File(getTestDir(), "work-dir");
+ FileUtil.createDirectoryIfNecessary(workingDirectory);
+ conf.setWorkingDirectory(workingDirectory);
+ conf.setComputeSteps(true);
+ conf.setCommitAfterEachFile(false);
+ conf.setImportDbMode(ImportDbMode.REFERENTIAL);
+ prepareInputFile(conf.getInput(), fixtures.importDbReferentialPath());
+
+ EchoBaseUser user = new EchoBaseUserImpl();
+ user.setEmail("testUser(a)fake.fr");
+
+ service.doImport(conf, user);
+
+ Assert.assertTrue(conf.getProgress() > 94);
+ }
+
+}
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AbstractRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AbstractRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AbstractRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -76,31 +76,30 @@
import fr.ifremer.echobase.entities.references.Vessel;
import fr.ifremer.echobase.services.EchoBaseTestServiceSupport;
import fr.ifremer.echobase.services.FakeEchoBaseServiceContext;
-import fr.ifremer.echobase.services.importdata.AbstractImportConfiguration;
-import fr.ifremer.echobase.services.importdata.AbstractImportDataService;
-import fr.ifremer.echobase.services.importdata.AcousticImportConfiguration;
-import fr.ifremer.echobase.services.importdata.AcousticImportService;
-import fr.ifremer.echobase.services.importdata.CatchesImportConfiguration;
-import fr.ifremer.echobase.services.importdata.CatchesImportService;
-import fr.ifremer.echobase.services.importdata.CommonAllImportService;
-import fr.ifremer.echobase.services.importdata.CommonImportConfiguration;
-import fr.ifremer.echobase.services.importdata.OperationImportConfiguration;
-import fr.ifremer.echobase.services.importdata.OperationImportService;
-import fr.ifremer.echobase.services.importdata.ResultsEsduCellImportService;
-import fr.ifremer.echobase.services.importdata.ResultsImportConfiguration;
-import fr.ifremer.echobase.services.importdata.ResultsMapFishCellImportService;
-import fr.ifremer.echobase.services.importdata.ResultsMapOtherCellImportService;
-import fr.ifremer.echobase.services.importdata.ResultsRegionCellImportService;
-import fr.ifremer.echobase.services.importdata.ResultsVoyageImportService;
-import fr.ifremer.echobase.services.removedata.RemoveDataConfiguration;
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.importdata.AbstractImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.AbstractImportDataService;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportService;
+import fr.ifremer.echobase.services.service.importdata.CatchesImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.CatchesImportService;
+import fr.ifremer.echobase.services.service.importdata.CommonAllImportService;
+import fr.ifremer.echobase.services.service.importdata.CommonImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.OperationImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.OperationImportService;
+import fr.ifremer.echobase.services.service.importdata.ResultsEsduCellImportService;
+import fr.ifremer.echobase.services.service.importdata.ResultsImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.ResultsMapFishCellImportService;
+import fr.ifremer.echobase.services.service.importdata.ResultsMapOtherCellImportService;
+import fr.ifremer.echobase.services.service.importdata.ResultsRegionCellImportService;
+import fr.ifremer.echobase.services.service.importdata.ResultsVoyageImportService;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataConfiguration;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Before;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaIdFactory;
@@ -247,25 +246,25 @@
public void setUp() throws Exception {
super.setUp();
- voyageDao = getDAO(Voyage.class, VoyageDAO.class);
- transectDAO = getDAO(Transect.class, TransectDAO.class);
- transitDAO = getDAO(Transit.class, TransitDAO.class);
- dataAcquisitionDAO = getDAO(DataAcquisition.class, DataAcquisitionDAO.class);
- dataProcessingDAO = getDAO(DataProcessing.class, DataProcessingDAO.class);
+ voyageDao = getEchoBasePersistenceContext().getVoyageDAO();
+ transectDAO = getEchoBasePersistenceContext().getTransectDAO();
+ transitDAO = getEchoBasePersistenceContext().getTransitDAO();
+ dataAcquisitionDAO = getEchoBasePersistenceContext().getDataAcquisitionDAO();
+ dataProcessingDAO = getEchoBasePersistenceContext().getDataProcessingDAO();
- cellDAO = getDAO(Cell.class, CellDAO.class);
- dataDAO = getDAO(Data.class, DataDAO.class);
- operationDAO = getDAO(Operation.class, OperationDAO.class);
- operationMetadataValueDAO = getDAO(OperationMetadataValue.class, OperationMetadataValueDAO.class);
- gearMetadataValueDAO = getDAO(GearMetadataValue.class, GearMetadataValueDAO.class);
- sampleDAO = getDAO(Sample.class, SampleDAO.class);
- sampleDataDAO = getDAO(SampleData.class, SampleDataDAO.class);
+ cellDAO = getEchoBasePersistenceContext().getCellDAO();
+ dataDAO = getEchoBasePersistenceContext().getDataDAO();
+ operationDAO = getEchoBasePersistenceContext().getOperationDAO();
+ operationMetadataValueDAO = getEchoBasePersistenceContext().getOperationMetadataValueDAO();
+ gearMetadataValueDAO = getEchoBasePersistenceContext().getGearMetadataValueDAO();
+ sampleDAO = getEchoBasePersistenceContext().getSampleDAO();
+ sampleDataDAO = getEchoBasePersistenceContext().getSampleDataDAO();
- echotypeDAO = getDAO(Echotype.class, EchotypeDAO.class);
- lengthAgeKeyDAO = getDAO(LengthAgeKey.class, LengthAgeKeyDAO.class);
- lengthWeightKeyDAO = getDAO(LengthWeightKey.class, LengthWeightKeyDAO.class);
- categoryDAO = getDAO(Category.class, CategoryDAO.class);
- resultDAO = getDAO(Result.class, ResultDAO.class);
+ echotypeDAO = getEchoBasePersistenceContext().getEchotypeDAO();
+ lengthAgeKeyDAO = getEchoBasePersistenceContext().getLengthAgeKeyDAO();
+ lengthWeightKeyDAO = getEchoBasePersistenceContext().getLengthWeightKeyDAO();
+ categoryDAO = getEchoBasePersistenceContext().getCategoryDAO();
+ resultDAO = getEchoBasePersistenceContext().getResultDAO();
//create imports for voyage 1
createCommonVoyageImportV1();
@@ -325,7 +324,7 @@
RemoveDataConfiguration conf = new RemoveDataConfiguration();
conf.setImportLogIds(new String[]{importId});
- RemoveDataService service = getService(RemoveDataService.class);
+ RemoveDataService service = getRemoveDataService();
EchoBaseUser fakeUser = createFakeUser();
@@ -356,16 +355,16 @@
}
private <E extends TopiaEntity> E getFirstEntity(Class<E> entityType) {
- List<E> entities = getEntities(entityType);
+ List<E> entities = getEchoBasePersistenceContext().getDAO(entityType).findAll();
Assert.assertTrue(CollectionUtils.isNotEmpty(entities));
return entities.get(0);
}
private <E extends TopiaEntity> E getEntity(String id) throws TopiaException {
- TopiaIdFactory topiaIdFactory = ((TopiaContextImplementor) getTransaction()).getTopiaIdFactory();
+ TopiaIdFactory topiaIdFactory = getEchoBasePersistenceContext().getTopiaIdFactory();
Class entityType = topiaIdFactory.getClassName(id);
- TopiaDAO<E> dao = getDAO(entityType);
+ TopiaDAO<E> dao = getEchoBasePersistenceContext().getDAO(entityType);
E entity = dao.findByTopiaId(id);
return entity;
}
@@ -373,19 +372,19 @@
private void createCommonVoyageImportV1() {
// create voyage
- Voyage voyage = create(voyageDao,
- TopiaEntity.PROPERTY_TOPIA_ID, voyage1Id,
- Voyage.PROPERTY_MISSION, getFirstEntity(Mission.class),
- Voyage.PROPERTY_NAME, "voyage1",
- Voyage.PROPERTY_START_DATE, newDate(),
- Voyage.PROPERTY_END_DATE, newDate(),
- Voyage.PROPERTY_START_PORT, "voyage1StartPort",
- Voyage.PROPERTY_END_PORT, "voyage1EndPort",
- Voyage.PROPERTY_DESCRIPTION, "voyage1Description",
- Voyage.PROPERTY_DATUM, "voyage1Datum"
+ Voyage voyage = voyageDao.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, voyage1Id,
+ Voyage.PROPERTY_MISSION, getFirstEntity(Mission.class),
+ Voyage.PROPERTY_NAME, "voyage1",
+ Voyage.PROPERTY_START_DATE, newDate(),
+ Voyage.PROPERTY_END_DATE, newDate(),
+ Voyage.PROPERTY_START_PORT, "voyage1StartPort",
+ Voyage.PROPERTY_END_PORT, "voyage1EndPort",
+ Voyage.PROPERTY_DESCRIPTION, "voyage1Description",
+ Voyage.PROPERTY_DATUM, "voyage1Datum"
);
- commitTransaction("ImportError!");
+ getEchoBasePersistenceContext().commitTransaction();
importCommonVoyage1Id = createImport(
CommonAllImportService.class,
@@ -399,19 +398,19 @@
private void createCommonVoyageImportV2() {
// create voyage
- Voyage voyage = create(voyageDao,
- TopiaEntity.PROPERTY_TOPIA_ID, voyage2Id,
- Voyage.PROPERTY_MISSION, getFirstEntity(Mission.class),
- Voyage.PROPERTY_NAME, "voyage2",
- Voyage.PROPERTY_START_DATE, newDate(),
- Voyage.PROPERTY_END_DATE, newDate(),
- Voyage.PROPERTY_START_PORT, "voyage2StartPort",
- Voyage.PROPERTY_END_PORT, "voyage2EndPort",
- Voyage.PROPERTY_DESCRIPTION, "voyage2Description",
- Voyage.PROPERTY_DATUM, "voyage2Datum"
+ Voyage voyage = voyageDao.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, voyage2Id,
+ Voyage.PROPERTY_MISSION, getFirstEntity(Mission.class),
+ Voyage.PROPERTY_NAME, "voyage2",
+ Voyage.PROPERTY_START_DATE, newDate(),
+ Voyage.PROPERTY_END_DATE, newDate(),
+ Voyage.PROPERTY_START_PORT, "voyage2StartPort",
+ Voyage.PROPERTY_END_PORT, "voyage2EndPort",
+ Voyage.PROPERTY_DESCRIPTION, "voyage2Description",
+ Voyage.PROPERTY_DATUM, "voyage2Datum"
);
- commitTransaction("ImportError!");
+ getEchoBasePersistenceContext().commitTransaction();
importCommonVoyage2Id = createImport(
CommonAllImportService.class,
@@ -428,18 +427,18 @@
Voyage voyage = getEntity(voyage1Id);
// create transit
- Transit transit = create(transitDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, transit1Id,
- Transit.PROPERTY_START_TIME, newDate(),
- Transit.PROPERTY_END_TIME, newDate(),
- Transit.PROPERTY_START_LOCALITY, "transit1tartLocality",
- Transit.PROPERTY_END_LOCALITY, "transit1EndLocality",
- Transit.PROPERTY_DESCRIPTION, "transit1Description",
- Transit.PROPERTY_RELATED_ACTIVITY, "transit1RelatedActivity"
+ Transit transit = transitDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, transit1Id,
+ Transit.PROPERTY_START_TIME, newDate(),
+ Transit.PROPERTY_END_TIME, newDate(),
+ Transit.PROPERTY_START_LOCALITY, "transit1tartLocality",
+ Transit.PROPERTY_END_LOCALITY, "transit1EndLocality",
+ Transit.PROPERTY_DESCRIPTION, "transit1Description",
+ Transit.PROPERTY_RELATED_ACTIVITY, "transit1RelatedActivity"
);
voyage.addTransit(transit);
- commitTransaction("ImportError!");
+ getEchoBasePersistenceContext().commitTransaction();
importCommonTransit1Id = createImport(
CommonAllImportService.class,
@@ -456,18 +455,18 @@
Voyage voyage = getEntity(voyage2Id);
// create transit
- Transit transit = create(transitDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, transit2Id,
- Transit.PROPERTY_START_TIME, newDate(),
- Transit.PROPERTY_END_TIME, newDate(),
- Transit.PROPERTY_START_LOCALITY, "transit2StartLocality",
- Transit.PROPERTY_END_LOCALITY, "transit2EndLocality",
- Transit.PROPERTY_DESCRIPTION, "transit2Description",
- Transit.PROPERTY_RELATED_ACTIVITY, "transit2RelatedActivity"
+ Transit transit = transitDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, transit2Id,
+ Transit.PROPERTY_START_TIME, newDate(),
+ Transit.PROPERTY_END_TIME, newDate(),
+ Transit.PROPERTY_START_LOCALITY, "transit2StartLocality",
+ Transit.PROPERTY_END_LOCALITY, "transit2EndLocality",
+ Transit.PROPERTY_DESCRIPTION, "transit2Description",
+ Transit.PROPERTY_RELATED_ACTIVITY, "transit2RelatedActivity"
);
voyage.addTransit(transit);
- commitTransaction("ImportError!");
+ getEchoBasePersistenceContext().commitTransaction();
importCommonTransit2Id = createImport(
CommonAllImportService.class,
@@ -486,24 +485,24 @@
Transit transit = voyage.getTransitByTopiaId(transit1Id);
// create transect
- Transect transect = create(transectDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, transect1Id,
- Transect.PROPERTY_TITLE, "transect1Title",
- Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
- Transect.PROPERTY_STRATUM, "transect1Stratum"
+ Transect transect = transectDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, transect1Id,
+ Transect.PROPERTY_TITLE, "transect1Title",
+ Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
+ Transect.PROPERTY_STRATUM, "transect1Stratum"
);
transit.addTransect(transect);
// create transect2
- Transect transect2 = create(transectDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, transect1_2Id,
- Transect.PROPERTY_TITLE, "transect12Title",
- Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
- Transect.PROPERTY_STRATUM, "transect12Stratum"
+ Transect transect2 = transectDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, transect1_2Id,
+ Transect.PROPERTY_TITLE, "transect12Title",
+ Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
+ Transect.PROPERTY_STRATUM, "transect12Stratum"
);
transit.addTransect(transect2);
- commitTransaction("ImportError!");
+ getEchoBasePersistenceContext().commitTransaction();
importCommonTransect1Id = createImport(
CommonAllImportService.class,
@@ -521,24 +520,24 @@
Transit transit = voyage.getTransitByTopiaId(transit2Id);
// create transect
- Transect transect = create(transectDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, transect2Id,
- Transect.PROPERTY_TITLE, "transect2Title",
- Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
- Transect.PROPERTY_STRATUM, "transect22tratum"
+ Transect transect = transectDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, transect2Id,
+ Transect.PROPERTY_TITLE, "transect2Title",
+ Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
+ Transect.PROPERTY_STRATUM, "transect22tratum"
);
transit.addTransect(transect);
// create transect2
- Transect transect2 = create(transectDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, transect2_2Id,
- Transect.PROPERTY_TITLE, "transect22Title",
- Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
- Transect.PROPERTY_STRATUM, "transect22Stratum"
+ Transect transect2 = transectDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, transect2_2Id,
+ Transect.PROPERTY_TITLE, "transect22Title",
+ Transect.PROPERTY_VESSEL, getFirstEntity(Vessel.class),
+ Transect.PROPERTY_STRATUM, "transect22Stratum"
);
transit.addTransect(transect2);
- commitTransaction("ImportError!");
+ getEchoBasePersistenceContext().commitTransaction();
importCommonTransect2Id = createImport(
CommonAllImportService.class,
@@ -554,17 +553,16 @@
Transect transect = getEntity(transect1Id);
// create operation
- Operation operation = create(operationDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, operation1Id,
- Operation.PROPERTY_ID, "operationId",
- Operation.PROPERTY_GEAR, getFirstEntity(Gear.class)
+ Operation operation = operationDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, operation1Id,
+ Operation.PROPERTY_ID, "operationId",
+ Operation.PROPERTY_GEAR, getFirstEntity(Gear.class)
);
transect.addOperation(operation);
// create operationMetadata
- OperationMetadataValue operationMetadataValue = create(
- operationMetadataValueDAO,
+ OperationMetadataValue operationMetadataValue = operationMetadataValueDAO.create(
OperationMetadataValue.PROPERTY_OPERATION_METADATA, getFirstEntity(OperationMetadata.class),
OperationMetadataValue.PROPERTY_DATA_VALUE, "dataValue"
);
@@ -572,8 +570,7 @@
operation.addOperationMetadataValue(operationMetadataValue);
// create geartMetadata
- GearMetadataValue gearMetadataValue = create(
- gearMetadataValueDAO,
+ GearMetadataValue gearMetadataValue = gearMetadataValueDAO.create(
GearMetadataValue.PROPERTY_GEAR, operation.getGear(),
GearMetadataValue.PROPERTY_GEAR_METADATA, getFirstEntity(GearMetadata.class),
GearMetadataValue.PROPERTY_DATA_VALUE, "gearDataValue"
@@ -596,52 +593,49 @@
Operation operation = getEntity(operation1Id);
// create totalSample
- Sample totalSample = create(sampleDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, totalSample1Id,
- Sample.PROPERTY_SAMPLE_TYPE, getFirstEntity(SampleType.class),
- Sample.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
- Sample.PROPERTY_NUMBER_SAMPLED, 10,
- Sample.PROPERTY_SAMPLE_WEIGHT, 2.4f
+ Sample totalSample = sampleDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, totalSample1Id,
+ Sample.PROPERTY_SAMPLE_TYPE, getFirstEntity(SampleType.class),
+ Sample.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
+ Sample.PROPERTY_NUMBER_SAMPLED, 10,
+ Sample.PROPERTY_SAMPLE_WEIGHT, 2.4f
);
operation.addSample(totalSample);
// add a data
- SampleData totalSampleData = create(sampleDataDAO,
- SampleData.PROPERTY_DATA_VALUE, 24.5f,
- SampleData.PROPERTY_SAMPLE_DATA_TYPE, getFirstEntity(SampleDataType.class)
+ SampleData totalSampleData = sampleDataDAO.create(SampleData.PROPERTY_DATA_VALUE, 24.5f,
+ SampleData.PROPERTY_SAMPLE_DATA_TYPE, getFirstEntity(SampleDataType.class)
);
totalSample.addSampleData(totalSampleData);
// create subSample
- Sample subSample = create(sampleDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, subSample1Id,
- Sample.PROPERTY_SAMPLE_TYPE, getFirstEntity(SampleType.class),
- Sample.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
- Sample.PROPERTY_NUMBER_SAMPLED, 10,
- Sample.PROPERTY_SAMPLE_WEIGHT, 2.5f
+ Sample subSample = sampleDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, subSample1Id,
+ Sample.PROPERTY_SAMPLE_TYPE, getFirstEntity(SampleType.class),
+ Sample.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
+ Sample.PROPERTY_NUMBER_SAMPLED, 10,
+ Sample.PROPERTY_SAMPLE_WEIGHT, 2.5f
);
operation.addSample(subSample);
// add a data
- SampleData subSampleData = create(sampleDataDAO,
- SampleData.PROPERTY_DATA_VALUE, 25.4f,
- SampleData.PROPERTY_SAMPLE_DATA_TYPE, getFirstEntity(SampleDataType.class)
+ SampleData subSampleData = sampleDataDAO.create(
+ SampleData.PROPERTY_DATA_VALUE, 25.4f,
+ SampleData.PROPERTY_SAMPLE_DATA_TYPE, getFirstEntity(SampleDataType.class)
);
subSample.addSampleData(subSampleData);
// create biometrySample
- Sample biometrySample = create(sampleDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, biometrySample1Id,
- Sample.PROPERTY_SAMPLE_TYPE, getFirstEntity(SampleType.class),
- Sample.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
- Sample.PROPERTY_NUMBER_SAMPLED, 10,
- Sample.PROPERTY_SAMPLE_WEIGHT, 2.6f
+ Sample biometrySample = sampleDAO.create(
+ TopiaEntity.PROPERTY_TOPIA_ID, biometrySample1Id,
+ Sample.PROPERTY_SAMPLE_TYPE, getFirstEntity(SampleType.class),
+ Sample.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
+ Sample.PROPERTY_NUMBER_SAMPLED, 10,
+ Sample.PROPERTY_SAMPLE_WEIGHT, 2.6f
);
operation.addSample(biometrySample);
// add a data
- SampleData biometrySampleData = create(sampleDataDAO,
- SampleData.PROPERTY_DATA_VALUE, 26.4f,
- SampleData.PROPERTY_SAMPLE_DATA_TYPE, getFirstEntity(SampleDataType.class)
+ SampleData biometrySampleData = sampleDataDAO.create(
+ SampleData.PROPERTY_DATA_VALUE, 26.4f,
+ SampleData.PROPERTY_SAMPLE_DATA_TYPE, getFirstEntity(SampleDataType.class)
);
biometrySample.addSampleData(biometrySampleData);
@@ -659,41 +653,35 @@
Transect transect = getEntity(transect1Id);
// create data acquisition
- DataAcquisition dataAcquisition = create(dataAcquisitionDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, dataAcquisition1Id,
- DataAcquisition.PROPERTY_ACOUSTIC_INSTRUMENT, getFirstEntity(AcousticInstrument.class));
+ DataAcquisition dataAcquisition = dataAcquisitionDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, dataAcquisition1Id,
+ DataAcquisition.PROPERTY_ACOUSTIC_INSTRUMENT, getFirstEntity(AcousticInstrument.class));
transect.addDataAcquisition(dataAcquisition);
// create dataProcessing
- DataProcessing dataProcessing = create(dataProcessingDAO,
- DataProcessing.PROPERTY_ID, "id1",
- DataProcessing.PROPERTY_PROCESSING_TEMPLATE, "processingTemplate");
+ DataProcessing dataProcessing = dataProcessingDAO.create(DataProcessing.PROPERTY_ID, "id1",
+ DataProcessing.PROPERTY_PROCESSING_TEMPLATE, "processingTemplate");
dataAcquisition.addDataProcessing(dataProcessing);
// create esdu cell
- Cell esduCell = create(cellDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, cellEsdu1Id,
- Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
- Cell.PROPERTY_NAME, "cellEsdu1");
+ Cell esduCell = cellDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, cellEsdu1Id,
+ Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
+ Cell.PROPERTY_NAME, "cellEsdu1");
dataProcessing.addCell(esduCell);
// create cell data
- Data esduData = create(dataDAO,
- Data.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
- Data.PROPERTY_DATA_VALUE, "esdu1Data");
+ Data esduData = dataDAO.create(Data.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
+ Data.PROPERTY_DATA_VALUE, "esdu1Data");
esduCell.addData(esduData);
// create elementary cell
- Cell elementaryCell = create(cellDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, cellElementary1Id,
- Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
- Cell.PROPERTY_NAME, "cellElementary1");
+ Cell elementaryCell = cellDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, cellElementary1Id,
+ Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
+ Cell.PROPERTY_NAME, "cellElementary1");
esduCell.addChilds(elementaryCell);
// create cell data
- Data elementaryData = create(dataDAO,
- Data.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
- Data.PROPERTY_DATA_VALUE, "elementary1Data");
+ Data elementaryData = dataDAO.create(Data.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
+ Data.PROPERTY_DATA_VALUE, "elementary1Data");
elementaryCell.addData(elementaryData);
importAcoustic1Id = createImport(
@@ -710,31 +698,28 @@
Voyage voyage = getEntity(voyage1Id);
// create echotype
- Echotype echotype = create(echotypeDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, echotype1Id,
- Echotype.PROPERTY_NAME, "echotype1Name");
+ Echotype echotype = echotypeDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, echotype1Id,
+ Echotype.PROPERTY_NAME, "echotype1Name");
voyage.addEchotype(echotype);
// create lengthAgeKey
- LengthAgeKey lengthAgeKey = create(lengthAgeKeyDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, lengthAgeKey1Id,
- LengthAgeKey.PROPERTY_AGE, 12,
- LengthAgeKey.PROPERTY_LENGTH, 12.5f,
- LengthAgeKey.PROPERTY_METADATA, "lengthAgeKeyMetadata1",
- LengthAgeKey.PROPERTY_SPECIES, getFirstEntity(Species.class),
- LengthAgeKey.PROPERTY_STRATA, getFirstEntity(Strata.class)
+ LengthAgeKey lengthAgeKey = lengthAgeKeyDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, lengthAgeKey1Id,
+ LengthAgeKey.PROPERTY_AGE, 12,
+ LengthAgeKey.PROPERTY_LENGTH, 12.5f,
+ LengthAgeKey.PROPERTY_METADATA, "lengthAgeKeyMetadata1",
+ LengthAgeKey.PROPERTY_SPECIES, getFirstEntity(Species.class),
+ LengthAgeKey.PROPERTY_STRATA, getFirstEntity(Strata.class)
);
voyage.addLengthAgeKey(lengthAgeKey);
// create lengthWeightKey
- LengthWeightKey lengthWeightKey = create(lengthWeightKeyDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, lengthWeightKey1Id,
- LengthWeightKey.PROPERTY_APARAMETER, 12.5f,
- LengthWeightKey.PROPERTY_BPARAMETER, 0.2f,
- LengthWeightKey.PROPERTY_METADATA, "lengthWeightMetadata1",
- LengthWeightKey.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
- LengthWeightKey.PROPERTY_STRATA, getFirstEntity(Strata.class)
+ LengthWeightKey lengthWeightKey = lengthWeightKeyDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, lengthWeightKey1Id,
+ LengthWeightKey.PROPERTY_APARAMETER, 12.5f,
+ LengthWeightKey.PROPERTY_BPARAMETER, 0.2f,
+ LengthWeightKey.PROPERTY_METADATA, "lengthWeightMetadata1",
+ LengthWeightKey.PROPERTY_SPECIES_CATEGORY, getFirstEntity(SpeciesCategory.class),
+ LengthWeightKey.PROPERTY_STRATA, getFirstEntity(Strata.class)
);
voyage.addLengthWeightKey(lengthWeightKey);
@@ -751,14 +736,13 @@
// create result (on ESDU)
- Category category = create(categoryDAO);
+ Category category = categoryDAO.create();
- Result result = create(resultDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, resultEsdu1Id,
- Result.PROPERTY_CATEGORY, category,
- Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
- Result.PROPERTY_RESULT_VALUE, "resultValueEdsu1",
- Result.PROPERTY_RESULT_LABEL, "resultLabelEdsu1"
+ Result result = resultDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, resultEsdu1Id,
+ Result.PROPERTY_CATEGORY, category,
+ Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
+ Result.PROPERTY_RESULT_VALUE, "resultValueEdsu1",
+ Result.PROPERTY_RESULT_LABEL, "resultLabelEdsu1"
);
Cell cell = getEntity(cellEsdu1Id);
@@ -776,10 +760,9 @@
private void createResultRegionImportV1() throws TopiaException {
// create region
- Cell region = create(cellDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, cellRegion1Id,
- Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
- Cell.PROPERTY_NAME, "cellRegion1");
+ Cell region = cellDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, cellRegion1Id,
+ Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
+ Cell.PROPERTY_NAME, "cellRegion1");
Voyage voyage = getEntity(voyage1Id);
voyage.addPostCell(region);
@@ -789,13 +772,12 @@
region.addChilds(esduCell);
// create result (on region)
- Category category = create(categoryDAO);
- Result result = create(resultDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, resultRegion1Id,
- Result.PROPERTY_CATEGORY, category,
- Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
- Result.PROPERTY_RESULT_VALUE, "resultValueRegion1",
- Result.PROPERTY_RESULT_LABEL, "resultLabelRegion1"
+ Category category = categoryDAO.create();
+ Result result = resultDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, resultRegion1Id,
+ Result.PROPERTY_CATEGORY, category,
+ Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
+ Result.PROPERTY_RESULT_VALUE, "resultValueRegion1",
+ Result.PROPERTY_RESULT_LABEL, "resultLabelRegion1"
);
region.addResult(result);
@@ -811,22 +793,20 @@
private void createResultMapFishImportV1() throws TopiaException {
// create map
- Cell map = create(cellDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, cellMapFish1Id,
- Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
- Cell.PROPERTY_NAME, "cellMap1");
+ Cell map = cellDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, cellMapFish1Id,
+ Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
+ Cell.PROPERTY_NAME, "cellMap1");
Voyage voyage = getEntity(voyage1Id);
voyage.addPostCell(map);
// create result (on map)
- Category category = create(categoryDAO);
- Result result = create(resultDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, resultMapFish1Id,
- Result.PROPERTY_CATEGORY, category,
- Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
- Result.PROPERTY_RESULT_VALUE, "resultValueMapFish1",
- Result.PROPERTY_RESULT_LABEL, "resultLabelMapFish1"
+ Category category = categoryDAO.create();
+ Result result = resultDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, resultMapFish1Id,
+ Result.PROPERTY_CATEGORY, category,
+ Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
+ Result.PROPERTY_RESULT_VALUE, "resultValueMapFish1",
+ Result.PROPERTY_RESULT_LABEL, "resultLabelMapFish1"
);
map.addResult(result);
@@ -842,21 +822,19 @@
private void createResultMapOtherImportV1() throws TopiaException {
// create map
- Cell map = create(cellDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, cellMapOther1Id,
- Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
- Cell.PROPERTY_NAME, "cellMapOther1");
+ Cell map = cellDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, cellMapOther1Id,
+ Cell.PROPERTY_CELL_TYPE, getFirstEntity(CellType.class),
+ Cell.PROPERTY_NAME, "cellMapOther1");
Voyage voyage = getEntity(voyage1Id);
voyage.addPostCell(map);
// create result (on map)
- Result result = create(resultDAO,
- TopiaEntity.PROPERTY_TOPIA_ID, resultMapOther1Id,
- Result.PROPERTY_CATEGORY, null,
- Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
- Result.PROPERTY_RESULT_VALUE, "resultValueMapOther1",
- Result.PROPERTY_RESULT_LABEL, "resultLabelMapOther1"
+ Result result = resultDAO.create(TopiaEntity.PROPERTY_TOPIA_ID, resultMapOther1Id,
+ Result.PROPERTY_CATEGORY, null,
+ Result.PROPERTY_DATA_METADATA, getFirstEntity(DataMetadata.class),
+ Result.PROPERTY_RESULT_VALUE, "resultValueMapOther1",
+ Result.PROPERTY_RESULT_LABEL, "resultLabelMapOther1"
);
map.addResult(result);
@@ -880,7 +858,7 @@
importConf.setImportNotes(importNote);
importConf.setVoyageId(voyageId);
- S importService = getService(serviceType);
+ S importService = newService(serviceType);
ImportLog importLog = importService.computeImportLogEntry(
importConf, createFakeUser());
@@ -889,7 +867,7 @@
importLog.addImportId(importId.getTopiaId());
}
- commitTransaction("ImportLogError!");
+ getEchoBasePersistenceContext().commitTransaction();
String importId = importLog.getTopiaId();
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AcousticRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AcousticRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/AcousticRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.AcousticRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.AcousticRemoveDataStrategy;
import org.junit.Test;
/**
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CatchesRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CatchesRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CatchesRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.CatchesRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.CatchesRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonAllRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonAllRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonAllRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.CommonAllRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonAllRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransectRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransectRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransectRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.CommonTransectRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonTransectRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransitRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransitRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonTransitRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.CommonTransitRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonTransitRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonVoyageRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonVoyageRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/CommonVoyageRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.CommonVoyageRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.CommonVoyageRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/OperationRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/OperationRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/OperationRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.OperationRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.OperationRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultEsduRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultEsduRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultEsduRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.ResultEsduRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultEsduRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveFishDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveFishDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveFishDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.ResultMapFishRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultMapFishRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveOtherDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveOtherDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultMapRemoveOtherDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.ResultMapOtherRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultMapOtherRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultRegionRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultRegionRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultRegionRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.ResultRegionRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultRegionRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultVoyageRemoveDataServiceTest.java
===================================================================
--- trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultVoyageRemoveDataServiceTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/src/test/java/fr/ifremer/echobase/ui/actions/removedata/ResultVoyageRemoveDataServiceTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
-import fr.ifremer.echobase.services.removedata.strategy.ResultVoyageRemoveDataStrategy;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.strategy.ResultVoyageRemoveDataStrategy;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
Modified: trunk/echobase-services/update-import-data-db.sh
===================================================================
--- trunk/echobase-services/update-import-data-db.sh 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-services/update-import-data-db.sh 2013-08-15 10:53:16 UTC (rev 842)
@@ -36,20 +36,20 @@
cp -v "$1" "src/test/resources/$dbnameprefix-importDb-referentiel.zip"
-executeMaven fr.ifremer.echobase.services.importdb.ImportDbServiceTest nodata
+executeMaven fr.ifremer.echobase.services.service.importdb.ImportDbServiceTest nodata
-executeMaven fr.ifremer.echobase.services.importdata.CommonAllImportServiceIT commonData
+executeMaven fr.ifremer.echobase.services.service.importdata.CommonAllImportServiceIT commonData
-executeMaven fr.ifremer.echobase.services.importdata.OperationImportServiceIT operation
+executeMaven fr.ifremer.echobase.services.service.importdata.OperationImportServiceIT operation
-executeMaven fr.ifremer.echobase.services.importdata.CatchesImportServiceIT catches
+executeMaven fr.ifremer.echobase.services.service.importdata.CatchesImportServiceIT catches
-executeMaven fr.ifremer.echobase.services.importdata.ResultsVoyageImportServiceIT catches-and-voyage-result
+executeMaven fr.ifremer.echobase.services.service.importdata.ResultsVoyageImportServiceIT catches-and-voyage-result
-#executeMaven fr.ifremer.echobase.services.importdata.AcousticImportServiceIT catches-and-acoustic-and-voyage-result
+#executeMaven fr.ifremer.echobase.services.service.importdata.AcousticImportServiceIT catches-and-acoustic-and-voyage-result
-#executeMaven fr.ifremer.echobase.services.importdata.ResultsEsduCellImportServiceIT
+#executeMaven fr.ifremer.echobase.services.service.importdata.ResultsEsduCellImportServiceIT
-#executeMaven fr.ifremer.echobase.services.importdata.ResultsRegionCellImportServiceIT
+#executeMaven fr.ifremer.echobase.services.service.importdata.ResultsRegionCellImportServiceIT
-#executeMaven fr.ifremer.echobase.services.importdata.ResultsMapFishCellImportServiceIT
+#executeMaven fr.ifremer.echobase.services.service.importdata.ResultsMapFishCellImportServiceIT
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/CellLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/CellLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/CellLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -31,7 +31,6 @@
import com.google.common.collect.Sets;
import com.healthmarketscience.jackcess.Database;
import fr.ifremer.echobase.EchoBaseFunctions;
-import fr.ifremer.echobase.entities.EchoBaseDAOHelper;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.Data;
@@ -228,10 +227,10 @@
EchoBaseFunctions.DATA_PROCESSING_ID);
DataMetadataDAO dataMetadataDAO =
- EchoBaseDAOHelper.getDataMetadataDAO(getTransaction());
+ getEchoBasePersistenceContext().getDataMetadataDAO();
CellMethod cellMethodstart =
- EchoBaseDAOHelper.getCellMethodDAO(getTransaction()).findByName("CellStart");
+ getEchoBasePersistenceContext().getCellMethodDAO().findByName("CellStart");
surfaceMetadata = dataMetadataDAO.findByName("Surface");
esduLatitudeMetadata = dataMetadataDAO.findByProperties(DataMetadata.PROPERTY_NAME, "LatitudeStart",
@@ -256,8 +255,8 @@
nullDataQuality = dataQualitiesById.get(0);
- CellTypeDAO cellTypeDAO = EchoBaseDAOHelper.getCellTypeDAO(
- getTransaction());
+ CellTypeDAO cellTypeDAO =
+ getEchoBasePersistenceContext().getCellTypeDAO();
esduCellType = cellTypeDAO.findById("Esdu");
elementaryCellType = cellTypeDAO.findById("Elementary");
@@ -301,7 +300,7 @@
// obtain acoustic dataMetadata for this data processing
DataMetadataDAO dataMetadataDAO =
- EchoBaseDAOHelper.getDataMetadataDAO(getTransaction());
+ getEchoBasePersistenceContext().getDataMetadataDAO();
Map<String, Object> eiconfigurationRow =
eiConfigurationByProcessingId.get(dataProcessingId);
@@ -319,8 +318,8 @@
Preconditions.checkNotNull(acousticMetadata, "Could not find acoustic Metadata with name " + longName);
dao = getDAO();
- dataDao = getDAO(Data.class);
- VoyageDAO voyageDao = (VoyageDAO) getDAO(Voyage.class);
+ dataDao = getEchoBasePersistenceContext().getDataDAO();
+ VoyageDAO voyageDao = getEchoBasePersistenceContext().getVoyageDAO();
Voyage voyage = voyageDao.findByName(campagne);
Preconditions.checkNotNull(voyage);
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/DataMetadataLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/DataMetadataLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/DataMetadataLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,8 +27,6 @@
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
import fr.ifremer.echobase.EchoBaseFunctions;
-import org.nuiton.topia.persistence.csv.EntityCsvModel;
-import fr.ifremer.echobase.entities.EchoBaseDAOHelper;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
import fr.ifremer.echobase.entities.references.CellMethod;
import fr.ifremer.echobase.entities.references.DataMetadata;
@@ -37,9 +35,9 @@
import fr.ifremer.echobase.tools.FileType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.csv.EntityCsvModel;
import org.nuiton.topia.persistence.metadata.TableMeta;
import java.io.IOException;
@@ -67,12 +65,10 @@
// require referenceDatum, dataType and cellMethod
- TopiaContext tx = serviceContext.getTransaction();
-
CellMethod cellMethod =
- EchoBaseDAOHelper.getCellMethodDAO(tx).findByName("Mean");
+ getEchoBasePersistenceContext().getCellMethodDAO().findByName("Mean");
DataType dataType =
- EchoBaseDAOHelper.getDataTypeDAO(tx).findByName("Acoustic density");
+ getEchoBasePersistenceContext().getDataTypeDAO().findByName("Acoustic density");
TopiaDAO<DataMetadata> dao = getDAO();
@@ -104,14 +100,14 @@
@Override
protected EntityCsvModel<EchoBaseEntityEnum, DataMetadata> createCsvImportModel(TableMeta<EchoBaseEntityEnum> meta) {
- EntityCsvModel<EchoBaseEntityEnum,DataMetadata> model = EntityCsvModel.newModel(
+ EntityCsvModel<EchoBaseEntityEnum, DataMetadata> model = EntityCsvModel.newModel(
getCsvSeparator(),
meta
);
- List<DataType> dataTypes = getEntities(DataType.class);
- List<ReferenceDatum> referenceDatums = getEntities(ReferenceDatum.class);
- List<CellMethod> cellMethods = getEntities(CellMethod.class);
+ List<DataType> dataTypes = getEchoBasePersistenceContext().getDataTypeDAO().findAll();
+ List<ReferenceDatum> referenceDatums = getEchoBasePersistenceContext().getReferenceDatumDAO().findAll();
+ List<CellMethod> cellMethods = getEchoBasePersistenceContext().getCellMethodDAO().findAll();
model.addForeignKeyForImport("DataTypeID", DataMetadata.PROPERTY_DATA_TYPE, DataType.class, dataTypes, EchoBaseFunctions.DATA_TYPE_NAME);
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/EntityLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/EntityLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/EntityLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -33,15 +33,18 @@
import com.healthmarketscience.jackcess.Database;
import fr.ifremer.echobase.EchoBaseTechnicalException;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
import fr.ifremer.echobase.services.EchoBaseServiceContext;
import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.exportdb.ExportService;
-import fr.ifremer.echobase.services.importdb.EchoBaseImportModelFactory;
+import fr.ifremer.echobase.services.service.importdb.EchoBaseImportModelFactory;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.tools.FileType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.nuiton.csv.Import;
+import org.nuiton.csv.ImportModel;
+import org.nuiton.csv.ImportToMap;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.TopiaEntities;
@@ -53,9 +56,6 @@
import org.nuiton.topia.persistence.metadata.MetaFilenameAware;
import org.nuiton.topia.persistence.metadata.TableMeta;
import org.nuiton.util.FileUtil;
-import org.nuiton.csv.Import;
-import org.nuiton.csv.ImportModel;
-import org.nuiton.csv.ImportToMap;
import java.io.BufferedReader;
import java.io.File;
@@ -143,11 +143,13 @@
// init internal states
- meta = getDbMeta().getTable(entityType);
+ EchoBaseDbMeta dbMeta = getDbMeta();
+ meta = dbMeta.getTable(entityType);
+
if (parent != null) {
- TableMeta<EchoBaseEntityEnum> parentMeta = getDbMeta().getTable(parent);
+ TableMeta<EchoBaseEntityEnum> parentMeta = dbMeta.getTable(parent);
// find the associationMeta
parentAssociationMeta =
@@ -222,8 +224,7 @@
Import<E> importer = Import.newImport(csvModel, bf);
try {
- DbEditorService dbEditorService =
- getService(DbEditorService.class);
+ DbEditorService dbEditorService = getDbEditorService();
importNewEntities(dbEditorService, tableMeta, importer);
} finally {
@@ -244,7 +245,7 @@
exportAssociations(outputDir, FileType.ASSOCIATION);
} finally {
if (cleanTransaction) {
- serviceContext.getTransaction().rollbackTransaction();
+ getEchoBasePersistenceContext().rollbackTransaction();
}
}
}
@@ -278,7 +279,7 @@
exportAssociations(outputDir, FileType.ASSOCIATION);
} finally {
if (cleanTransaction) {
- serviceContext.getTransaction().rollbackTransaction();
+ getEchoBasePersistenceContext().rollbackTransaction();
}
}
}
@@ -377,22 +378,14 @@
}
}
if (commit) {
- commitTransaction("Could not copyAndLoadEntities");
+ getEchoBasePersistenceContext().commitTransaction();
}
}
protected TopiaDAO<E> getDAO() throws TopiaException {
- return getDAO(entityClass);
+ return getEchoBasePersistenceContext().getDAO(entityClass);
}
- protected final ExportService getExportService() {
- return getService(ExportService.class);
- }
-
- protected final char getCsvSeparator() {
- return serviceContext.getConfiguration().getCsvSeparator();
- }
-
protected final Class<E> getEntityClass() {
return entityClass;
}
@@ -407,7 +400,7 @@
protected <E extends TopiaEntity, K> Map<K, E> getUniverse(Class<E> entityType,
Function<E, K> function) {
- List<E> entities = getEntities(entityType);
+ List<E> entities = getEchoBasePersistenceContext().getDAO(entityType).findAll();
Map<K, E> universe = Maps.uniqueIndex(entities, function);
return universe;
}
@@ -435,7 +428,7 @@
}
EchoBaseEntityEnum target = associationMeta.getTarget();
- List<TopiaEntity> targetEntities = (List<TopiaEntity>) getEntities(target.getContract());
+ List<TopiaEntity> targetEntities = (List<TopiaEntity>) getEchoBasePersistenceContext().getDAO(target.getContract()).findAll();
Map<String, TopiaEntity> targetsById =
Maps.uniqueIndex(targetEntities, TopiaEntities.getTopiaIdFunction());
@@ -445,7 +438,7 @@
ImportToMap importer = ImportToMap.newImportToMap(model, reader);
- List<E> sourceEntities = (List<E>) getEntities(sourceType.getContract());
+ List<E> sourceEntities = (List<E>) getEchoBasePersistenceContext().getDAO(sourceType.getContract()).findAll();
Map<String, E> sourcesById =
Maps.uniqueIndex(sourceEntities, TopiaEntities.getTopiaIdFunction());
try {
@@ -483,7 +476,7 @@
Import<TopiaEntity> importer = Import.newImport(model, reader);
try {
- TopiaDAO<?> dao = getDAO(tableMeta.getSource().getContract());
+ TopiaDAO<?> dao = getEchoBasePersistenceContext().getDAO(tableMeta.getSource().getContract());
for (TopiaEntity entity : importer) {
Map<String, Object> properties = meta.prepareCreate(
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/GearMetadataLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/GearMetadataLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/GearMetadataLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -48,7 +48,8 @@
@Override
protected EntityCsvModel<EchoBaseEntityEnum, GearMetadata> createCsvImportModel(TableMeta<EchoBaseEntityEnum> meta) {
- List<OperationEvent> events = getEntities(OperationEvent.class);
+ List<OperationEvent> events =
+ getEchoBasePersistenceContext().getOperationEventDAO().findAll();
EntityCsvModel<EchoBaseEntityEnum,GearMetadata> model = EntityCsvModel.newModel(
getCsvSeparator(),
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -165,7 +165,7 @@
Gear.class, EchoBaseFunctions.GEAR_CASINO_GEAR_NAME);
OperationMetadataDAO operationMetadataDAO =
- (OperationMetadataDAO) getDAO(OperationMetadata.class);
+ getEchoBasePersistenceContext().getOperationMetadataDAO();
//SONDE
meanWaterDepthOperationMeta =
@@ -183,7 +183,7 @@
Preconditions.checkNotNull(endWaterDepthOperationMeta);
GearMetadataDAO gearMetadataDAO =
- (GearMetadataDAO) getDAO(GearMetadata.class);
+ getEchoBasePersistenceContext().getGearMetadataDAO();
//LFUNES
cableLengthGearMeta = gearMetadataDAO.findByName("CableLength");
@@ -196,8 +196,8 @@
Preconditions.checkNotNull(maxSpeedGearMeta);
dao = getDAO();
- operationMetadataValueDAO = getDAO(OperationMetadataValue.class);
- gearMetadataValueDAO = getDAO(GearMetadataValue.class);
+ operationMetadataValueDAO = getEchoBasePersistenceContext().getOperationMetadataValueDAO();
+ gearMetadataValueDAO = getEchoBasePersistenceContext().getGearMetadataValueDAO();
Multimap<String, Map<String, Object>> stationByCampagneName = Multimaps.index(
db.getTable("STATIONS"), EchoBaseFunctions.newRowFunction("CAMPAGNE"));
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationMetadataLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationMetadataLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/OperationMetadataLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -49,7 +49,8 @@
@Override
protected EntityCsvModel<EchoBaseEntityEnum, OperationMetadata> createCsvImportModel(TableMeta<EchoBaseEntityEnum> meta) {
- List<OperationEvent> events = getEntities(OperationEvent.class);
+ List<OperationEvent> events =
+ getEchoBasePersistenceContext().getOperationEventDAO().findAll();
EntityCsvModel<EchoBaseEntityEnum, OperationMetadata> model = EntityCsvModel.newModel(
getCsvSeparator(),
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/ReferenceDatumLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/ReferenceDatumLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/ReferenceDatumLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,11 +24,11 @@
package fr.ifremer.echobase.tools.loaders;
import fr.ifremer.echobase.EchoBaseFunctions;
-import org.nuiton.topia.persistence.csv.EntityCsvModel;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
import fr.ifremer.echobase.entities.references.ReferenceDatum;
import fr.ifremer.echobase.entities.references.ReferenceDatumType;
import fr.ifremer.echobase.tools.FileType;
+import org.nuiton.topia.persistence.csv.EntityCsvModel;
import org.nuiton.topia.persistence.metadata.TableMeta;
import java.util.List;
@@ -47,13 +47,13 @@
@Override
protected EntityCsvModel<EchoBaseEntityEnum, ReferenceDatum> createCsvImportModel(TableMeta<EchoBaseEntityEnum> meta) {
- EntityCsvModel<EchoBaseEntityEnum,ReferenceDatum> model = EntityCsvModel.newModel(
+ EntityCsvModel<EchoBaseEntityEnum, ReferenceDatum> model = EntityCsvModel.newModel(
getCsvSeparator(),
meta
);
List<ReferenceDatumType> referenceDatumTypes =
- getEntities(ReferenceDatumType.class);
+ getEchoBasePersistenceContext().getReferenceDatumTypeDAO().findAll();
model.newMandatoryColumn(ReferenceDatum.PROPERTY_ID);
model.newMandatoryColumn(ReferenceDatum.PROPERTY_MEANING);
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SampleLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SampleLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SampleLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -164,7 +164,7 @@
EchoBaseFunctions.newRowFunction("NOSTA_VALEUR_BIOMETRIE")
);
SampleTypeDAO sampleTypeDAO =
- (SampleTypeDAO) getDAO(SampleType.class);
+ getEchoBasePersistenceContext().getSampleTypeDAO();
SampleType sampleTypeTotal = sampleTypeDAO.findByName("Total");
Preconditions.checkNotNull(sampleTypeTotal);
@@ -175,7 +175,7 @@
SampleType sampleTypeIndividual = sampleTypeDAO.findByName("Individual");
Preconditions.checkNotNull(sampleTypeIndividual);
- sampleDataDAO = (SampleDataDAO) getDAO(SampleData.class);
+ sampleDataDAO = getEchoBasePersistenceContext().getSampleDataDAO();
//MeanLengthcm
SampleDataType sampleDataTypeMeanLength = getFK(sampleDataTypeByRaptriCode, "114");
@@ -189,7 +189,7 @@
SampleDataType sampleDataTypeWeightAtLength = getFK(sampleDataTypeByRaptriCode, "113");
dao = getDAO();
- speciesCategoryDAO = (SpeciesCategoryDAO) getDAO(SpeciesCategory.class);
+ speciesCategoryDAO = getEchoBasePersistenceContext().getSpeciesCategoryDAO();
int nbSampleUnsorted = 0;
int nbSampleTotal = 0;
int nbSubSample = 0;
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SpeciesCategoryLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SpeciesCategoryLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/SpeciesCategoryLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -70,7 +70,7 @@
SexCategory.class, EchoBaseFunctions.SEX_CATEGORY_NAME);
SpeciesCategoryDAO speciesCategoryDAO =
- (SpeciesCategoryDAO) getDAO(SpeciesCategory.class);
+ getEchoBasePersistenceContext().getSpeciesCategoryDAO();
List<LengthWeightKey> lengthWeightKeys = Lists.newArrayList();
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/StrataLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/StrataLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/StrataLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -49,7 +49,8 @@
@Override
protected EntityCsvModel<EchoBaseEntityEnum, Strata> createCsvImportModel(TableMeta<EchoBaseEntityEnum> meta) {
- List<DepthStratum> depthStratums = getEntities(DepthStratum.class);
+ List<DepthStratum> depthStratums =
+ getEchoBasePersistenceContext().getDepthStratumDAO().findAll();
EntityCsvModel<EchoBaseEntityEnum,Strata> model = EntityCsvModel.newModel(
getCsvSeparator(),
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VesselLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VesselLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VesselLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -49,8 +49,8 @@
@Override
protected EntityCsvModel<EchoBaseEntityEnum, Vessel> createCsvImportModel(TableMeta<EchoBaseEntityEnum> meta) {
- List<VesselType> vesselTypesByName = getEntities(
- VesselType.class);
+ List<VesselType> vesselTypesByName =
+ getEchoBasePersistenceContext().getVesselTypeDAO().findAll();
EntityCsvModel<EchoBaseEntityEnum,Vessel> model = EntityCsvModel.newModel(
getCsvSeparator(),
Modified: trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VoyageLoader.java
===================================================================
--- trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VoyageLoader.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/main/java/fr/ifremer/echobase/tools/loaders/VoyageLoader.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -29,7 +29,6 @@
import com.healthmarketscience.jackcess.Table;
import fr.ifremer.echobase.EchoBaseFunctions;
import fr.ifremer.echobase.EchoBaseTechnicalException;
-import org.nuiton.topia.persistence.csv.in.AbstractImportModel;
import fr.ifremer.echobase.csv.EchoBaseCsvUtil;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
import fr.ifremer.echobase.entities.data.Echotype;
@@ -40,16 +39,17 @@
import fr.ifremer.echobase.entities.references.EchotypeCategory;
import fr.ifremer.echobase.entities.references.Mission;
import fr.ifremer.echobase.entities.references.Species;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.tools.FileType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.nuiton.csv.Import;
+import org.nuiton.csv.ImportModel;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.csv.in.AbstractImportModel;
import org.nuiton.topia.persistence.metadata.AssociationMeta;
import org.nuiton.topia.persistence.metadata.TableMeta;
-import org.nuiton.csv.Import;
-import org.nuiton.csv.ImportModel;
import java.io.BufferedReader;
import java.io.File;
@@ -158,8 +158,7 @@
AssociationMeta<EchoBaseEntityEnum> echotypeSpeciesAssociationMeta =
echotypeMeta.getAssociations(Echotype.PROPERTY_SPECIES);
- DbEditorService dbEditorService =
- getService(DbEditorService.class);
+ DbEditorService dbEditorService = getDbEditorService();
try {
BufferedReader bf = new BufferedReader(new FileReader(csvfile));
@@ -193,7 +192,7 @@
keystoTopiaId.put(key, topiaId);
Echotype echotypeSaved =
- dbEditorService.getEntityById(Echotype.class, topiaId);
+ getEchoBasePersistenceContext().getEntityById(Echotype.class, topiaId);
echotypeSaved.addSpecies(row.getSpecies());
row.getVoyage().addEchotype(echotypeSaved);
}
@@ -229,7 +228,7 @@
} finally {
if (cleanTransaction) {
- serviceContext.getTransaction().rollbackTransaction();
+ getEchoBasePersistenceContext().rollbackTransaction();
}
}
}
Modified: trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/AbstractToolTest.java
===================================================================
--- trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/AbstractToolTest.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/AbstractToolTest.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,25 +23,21 @@
*/
package fr.ifremer.echobase.tools;
-import fr.ifremer.echobase.EchoBaseConfiguration;
-import fr.ifremer.echobase.EchoBaseConfigurationOption;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfigurationOption;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
import fr.ifremer.echobase.persistence.JdbcConfiguration;
-import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
import fr.ifremer.echobase.services.DefaultEchoBaseServiceContext;
-import fr.ifremer.echobase.services.EchoBaseService;
import fr.ifremer.echobase.services.EchoBaseServiceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.TopiaEntity;
import java.io.File;
import java.util.Locale;
@@ -79,42 +75,35 @@
log.debug("Test directory = " + testdir);
}
+ JdbcConfiguration dbConf = JdbcConfiguration.newEmbeddedConfig(testdir);
+
+ topiaContext = EchobaseTopiaContexts.newWorkingDb(dbConf);
+
+ // init configuration
+
Properties defaultProps = new Properties();
defaultProps.put(EchoBaseConfigurationOption.DATA_DIRECTORY.getKey(), testdir);
-
configuration = new EchoBaseConfiguration(defaultProps);
- JdbcConfiguration dbConf = JdbcConfiguration.newEmbeddedConfig(testdir);
-
- topiaContext = EchobaseTopiaContexts.newWorkingDb(
- dbConf);
-
serviceContext = DefaultEchoBaseServiceContext.newContext(
Locale.getDefault(),
- null,
- topiaContext.beginTransaction(),
configuration,
- EchoBaseDbMeta.newDbMeta()
+ EchoBaseDbMeta.newDbMeta(),
+ null
+
);
+ serviceContext.setEchoBasePersistenceContext(new TopiaEchoBasePersistenceContext(topiaContext.beginTransaction()));
}
@After
public void tearDown() throws Exception {
try {
- serviceContext.getTransaction().closeContext();
+ serviceContext.getEchoBasePersistenceContext().closeContext();
} finally {
+
topiaContext.closeContext();
}
}
- public <E extends EchoBaseService> E getService(Class<E> clazz) {
- return serviceContext.getService(clazz);
- }
-
- protected <E extends TopiaEntity> TopiaDAO<E> getDao(Class<E> entityClass) throws TopiaException {
- TopiaDAO<E> dao = serviceContext.getDbMeta().getPersistenceHelper().getDAO(serviceContext.getTransaction(), entityClass);
- return dao;
- }
-
}
Modified: trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/AbstractLoaderIT.java
===================================================================
--- trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/AbstractLoaderIT.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/AbstractLoaderIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -28,7 +28,7 @@
import com.google.common.collect.Sets;
import com.healthmarketscience.jackcess.Database;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.importdb.ImportService;
+import fr.ifremer.echobase.services.service.importdb.ImportService;
import fr.ifremer.echobase.tools.AbstractToolTest;
import fr.ifremer.echobase.tools.FileType;
import fr.ifremer.echobase.tools.TestHelper;
@@ -115,7 +115,7 @@
FileUtil.createDirectoryIfNecessary(exportdir);
// get loader
- loader = getService(loaderType);
+ loader = serviceContext.newService(loaderType);
if (loadDependencies) {
loadDependencies();
@@ -264,7 +264,7 @@
}
private TopiaDAO<E> getDAO() throws TopiaException {
- return getDao(loader.getEntityClass());
+ return serviceContext.getEchoBasePersistenceContext().getDAO(loader.getEntityClass());
}
private File getTableFile(FileType fileType) throws IOException {
@@ -289,7 +289,7 @@
if (log.isInfoEnabled()) {
log.info("Import " + inFile);
}
- CsvImportResult<EchoBaseEntityEnum> csvImportResult = getService(ImportService.class).importDatas(
+ CsvImportResult<EchoBaseEntityEnum> csvImportResult = serviceContext.newService(ImportService.class).importDatas(
loader.getEntityType(),
inFile.getAbsolutePath(),
inFile,
@@ -333,43 +333,43 @@
public List<EntityLoader<?>> getEntityLoaders() {
if (entityLoaders == null) {
entityLoaders = Lists.newArrayList();
- entityLoaders.add(getService(SpeciesLoader.class));
- entityLoaders.add(getService(MissionLoader.class));
- entityLoaders.add(getService(AreaOfOperationLoader.class));
- entityLoaders.add(getService(AcousticInstrumentLoader.class));
- entityLoaders.add(getService(DepthStratumLoader.class));
- entityLoaders.add(getService(DataQualityLoader.class));
- entityLoaders.add(getService(ReferenceDatumTypeLoader.class));
- entityLoaders.add(getService(ReferenceDatumLoader.class));
- entityLoaders.add(getService(DataTypeLoader.class));
- entityLoaders.add(getService(CellTypeLoader.class));
- entityLoaders.add(getService(CellMethodLoader.class));
- entityLoaders.add(getService(DataMetadataLoader.class));
- entityLoaders.add(getService(TSParametersLoader.class));
- entityLoaders.add(getService(StrataLoader.class));
- entityLoaders.add(getService(EchotypeCategoryLoader.class));
- entityLoaders.add(getService(VesselTypeLoader.class));
- entityLoaders.add(getService(VesselLoader.class));
- entityLoaders.add(getService(OperationEventLoader.class));
- entityLoaders.add(getService(SampleDataTypeLoader.class));
- entityLoaders.add(getService(SampleTypeLoader.class));
- entityLoaders.add(getService(LengthAgeKeyLoader.class));
- entityLoaders.add(getService(LengthWeightKeyLoader.class));
- entityLoaders.add(getService(SexCategoryLoader.class));
- entityLoaders.add(getService(SizeCategoryLoader.class));
- entityLoaders.add(getService(OperationMetadataLoader.class));
- entityLoaders.add(getService(GearMetadataLoader.class));
- entityLoaders.add(getService(GearLoader.class));
- entityLoaders.add(getService(AgeCategoryLoader.class));
- entityLoaders.add(getService(SpeciesCategoryLoader.class));
+ entityLoaders.add(serviceContext.newService(SpeciesLoader.class));
+ entityLoaders.add(serviceContext.newService(MissionLoader.class));
+ entityLoaders.add(serviceContext.newService(AreaOfOperationLoader.class));
+ entityLoaders.add(serviceContext.newService(AcousticInstrumentLoader.class));
+ entityLoaders.add(serviceContext.newService(DepthStratumLoader.class));
+ entityLoaders.add(serviceContext.newService(DataQualityLoader.class));
+ entityLoaders.add(serviceContext.newService(ReferenceDatumTypeLoader.class));
+ entityLoaders.add(serviceContext.newService(ReferenceDatumLoader.class));
+ entityLoaders.add(serviceContext.newService(DataTypeLoader.class));
+ entityLoaders.add(serviceContext.newService(CellTypeLoader.class));
+ entityLoaders.add(serviceContext.newService(CellMethodLoader.class));
+ entityLoaders.add(serviceContext.newService(DataMetadataLoader.class));
+ entityLoaders.add(serviceContext.newService(TSParametersLoader.class));
+ entityLoaders.add(serviceContext.newService(StrataLoader.class));
+ entityLoaders.add(serviceContext.newService(EchotypeCategoryLoader.class));
+ entityLoaders.add(serviceContext.newService(VesselTypeLoader.class));
+ entityLoaders.add(serviceContext.newService(VesselLoader.class));
+ entityLoaders.add(serviceContext.newService(OperationEventLoader.class));
+ entityLoaders.add(serviceContext.newService(SampleDataTypeLoader.class));
+ entityLoaders.add(serviceContext.newService(SampleTypeLoader.class));
+ entityLoaders.add(serviceContext.newService(LengthAgeKeyLoader.class));
+ entityLoaders.add(serviceContext.newService(LengthWeightKeyLoader.class));
+ entityLoaders.add(serviceContext.newService(SexCategoryLoader.class));
+ entityLoaders.add(serviceContext.newService(SizeCategoryLoader.class));
+ entityLoaders.add(serviceContext.newService(OperationMetadataLoader.class));
+ entityLoaders.add(serviceContext.newService(GearMetadataLoader.class));
+ entityLoaders.add(serviceContext.newService(GearLoader.class));
+ entityLoaders.add(serviceContext.newService(AgeCategoryLoader.class));
+ entityLoaders.add(serviceContext.newService(SpeciesCategoryLoader.class));
- entityLoaders.add(getService(VoyageLoader.class));
- entityLoaders.add(getService(TransitLoader.class));
- entityLoaders.add(getService(TransectLoader.class));
- entityLoaders.add(getService(DataAcquisitionLoader.class));
- entityLoaders.add(getService(DataProcessingLoader.class));
- entityLoaders.add(getService(CellLoader.class));
- entityLoaders.add(getService(OperationLoader.class));
+ entityLoaders.add(serviceContext.newService(VoyageLoader.class));
+ entityLoaders.add(serviceContext.newService(TransitLoader.class));
+ entityLoaders.add(serviceContext.newService(TransectLoader.class));
+ entityLoaders.add(serviceContext.newService(DataAcquisitionLoader.class));
+ entityLoaders.add(serviceContext.newService(DataProcessingLoader.class));
+ entityLoaders.add(serviceContext.newService(CellLoader.class));
+ entityLoaders.add(serviceContext.newService(OperationLoader.class));
}
return entityLoaders;
}
Modified: trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/CellLoaderIT.java
===================================================================
--- trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/CellLoaderIT.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-tools/src/test/java/fr/ifremer/echobase/tools/loaders/CellLoaderIT.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -32,7 +32,7 @@
import fr.ifremer.echobase.entities.data.Cell;
import fr.ifremer.echobase.entities.data.DataProcessing;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.tools.FileType;
import fr.ifremer.echobase.tools.TestHelper;
import org.apache.commons.collections.CollectionUtils;
Modified: trunk/echobase-ui/pom.xml
===================================================================
--- trunk/echobase-ui/pom.xml 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/pom.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -138,10 +138,12 @@
<configuration>
<path>/echobase</path>
<uriEncoding>UTF-8</uriEncoding>
+ <!--<fork>true</fork>-->
<systemProperties>
<echobase.log.dir>
${project.build.directory}/echobase.log
</echobase.log.dir>
+ <JAVA_OPTS>-Xms512m -Xmx2048m -XX:MaxPermSize=256m</JAVA_OPTS>
</systemProperties>
</configuration>
</plugin>
@@ -156,6 +158,7 @@
<echobase.log.dir>
${project.build.directory}/echobase.log
</echobase.log.dir>
+ <JAVA_OPTS>-Xms512m -Xmx2048m -XX:MaxPermSize=256m</JAVA_OPTS>
</systemProperties>
</configuration>
</plugin>
Modified: trunk/echobase-ui/src/main/assembly/dist/help.sql
===================================================================
--- trunk/echobase-ui/src/main/assembly/dist/help.sql 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/assembly/dist/help.sql 2013-08-15 10:53:16 UTC (rev 842)
@@ -1,8 +1,8 @@
---
-- #%L
-- EchoBase :: UI
--- $Id:$
--- $HeadURL:$
+-- $Id$
+-- $HeadURL$
-- %%
-- Copyright (C) 2011 - 2013 Ifremer, Codelutin
-- %%
@@ -64,6 +64,8 @@
-- esdu fr.ifremer.echobase.entities.data.Cell#1334269715614#0.1761358511840082
+-- esdu fr.ifremer.echobase.entities.data.Cell#1348330016210#0.934653007293087
+
-- get all elementary
SELECT
*
Property changes on: trunk/echobase-ui/src/main/assembly/dist/help.sql
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/assembly/dist/postgis-structure.sql
===================================================================
--- trunk/echobase-ui/src/main/assembly/dist/postgis-structure.sql 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/assembly/dist/postgis-structure.sql 2013-08-15 10:53:16 UTC (rev 842)
@@ -234,7 +234,7 @@
RETURNS VOID AS $$
BEGIN
- RAISE NOTICE 'Treat spatial cell % [type %] ...', cell_id, cell_type;
+ RAISE LOG 'Treat spatial cell % [type %] ...', cell_id, cell_type;
CASE cell_type
WHEN 'ESDU'
THEN
@@ -330,11 +330,22 @@
SELECT
echobase_latitudetext_to_dd(latitude)
INTO latitudeNumber;
+
+ IF latitude IS NOT NULL AND latitudeNumber IS NULL
+ THEN
+ latitudeNumber := latitude :: REAL;
+ END IF;
+
-- convert dms longitude to dd longitude
SELECT
echobase_longitudetext_to_dd(longitude)
INTO longitudeNumber;
+ IF longitude IS NOT NULL AND longitudeNumber IS NULL
+ THEN
+ longitudeNumber := longitude :: REAL;
+ END IF;
+
SELECT
'SRID=4326;POINT(' || longitudeNumber || ' ' || latitudeNumber || ')'
INTO spatialText;
@@ -474,11 +485,22 @@
SELECT
echobase_latitudetext_to_dd(latitude)
INTO latitudeNumber;
+
+ IF latitude IS NOT NULL AND latitudeNumber IS NULL
+ THEN
+ latitudeNumber := latitude :: REAL;
+ END IF;
+
-- convert dms longitude to dd longitude
SELECT
echobase_longitudetext_to_dd(longitude)
INTO longitudeNumber;
+ IF longitude IS NOT NULL AND longitudeNumber IS NULL
+ THEN
+ longitudeNumber := longitude :: REAL;
+ END IF;
+
SELECT
'SRID=4326;POINTZ(' || longitudeNumber || ' ' || latitudeNumber || ' ' ||
depth || ')'
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationContext.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationContext.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationContext.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,13 +26,29 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import com.opensymphony.xwork2.ActionContext;
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
+import fr.ifremer.echobase.entities.spatial.SpatialDataCache;
import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
+import fr.ifremer.echobase.persistence.EchoBaseEntityHelper;
+import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
+import fr.ifremer.echobase.services.DefaultEchoBaseServiceContext;
+import fr.ifremer.echobase.services.EchoBaseServiceContext;
+import fr.ird.converter.FloatConverter;
+import org.apache.commons.beanutils.ConvertUtils;
+import org.apache.commons.beanutils.Converter;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.nuiton.i18n.I18n;
+import org.nuiton.i18n.init.DefaultI18nInitializer;
import org.nuiton.topia.TopiaContext;
+import org.nuiton.util.converter.ConverterUtil;
import javax.servlet.ServletContext;
+import java.beans.Introspector;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -50,24 +66,9 @@
private static final String APPLICATION_CONTEXT_PARAMETER =
"echobaseApplicationContext";
- protected EchoBaseConfiguration configuration;
-
- protected EchoBaseDbMeta dbMeta;
-
- /** Root context for the internal database. */
- protected TopiaContext internalRootContext;
-
/** Set of all loggued user sessions to be close at shutdown time. */
protected Set<EchoBaseSession> sessions;
- /**
- * Flag setted to true when internal db was just created (should then
- * display in ui created user password).
- *
- * @since 1.1
- */
- protected boolean defaultUsersCreated;
-
public static EchoBaseApplicationContext getApplicationContext(ActionContext actionContext) {
Map<String, Object> application = actionContext.getApplication();
EchoBaseApplicationContext result =
@@ -93,6 +94,33 @@
servletContext.removeAttribute(APPLICATION_CONTEXT_PARAMETER);
}
+ protected EchoBaseConfiguration configuration;
+
+ protected EchoBaseDbMeta dbMeta;
+
+ /** Root context for the internal database. */
+ protected TopiaContext internalRootContext;
+
+ /**
+ * Flag setted to true when internal db was just created (should then
+ * display in ui created user password).
+ *
+ * @since 1.1
+ */
+ protected boolean defaultUsersCreated;
+
+ /**
+ * A simple cache of spatial data.
+ *
+ * @since 2.2
+ */
+ protected final SpatialDataCache spatialDataCache;
+
+ public EchoBaseApplicationContext() {
+
+ spatialDataCache = new SpatialDataCache();
+ }
+
public Set<EchoBaseSession> getEchoBaseSessions() {
return sessions;
}
@@ -124,35 +152,144 @@
session.close();
}
+ public void init() {
+
+ // init I18n
+ DefaultI18nInitializer i18nInitializer =
+ new DefaultI18nInitializer("echobase-i18n");
+ i18nInitializer.setMissingKeyReturnNull(true);
+ I18n.init(i18nInitializer, Locale.getDefault());
+
+ // init converters
+ Converter converter = ConverterUtil.getConverter(Float.class);
+ if (converter != null) {
+ ConvertUtils.deregister(Float.class);
+ }
+ ConvertUtils.register(new FloatConverter(), Float.class);
+
+ // initialize configuration
+ EchoBaseConfiguration configuration = new EchoBaseConfiguration();
+
+ // initialize internal root context
+ TopiaContext internalRootContext =
+ EchobaseTopiaContexts.newInternalDb(
+ configuration.getInternalDbDirectory());
+
+ setConfiguration(configuration);
+ setDbMeta(EchoBaseDbMeta.newDbMeta());
+ setInternalRootContext(internalRootContext);
+ }
+
public EchoBaseConfiguration getConfiguration() {
return configuration;
}
- public void setConfiguration(EchoBaseConfiguration configuration) {
- this.configuration = configuration;
+ public EchoBaseDbMeta getDbMeta() {
+ return dbMeta;
}
public TopiaContext getInternalRootContext() {
return internalRootContext;
}
- public void setInternalRootContext(TopiaContext internalRootContext) {
- this.internalRootContext = internalRootContext;
+ public boolean isDefaultUsersCreated() {
+ return defaultUsersCreated;
}
- public EchoBaseDbMeta getDbMeta() {
- return dbMeta;
+ public SpatialDataCache getSpatialDataCache() {
+ return spatialDataCache;
}
+ public EchoBaseServiceContext newServiceContext(Locale locale,
+ TopiaContext topiaInternalContext,
+ TopiaContext topiaContext) {
+
+ EchoBaseServiceContext newServiceContext =
+ DefaultEchoBaseServiceContext.newContext(
+ locale,
+ configuration,
+ dbMeta,
+ spatialDataCache);
+
+ TopiaEchoBaseInternalPersistenceContext internalPersistenceContext =
+ new TopiaEchoBaseInternalPersistenceContext(topiaInternalContext);
+
+ newServiceContext.setEchoBaseInternalPersistenceContext(
+ internalPersistenceContext);
+
+ TopiaEchoBasePersistenceContext persistenceContext =
+ new TopiaEchoBasePersistenceContext(topiaContext);
+
+ newServiceContext.setEchoBasePersistenceContext(persistenceContext);
+
+ return newServiceContext;
+ }
+
+ public void close() {
+
+ try {
+ spatialDataCache.clear();
+
+ if (internalRootContext != null) {
+ // release internal db
+ EchoBaseEntityHelper.releaseRootContext(internalRootContext);
+ }
+ } finally {
+
+ try {
+ // release all user sessions
+ if (CollectionUtils.isNotEmpty(sessions)) {
+ for (EchoBaseSession session : sessions) {
+ destroyEchoBaseSession(session);
+ }
+ }
+ } finally {
+ // see http://wiki.apache.org/commons/Logging/FrequentlyAskedQuestions#A_memory_le…
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ LogFactory.release(contextClassLoader);
+
+ Introspector.flushCaches();
+ }
+ }
+ }
+
public void setDbMeta(EchoBaseDbMeta dbMeta) {
this.dbMeta = dbMeta;
}
- public boolean isDefaultUsersCreated() {
- return defaultUsersCreated;
+ public void setInternalRootContext(TopiaContext internalRootContext) {
+ this.internalRootContext = internalRootContext;
}
public void setDefaultUsersCreated(boolean defaultUsersCreated) {
this.defaultUsersCreated = defaultUsersCreated;
}
+
+ public void setConfiguration(EchoBaseConfiguration configuration) {
+ this.configuration = configuration;
+ }
+
+// protected final EventListenerList listenerList = new EventListenerList();
+//
+// public void addWorkingDbChangeListener(WorkingDbChangeListener listener) {
+// listenerList.add(WorkingDbChangeListener.class, listener);
+// }
+//
+// public void removeWorkingDbChangeListener(WorkingDbChangeListener listener) {
+// listenerList.remove(WorkingDbChangeListener.class, listener);
+// }
+//
+// public void fireVoyageChangeEvent(String jdbcUrl, String voyageId) {
+// VoyageChangedEvent event = new VoyageChangedEvent(jdbcUrl, voyageId);
+// for (WorkingDbChangeListener listener : listenerList.getListeners(WorkingDbChangeListener.class)) {
+// listener.onVoyageChanged(event);
+// }
+// }
+//
+// public void fireDbChangeEvent(String jdbcUrl) {
+// DbChangedEvent event = new DbChangedEvent(jdbcUrl);
+// for (WorkingDbChangeListener listener : listenerList.getListeners(WorkingDbChangeListener.class)) {
+// listener.onDbChanged(event);
+// }
+// }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,39 +24,31 @@
package fr.ifremer.echobase.ui;
import com.google.common.base.Preconditions;
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
import fr.ifremer.echobase.entities.DriverType;
import fr.ifremer.echobase.entities.EchoBaseUser;
+import fr.ifremer.echobase.entities.TopiaEchoBaseInternalPersistenceContext;
import fr.ifremer.echobase.persistence.EchoBaseDbMeta;
import fr.ifremer.echobase.persistence.EchoBaseEntityHelper;
-import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
import fr.ifremer.echobase.services.DefaultEchoBaseServiceContext;
import fr.ifremer.echobase.services.EchoBaseServiceContext;
-import fr.ifremer.echobase.services.UserService;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationService;
-import fr.ifremer.echobase.services.workingDb.WorkingDbConfigurationService;
-import fr.ird.converter.FloatConverter;
-import org.apache.commons.beanutils.ConvertUtils;
-import org.apache.commons.beanutils.Converter;
+import fr.ifremer.echobase.services.service.embeddedapplication.EmbeddedApplicationService;
+import fr.ifremer.echobase.services.service.UserService;
+import fr.ifremer.echobase.services.service.workingDb.WorkingDbConfigurationService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.i18n.I18n;
-import org.nuiton.i18n.init.DefaultI18nInitializer;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.util.converter.ConverterUtil;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
-import java.beans.Introspector;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Locale;
-import java.util.Set;
/**
* To listen start or end of the application.
@@ -99,51 +91,27 @@
log.info("Application starting at " + new Date() + "...");
}
- // init I18n
- DefaultI18nInitializer i18nInitializer =
- new DefaultI18nInitializer("echobase-i18n");
- i18nInitializer.setMissingKeyReturnNull(true);
- I18n.init(i18nInitializer, Locale.getDefault());
-
- // init converters
- Converter converter = ConverterUtil.getConverter(Float.class);
- if (converter != null) {
- ConvertUtils.deregister(Float.class);
- }
- ConvertUtils.register(new FloatConverter(), Float.class);
-
- // initialize configuration
- EchoBaseConfiguration configuration = new EchoBaseConfiguration();
-
- // initialize internal root context
- TopiaContext internalRootContext =
- EchobaseTopiaContexts.newInternalDb(
- configuration.getInternalDbDirectory());
-
// initialize application context
EchoBaseApplicationContext applicationContext =
new EchoBaseApplicationContext();
+
EchoBaseApplicationContext.setApplicationContext(
sce.getServletContext(), applicationContext);
- applicationContext.setConfiguration(configuration);
- applicationContext.setDbMeta(EchoBaseDbMeta.newDbMeta());
- applicationContext.setInternalRootContext(internalRootContext);
+ applicationContext.init();
+ // create a service context
EchoBaseServiceContext serviceContext =
DefaultEchoBaseServiceContext.newContext(
Locale.getDefault(),
- null,
- null,
- configuration,
- applicationContext.getDbMeta()
- );
+ applicationContext.getConfiguration(),
+ applicationContext.getDbMeta(),
+ applicationContext.getSpatialDataCache());
// init database (and create minimal admin user if required)
initInternalDatabase(applicationContext, serviceContext);
-
// copy drivers if required
try {
copyDriverFiles(serviceContext);
@@ -167,27 +135,28 @@
// remove application context from container
EchoBaseApplicationContext.removeApplicationContext(servletContext);
- try {
- // release internal db
- TopiaContext rootContext =
- applicationContext.getInternalRootContext();
- EchoBaseEntityHelper.releaseRootContext(rootContext);
- } finally {
+ applicationContext.close();
- // release all user sessions
- Set<EchoBaseSession> sessions = applicationContext.getEchoBaseSessions();
- if (CollectionUtils.isNotEmpty(sessions)) {
- for (EchoBaseSession session : sessions) {
- applicationContext.destroyEchoBaseSession(session);
- }
- }
+// // release internal db
+// TopiaContext rootContext =
+// applicationContext.getInternalRootContext();
+// EchoBaseEntityHelper.releaseRootContext(rootContext);
+// finally {
- // see http://wiki.apache.org/commons/Logging/FrequentlyAskedQuestions#A_memory_le…
- ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
- LogFactory.release(contextClassLoader);
+// // release all user sessions
+// Set<EchoBaseSession> sessions = applicationContext.getEchoBaseSessions();
+// if (CollectionUtils.isNotEmpty(sessions)) {
+// for (EchoBaseSession session : sessions) {
+// applicationContext.destroyEchoBaseSession(session);
+// }
+// }
- Introspector.flushCaches();
- }
+// // see http://wiki.apache.org/commons/Logging/FrequentlyAskedQuestions#A_memory_le…
+// ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+// LogFactory.release(contextClassLoader);
+//
+// Introspector.flushCaches();
+// }
}
/**
@@ -224,9 +193,9 @@
TopiaContext tx = rootContext.beginTransaction();
try {
- serviceContext.setInternalTransaction(tx);
+ serviceContext.setEchoBaseInternalPersistenceContext(new TopiaEchoBaseInternalPersistenceContext(tx));
- UserService service = serviceContext.getService(UserService.class);
+ UserService service = serviceContext.newService(UserService.class);
List<EchoBaseUser> users = service.getUsers();
@@ -248,18 +217,18 @@
"configuration for embedded db.");
}
// try to create a default embedded working db configuration
- serviceContext.getService(WorkingDbConfigurationService.class).
+ serviceContext.newService(WorkingDbConfigurationService.class).
createEmbeddedWorkingDbConfiguration();
}
} finally {
- serviceContext.setInternalTransaction(null);
+ serviceContext.setEchoBaseInternalPersistenceContext(null);
EchoBaseEntityHelper.closeConnection(tx);
}
}
protected void copyDriverFiles(EchoBaseServiceContext serviceContext) throws IOException {
EmbeddedApplicationService service =
- serviceContext.getService(EmbeddedApplicationService.class);
+ serviceContext.newService(EmbeddedApplicationService.class);
EchoBaseConfiguration configuration = serviceContext.getConfiguration();
File libDirectory = configuration.getLibDirectory();
for (DriverType driverType : DriverType.values()) {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseInternalDbTransactionFilter.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseInternalDbTransactionFilter.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseInternalDbTransactionFilter.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,6 @@
package fr.ifremer.echobase.ui;
import com.opensymphony.xwork2.ActionContext;
-import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
@@ -55,7 +54,7 @@
@Override
protected /*synchronized*/ TopiaContext beginTransaction(ServletRequest request) {
EchoBaseApplicationContext applicationContext =
- EchoBaseActionSupport.getEchoBaseApplicationContext();
+ EchoBaseApplicationContext.getApplicationContext(request.getServletContext());
TopiaContext rootContext = applicationContext.getInternalRootContext();
TopiaContext transaction = rootContext.beginTransaction();
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseSession.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,6 +23,7 @@
*/
package fr.ifremer.echobase.ui;
+import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.opensymphony.xwork2.ActionContext;
@@ -31,6 +32,9 @@
import fr.ifremer.echobase.persistence.EchobaseTopiaContexts;
import fr.ifremer.echobase.persistence.JdbcConfiguration;
import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
+import fr.ifremer.echobase.entities.spatial.SpatialData;
+import fr.ifremer.echobase.ui.actions.spatial.ShowSpatialModel;
+import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.topia.TopiaContext;
@@ -39,6 +43,8 @@
import javax.servlet.http.HttpSession;
import java.io.Closeable;
import java.io.Serializable;
+import java.util.Collection;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@@ -66,6 +72,9 @@
/** Key to set root context of working db selected by user (if any). */
private static final String PROPERTY_WORKING_DB_ROOT_CONTEXT = "workingDbRootContext";
+ /** Key to set spatial data list. */
+ private static final String PROPERTY_SPATIAL_DATA = "spatialData";
+
public static final String SESSION_TOKEN_MESSAGES = "messages";
public static final String SESSION_TOKEN_ERRORS = "errors";
@@ -263,13 +272,6 @@
}
}
- protected Map<String, Object> getDynamicData() {
- if (store == null) {
- store = Maps.newHashMap();
- }
- return store;
- }
-
public void addMessage(String messageScope, String message) {
Set<String> messages = getDynamicSetData(messageScope);
if (messages == null) {
@@ -280,6 +282,36 @@
}
}
+ public Set<SpatialData> getSpatialData(ShowSpatialModel model) {
+ List<ShowSpatialModel> list = get(PROPERTY_SPATIAL_DATA, List.class);
+ Set<SpatialData> result = null;
+ if (list != null) {
+ int i = list.indexOf(model);
+ if (i != -1) {
+ ShowSpatialModel showSpatialModel = list.get(i);
+ result = showSpatialModel.getSpatialData();
+ }
+ }
+
+ return result;
+ }
+
+ public void setSpatialData(ShowSpatialModel model) {
+ List<ShowSpatialModel> list = get(PROPERTY_SPATIAL_DATA, List.class);
+ if (list == null) {
+ list = Lists.newArrayList();
+ set(PROPERTY_SPATIAL_DATA, list);
+ }
+ list.add(model);
+ }
+
+ protected Map<String, Object> getDynamicData() {
+ if (store == null) {
+ store = Maps.newHashMap();
+ }
+ return store;
+ }
+
/** Protect session constructor. */
protected EchoBaseSession() {
store = new TreeMap<String, Object>();
@@ -304,7 +336,7 @@
*
* @param key the key to test in this session
* @return {@code true} if an object was found in this session,
- * {@code false} otherwise
+ * {@code false} otherwise
*/
protected boolean contains(String key) {
boolean result = store.containsKey(key);
@@ -370,4 +402,34 @@
}
}
}
+
+ public boolean isWithFlashMessages() {
+ Collection<String> result = getDynamicSetData(EchoBaseSession.SESSION_TOKEN_MESSAGES);
+ return CollectionUtils.isNotEmpty(result);
+ }
+
+ public boolean isWithFlashErrors() {
+ Collection<String> result = getDynamicSetData(EchoBaseSession.SESSION_TOKEN_ERRORS);
+ return CollectionUtils.isNotEmpty(result);
+ }
+
+ public boolean isWithFlashWarnings() {
+ Collection<String> result = getDynamicSetData(EchoBaseSession.SESSION_TOKEN_WARNINGS);
+ return CollectionUtils.isNotEmpty(result);
+ }
+
+ public Collection<String> getFlashMessages() {
+ Collection<String> result = consumeDynamicSetData(EchoBaseSession.SESSION_TOKEN_MESSAGES);
+ return result;
+ }
+
+ public Collection<String> getFlashErrors() {
+ Collection<String> result = consumeDynamicSetData(EchoBaseSession.SESSION_TOKEN_ERRORS);
+ return result;
+ }
+
+ public Collection<String> getFlashWarnings() {
+ Collection<String> result = consumeDynamicSetData(EchoBaseSession.SESSION_TOKEN_WARNINGS);
+ return result;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractConfigureAction.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractConfigureAction.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractConfigureAction.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,6 +25,8 @@
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -99,4 +101,19 @@
return getEchoBaseSession().getActionConfiguration(modelType);
}
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient DecoratorService decoratorService;
+
+ public void setDecoratorService(DecoratorService decoratorService) {
+ this.decoratorService = decoratorService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractWaitAndExecAction.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractWaitAndExecAction.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/AbstractWaitAndExecAction.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,6 +25,7 @@
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.Preparable;
+import fr.ifremer.echobase.entities.TopiaEchoBasePersistenceContext;
import fr.ifremer.echobase.persistence.EchoBaseEntityHelper;
import fr.ifremer.echobase.services.AbstractEchobaseActionConfiguration;
import fr.ifremer.echobase.services.EchoBaseService;
@@ -151,16 +152,15 @@
// in more than one request
TopiaContext tx = EchoBaseEntityHelper.newTransactionFromRootContext(
- getServiceContext().getTransaction());
+ getServiceContext().getEchoBasePersistenceContext().getContext());
try {
- getServiceContext().setTransaction(tx);
+ getServiceContext().setEchoBasePersistenceContext(new TopiaEchoBasePersistenceContext(tx));
- S service = getService(serviceType);
+ S service = getServiceContext().newService(serviceType);
startAction(service, model);
-
} catch (Exception e) {
model.setError(e);
} finally {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/EchoBaseActionSupport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/EchoBaseActionSupport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/EchoBaseActionSupport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,33 +24,16 @@
package fr.ifremer.echobase.ui.actions;
import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import com.opensymphony.xwork2.ActionContext;
-import fr.ifremer.echobase.EchoBaseConfiguration;
-import fr.ifremer.echobase.I18nAble;
-import fr.ifremer.echobase.services.DecoratorService;
-import fr.ifremer.echobase.services.DefaultEchoBaseServiceContext;
import fr.ifremer.echobase.services.EchoBaseService;
import fr.ifremer.echobase.services.EchoBaseServiceContext;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.ServiceFactoryAware;
import fr.ifremer.echobase.ui.EchoBaseApplicationContext;
-import fr.ifremer.echobase.ui.EchoBaseInternalDbTransactionFilter;
import fr.ifremer.echobase.ui.EchoBaseSession;
-import fr.ifremer.echobase.ui.EchoBaseWorkingDbTransactionFilter;
-import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
-import org.apache.struts2.interceptor.ParameterAware;
-import org.apache.struts2.interceptor.SessionAware;
-import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.web.struts2.BaseAction;
import java.text.SimpleDateFormat;
-import java.util.Collection;
import java.util.Date;
-import java.util.List;
import java.util.Locale;
-import java.util.Map;
/**
* EchoBase action support.
@@ -58,7 +41,7 @@
* @author tchemit <chemit(a)codelutin.com>
* @since 0.1
*/
-public class EchoBaseActionSupport extends BaseAction implements ServiceFactoryAware {
+public class EchoBaseActionSupport extends BaseAction {
private static final long serialVersionUID = 1L;
@@ -68,95 +51,12 @@
private static final SimpleDateFormat monthFormat =
new SimpleDateFormat("mm-yyyy");
- private static EchoBaseApplicationContext applicationContext;
-
- public static EchoBaseApplicationContext getEchoBaseApplicationContext() {
- if (applicationContext == null) {
- applicationContext = EchoBaseApplicationContext.getApplicationContext(
- getActionContext());
- }
- return applicationContext;
- }
-
- public static String getApplicationVersion() {
- return getEchoBaseApplicationContext().getConfiguration().getApplicationVersion().toString();
- }
-
- protected EchoBaseConfiguration getConfiguration() {
- return getEchoBaseApplicationContext().getConfiguration();
- }
-
- /** EchoBase User session. */
- private transient EchoBaseSession echoBaseSession;
-
- /**
- * Service context used to access and create services.
- *
- * @since 1.0
- */
- private transient EchoBaseServiceContext serviceContext;
-
- /**
- * Parameters injected if you put {@link ParameterAware} contract on your
- * action.
- *
- * @see ParameterAware
- * @since 1.1
- */
- private transient Map<String, String[]> parameters;
-
- /**
- * Session injected if you put {@link SessionAware} contract on your action.
- *
- * @see SessionAware
- * @since 1.1
- */
- private transient Map<String, Object> session;
-
- public EchoBaseSession getEchoBaseSession() {
- if (echoBaseSession == null) {
-
- // load it from session
- echoBaseSession = EchoBaseSession.getEchoBaseSession(getActionContext());
- }
- return echoBaseSession;
- }
-
- public EchoBaseServiceContext getServiceContext() {
- if (serviceContext == null) {
- serviceContext = DefaultEchoBaseServiceContext.newContext(
- getLocale(),
- EchoBaseInternalDbTransactionFilter.getTransaction(getActionContext()),
- EchoBaseWorkingDbTransactionFilter.getTransaction(getActionContext()),
- getConfiguration(),
- getEchoBaseApplicationContext().getDbMeta()
- );
- }
- return serviceContext;
- }
-
- /**
- * Sub-classes should use this method to easily get a service instance.
- *
- * @param serviceClass The type of service to instantiate
- * @return A newly created service of the expected type with necessary data set
- */
- @Override
- public <E extends EchoBaseService> E getService(Class<E> serviceClass) {
- E service = getServiceContext().getService(serviceClass);
+ protected <E extends EchoBaseService> E newService(Class<E> serviceClass) {
+ E service = getServiceContext().newService(serviceClass);
return service;
}
- public boolean isAdmin() {
- boolean result = getEchoBaseSession().isAdmin();
- return result;
- }
- public boolean isWorkingDbSelected() {
- boolean result = getEchoBaseSession().isWorkingDbSelected();
- return result;
- }
-
public String formatDate(Date date) {
String result = dateFormat.format(date);
return result;
@@ -167,14 +67,6 @@
return result;
}
- public void setParameters(Map<String, String[]> parameters) {
- this.parameters = parameters;
- }
-
- public void setSession(Map<String, Object> session) {
- this.session = session;
- }
-
public void addFlashMessage(String message) {
getEchoBaseSession().addMessage(EchoBaseSession.SESSION_TOKEN_MESSAGES, message);
}
@@ -187,57 +79,13 @@
getEchoBaseSession().addMessage(EchoBaseSession.SESSION_TOKEN_WARNINGS, message);
}
- public Collection<String> getFlashMessages() {
- Collection<String> result = getEchoBaseSession().consumeDynamicSetData(EchoBaseSession.SESSION_TOKEN_MESSAGES);
- return result;
- }
-
- public Collection<String> getFlashErrors() {
- Collection<String> result = getEchoBaseSession().consumeDynamicSetData(EchoBaseSession.SESSION_TOKEN_ERRORS);
- return result;
- }
-
- public Collection<String> getFlashWarnings() {
- Collection<String> result = getEchoBaseSession().consumeDynamicSetData(EchoBaseSession.SESSION_TOKEN_WARNINGS);
- return result;
- }
-
- public boolean hasFlashMessages() {
- Collection<String> result = getEchoBaseSession().getDynamicSetData(EchoBaseSession.SESSION_TOKEN_MESSAGES);
- return CollectionUtils.isNotEmpty(result);
- }
-
- public boolean hasFlashErrors() {
- Collection<String> result = getEchoBaseSession().getDynamicSetData(EchoBaseSession.SESSION_TOKEN_ERRORS);
- return CollectionUtils.isNotEmpty(result);
- }
-
- public boolean hasFlashWarnings() {
- Collection<String> result = getEchoBaseSession().getDynamicSetData(EchoBaseSession.SESSION_TOKEN_WARNINGS);
- return CollectionUtils.isNotEmpty(result);
- }
-
- public void clearFlashMessages() {
- Collection<String> result = getEchoBaseSession().getDynamicSetData(EchoBaseSession.SESSION_TOKEN_MESSAGES);
- if (result != null) {
- result.clear();
- }
- }
-
- public void clearFlashErrors() {
- Collection<String> result = getEchoBaseSession().getDynamicSetData(EchoBaseSession.SESSION_TOKEN_ERRORS);
- if (result != null) {
- result.clear();
- }
- }
-
public String getDocumentation(String page) {
return getDocumentation(page, null);
}
public String getDocumentation(String page, String anchor) {
Locale locale = getLocale();
- String result = getConfiguration().getDocumentationUrl().toString();
+ String result = getEchoBaseApplicationContext().getConfiguration().getDocumentationUrl().toString();
if (!result.endsWith("/")) {
result += "/";
}
@@ -251,46 +99,48 @@
return result;
}
- public boolean hasAnyErrors() {
- boolean result = super.hasErrors();
- return result || hasFlashErrors();
- }
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
- protected static ActionContext getActionContext() {
- return ActionContext.getContext();
- }
+ /** EchoBase Application context. */
+ private transient EchoBaseApplicationContext applicationContext;
- protected final <E extends Enum<E> & I18nAble> Map<String, String> decorateEnums(E... enumValues) {
- Map<String, String> result = Maps.newLinkedHashMap();
- for (E enumValue : enumValues) {
- result.put(enumValue.name(), _(enumValue.getI18nKey()));
- }
- return result;
- }
+ /** EchoBase User session. */
+ private transient EchoBaseSession echoBaseSession;
- protected final <E extends TopiaEntity> Map<String, String> loadSortAndDecorate(Class<E> beanType) {
+ /**
+ * Service context used to access and create services.
+ *
+ * @since 1.0
+ */
+ private transient EchoBaseServiceContext serviceContext;
- EchoBaseServiceSupport service = getService(EchoBaseServiceSupport.class);
- List<E> beans = service.getEntities(beanType);
+ public void setApplicationContext(EchoBaseApplicationContext applicationContext) {
+ this.applicationContext = applicationContext;
+ }
- DecoratorService decoratorService = getService(DecoratorService.class);
- return decoratorService.sortAndDecorate(getLocale(), beans, null);
+ public void setEchoBaseSession(EchoBaseSession echoBaseSession) {
+ this.echoBaseSession = echoBaseSession;
}
+ public void setServiceContext(EchoBaseServiceContext serviceContext) {
+ this.serviceContext = serviceContext;
+ }
- protected Map<String, String[]> getParameters() {
- Preconditions.checkNotNull(
- parameters,
- "You must put ParameterAware contract on your action " +
- getClass().getName());
- return parameters;
+ public EchoBaseApplicationContext getEchoBaseApplicationContext() {
+ Preconditions.checkNotNull("No applicationContext is your action " + this);
+ return applicationContext;
}
- protected Map<String, Object> getSession() {
- Preconditions.checkNotNull(
- session,
- "You must put SessionAware contract on your action " +
- getClass().getName());
- return session;
+ public EchoBaseSession getEchoBaseSession() {
+ Preconditions.checkNotNull("No echoBaseSession is your action " + this);
+ return echoBaseSession;
}
+
+ public EchoBaseServiceContext getServiceContext() {
+ Preconditions.checkNotNull("No serviceContext is your action " + this);
+ return serviceContext;
+ }
+
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/Home.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/Home.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/Home.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -36,7 +36,7 @@
@Override
public String execute() throws Exception {
- if (!isWorkingDbSelected()) {
+ if (!getEchoBaseSession().isWorkingDbSelected()) {
addFlashMessage(_("echobase.info.no.workingDb.selected"));
}
return SUCCESS;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/AbstractLoadPage.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/AbstractLoadPage.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/AbstractLoadPage.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,7 +25,7 @@
import com.google.common.collect.Maps;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.nuiton.topia.persistence.metadata.ColumnMeta;
import org.nuiton.topia.persistence.metadata.DbMeta;
@@ -48,28 +48,28 @@
/** Type of entity to load. */
protected EchoBaseEntityEnum entityType;
+ public void setEntityType(EchoBaseEntityEnum entityType) {
+ this.entityType = entityType;
+ }
+
+ public EchoBaseEntityEnum getEntityType() {
+ return entityType;
+ }
+
/** All entities availables. */
protected Map<String, String> entityTypes;
- /** Metas of the table. */
- protected TableMeta<EchoBaseEntityEnum> tableMeta;
-
public Map<String, String> getEntityTypes() {
return entityTypes;
}
+ /** Metas of the table. */
+ protected TableMeta<EchoBaseEntityEnum> tableMeta;
+
public List<ColumnMeta> getColumnMetas() {
return tableMeta.getColumns();
}
- public void setEntityType(EchoBaseEntityEnum entityType) {
- this.entityType = entityType;
- }
-
- public EchoBaseEntityEnum getEntityType() {
- return entityType;
- }
-
public void load() throws Exception {
entityTypes = Maps.newTreeMap();
DbMeta<EchoBaseEntityEnum> dbMeta = getEchoBaseApplicationContext().getDbMeta();
@@ -88,9 +88,18 @@
} else {
// load table metas
- DbEditorService dbEditorService = getService(DbEditorService.class);
tableMeta = dbEditorService.getTableMeta(entityType);
}
}
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
+
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ExportTable.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ExportTable.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ExportTable.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,8 @@
package fr.ifremer.echobase.ui.actions.dbeditor;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.exportdb.ExportService;
+import fr.ifremer.echobase.services.service.DbEditorService;
+import fr.ifremer.echobase.services.service.exportdb.ExportService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -49,55 +50,54 @@
/** Type of entity to export. */
protected EchoBaseEntityEnum entityType;
+ public void setEntityType(EchoBaseEntityEnum entityType) {
+ this.entityType = entityType;
+ }
+
/** Default file name to create. */
protected String exportFileName;
- /** Stream of the file to export. */
- protected transient InputStream inputStream;
-
- /** Length of the file to export. */
- protected long contentLength;
-
- /** Type of the file to export. */
- protected String contentType;
-
- /** Export datas as seen on screen (no topiaId). */
- protected boolean exportAsSeen;
-
- public void setEntityType(EchoBaseEntityEnum entityType) {
- this.entityType = entityType;
+ public String getExportFileName() {
+ return exportFileName;
}
public void setExportFileName(String exportFileName) {
this.exportFileName = exportFileName;
}
+ /** Export datas as seen on screen (no topiaId). */
+ protected boolean exportAsSeen;
+
public void setExportAsSeen(boolean exportAsSeen) {
this.exportAsSeen = exportAsSeen;
}
+ /** Stream of the file to export. */
+ protected transient InputStream inputStream;
+
public InputStream getInputStream() {
return inputStream;
}
+ /** Length of the file to export. */
+ protected long contentLength;
+
public long getContentLength() {
return contentLength;
}
+ /** Type of the file to export. */
+ protected String contentType;
+
public String getContentType() {
return contentType;
}
- public String getExportFileName() {
- return exportFileName;
- }
-
@Override
public String execute() throws Exception {
- TableMeta<EchoBaseEntityEnum> table = getServiceContext().getDbMeta().getTable(entityType);
- String content = getService(ExportService.class).exportData(table,
- exportAsSeen);
+ TableMeta<EchoBaseEntityEnum> table = dbEditorService.getTableMeta(entityType);
+ String content = exportService.exportData(table, exportAsSeen);
if (log.isDebugEnabled()) {
log.debug("file to export " + content);
@@ -108,4 +108,20 @@
inputStream = new ByteArrayInputStream(content.getBytes());
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
+
+ protected transient ExportService exportService;
+
+ public void setExportService(ExportService exportService) {
+ this.exportService = exportService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntities.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntities.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntities.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -32,16 +32,17 @@
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.DbEditorService;
-import fr.ifremer.echobase.services.DecoratorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
import fr.ifremer.echobase.ui.actions.AbstractJSONPaginedAction;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.nuiton.decorator.Decorator;
import org.nuiton.topia.persistence.pager.FilterRule;
import org.nuiton.topia.persistence.pager.FilterRuleGroupOperator;
import org.nuiton.topia.persistence.pager.FilterRuleOperator;
-import org.nuiton.decorator.Decorator;
import java.util.Arrays;
import java.util.Collection;
@@ -60,22 +61,22 @@
/** Logger. */
private static final Log log = LogFactory.getLog(GetEntities.class);
- /** Type of entity to load. */
- protected EchoBaseEntityEnum entityType;
-
- /** Datas of the given table. */
- protected Map<?, ?>[] datas;
-
protected String voyageId;
public void setVoyageId(String voyageId) {
this.voyageId = voyageId;
}
+ /** Type of entity to load. */
+ protected EchoBaseEntityEnum entityType;
+
public void setEntityType(EchoBaseEntityEnum entityType) {
this.entityType = entityType;
}
+ /** Datas of the given table. */
+ protected Map<?, ?>[] datas;
+
public Map<?, ?>[] getDatas() {
return datas;
}
@@ -94,7 +95,7 @@
log.debug("sord = " + ascendantOrder);
}
- datas = getService(DbEditorService.class).getData(entityType, pager);
+ datas = dbEditorService.getData(entityType, pager);
if (log.isDebugEnabled()) {
log.debug("Total page = " + getTotal());
@@ -122,16 +123,16 @@
pager.setGroupOp(FilterRuleGroupOperator.AND);
}
execute();
- Map<String, String> importTypes = decorateEnums(ImportType.values());
+ Map<String, String> importTypes =
+ decoratorService.decorateEnums(ImportType.values());
- DbEditorService service = getService(DbEditorService.class);
for (Map row : datas) {
String importType = (String) row.get(ImportLog.PROPERTY_IMPORT_TYPE);
String importTypeToString = importTypes.get(importType);
row.put(ImportLog.PROPERTY_IMPORT_TYPE, importTypeToString);
- service.decorateForeignKey(row, Voyage.class, ImportLog.PROPERTY_VOYAGE_ID, null);
+ dbEditorService.decorateForeignKey(row, Voyage.class, ImportLog.PROPERTY_VOYAGE_ID, null);
}
return SUCCESS;
}
@@ -140,14 +141,12 @@
entityType = EchoBaseEntityEnum.Voyage;
execute();
- DbEditorService service = getService(DbEditorService.class);
- DecoratorService decoratorService = getService(DecoratorService.class);
Decorator<ImportLog> importLogDecorator = decoratorService.getDecorator(
getLocale(), ImportLog.class, DecoratorService.DATE_ONLY);
Multimap<String, ImportLog> importLogsByVoyage = Multimaps.index(
- service.getEntities(ImportLog.class),
+ workingDbPersistenceService.getImportLogDAO().findAll(),
EchoBaseFunctions.IMPORT_LOG_VOYAGE_ID);
for (Map row : datas) {
@@ -156,7 +155,7 @@
Collection<ImportLog> importLogs = importLogsByVoyage.get(id);
- service.decorateForeignKey(row, Voyage.class, "id", null);
+ dbEditorService.decorateForeignKey(row, Voyage.class, "id", null);
// to keep importLogs decorated, indexed by their topiaId
Map<String, String> imports = Maps.newHashMap();
@@ -181,4 +180,26 @@
}
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
+
+ protected transient DecoratorService decoratorService;
+
+ public void setDecoratorService(DecoratorService decoratorService) {
+ this.decoratorService = decoratorService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntity.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntity.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetEntity.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,7 +25,7 @@
import com.google.common.collect.Maps;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.nuiton.topia.persistence.metadata.ColumnMeta;
import org.nuiton.topia.persistence.metadata.TableMeta;
@@ -46,23 +46,23 @@
/** Type of entity to load. */
protected EchoBaseEntityEnum entityType;
+ public void setEntityType(EchoBaseEntityEnum entityType) {
+ this.entityType = entityType;
+ }
+
/** Id of entity to load. */
protected String id;
+ public void setId(String id) {
+ this.id = id;
+ }
+
/** Datas of the given table. */
protected Map<?, ?> datas;
/** Universe of columns metat datas of the selected entity type. */
protected Map<String, ColumnMeta> metas;
- public void setEntityType(EchoBaseEntityEnum entityType) {
- this.entityType = entityType;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
public Map<?, ?> getDatas() {
return datas;
}
@@ -75,9 +75,9 @@
public String execute() throws Exception {
TableMeta<EchoBaseEntityEnum> table =
- getServiceContext().getDbMeta().getTable(entityType);
+ dbEditorService.getTableMeta(entityType);
- datas = getService(DbEditorService.class).getData(table, id);
+ datas = dbEditorService.getData(table, id);
Object length = datas.remove("length");
if (length != null) {
@@ -92,4 +92,14 @@
}
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetForeignEntities.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetForeignEntities.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/GetForeignEntities.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,6 +24,7 @@
package fr.ifremer.echobase.ui.actions.dbeditor;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.util.Map;
@@ -41,13 +42,13 @@
/** Type of entity to load. */
protected EchoBaseEntityEnum entityType;
- /** Entities loaded (key are id, values are decoration of entity). */
- protected Map<String, String> entities;
-
public void setEntityType(EchoBaseEntityEnum entityType) {
this.entityType = entityType;
}
+ /** Entities loaded (key are id, values are decoration of entity). */
+ protected Map<String, String> entities;
+
public Map<String, String> getEntities() {
return entities;
}
@@ -55,8 +56,18 @@
@Override
public String execute() throws Exception {
- entities = loadSortAndDecorate(entityType.getContract());
+ entities = workingDbPersistenceService.loadSortAndDecorate(entityType.getContract());
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ImportTable.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ImportTable.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/ImportTable.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,7 +25,7 @@
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.importdb.ImportService;
+import fr.ifremer.echobase.services.service.importdb.ImportService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -128,7 +128,7 @@
public String execute() throws Exception {
try {
- result = getService(ImportService.class).importDatas(
+ result = importService.importDatas(
getEntityType(),
importFileFileName,
importFile,
@@ -151,4 +151,15 @@
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient ImportService importService;
+
+ public void setImportService(ImportService importService) {
+ this.importService = importService;
+ }
+
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/SaveEntity.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/SaveEntity.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/dbeditor/SaveEntity.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,7 +25,7 @@
import com.google.common.collect.Maps;
import fr.ifremer.echobase.entities.EchoBaseEntityEnum;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.struts2.interceptor.ParameterAware;
import org.nuiton.topia.persistence.TopiaEntity;
@@ -47,16 +47,16 @@
/** Type of entity to save. */
protected EchoBaseEntityEnum entityType;
- /** id of entity to save. */
- protected String topiaId;
+ public void setEntityType(EchoBaseEntityEnum entityType) {
+ this.entityType = entityType;
+ }
public EchoBaseEntityEnum getEntityType() {
return entityType;
}
- public void setEntityType(EchoBaseEntityEnum entityType) {
- this.entityType = entityType;
- }
+ /** id of entity to save. */
+ protected String topiaId;
public void setTopiaId(String topiaId) {
this.topiaId = topiaId;
@@ -65,12 +65,10 @@
@Override
public String execute() throws Exception {
- DbEditorService service = getService(DbEditorService.class);
-
- TableMeta<EchoBaseEntityEnum> tableMeta = service.getTableMeta(entityType);
+ TableMeta<EchoBaseEntityEnum> tableMeta =
+ dbEditorService.getTableMeta(entityType);
Map<String, String> properties = Maps.newHashMap();
List<String> columnNames = tableMeta.getColumnNames();
- Map<String, String[]> parameters = getParameters();
for (String columnName : columnNames) {
if (parameters.containsKey(columnName)) {
@@ -89,11 +87,28 @@
}
properties.put(TopiaEntity.PROPERTY_TOPIA_ID, topiaId);
- service.saveEntity(tableMeta,
- properties,
- getEchoBaseSession().getUser());
+ dbEditorService.saveEntity(tableMeta,
+ properties,
+ getEchoBaseSession().getUser());
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ private transient Map<String, String[]> parameters;
+
+ @Override
+ public void setParameters(Map<String, String[]> parameters) {
+ this.parameters = parameters;
+ }
+
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Build.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Build.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Build.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.embeddedApplication;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationConfiguration;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationService;
+import fr.ifremer.echobase.services.service.embeddedapplication.EmbeddedApplicationConfiguration;
+import fr.ifremer.echobase.services.service.embeddedapplication.EmbeddedApplicationService;
import fr.ifremer.echobase.ui.actions.AbstractWaitAndExecAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Configure.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Configure.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Configure.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,9 +23,9 @@
*/
package fr.ifremer.echobase.ui.actions.embeddedApplication;
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationConfiguration;
+import fr.ifremer.echobase.services.service.embeddedapplication.EmbeddedApplicationConfiguration;
import fr.ifremer.echobase.ui.actions.AbstractConfigureAction;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
@@ -54,14 +54,14 @@
/** Universe of voyages to export in db. */
protected Map<String, String> voyages;
+ public Map<String, String> getVoyages() {
+ return voyages;
+ }
+
public Configure() {
super(EmbeddedApplicationConfiguration.class);
}
- public Map<String, String> getVoyages() {
- return voyages;
- }
-
@Override
protected EmbeddedApplicationConfiguration createModel() {
return new EmbeddedApplicationConfiguration();
@@ -71,7 +71,8 @@
protected void prepareInputAction(EmbeddedApplicationConfiguration model) {
// give default embedded application archive file name
- EchoBaseConfiguration configuration = getConfiguration();
+ EchoBaseConfiguration configuration =
+ getEchoBaseApplicationContext().getConfiguration();
Version version = configuration.getApplicationVersion();
String fileName = "echobase-embedded-" + version.toString();
model.setFileName(fileName);
@@ -84,7 +85,7 @@
}
model.setWarLocation(warLocation);
- voyages = loadSortAndDecorate(Voyage.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
if (MapUtils.isEmpty(voyages)) {
addFlashMessage(_("echobase.info.no.voyagee.found"));
@@ -105,7 +106,7 @@
log.info("Temporary directory to use : " + dataDirectory);
}
- File warLocation = getConfiguration().getWarLocation();
+ File warLocation = getEchoBaseApplicationContext().getConfiguration().getWarLocation();
model.setWarLocation(warLocation);
}
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Download.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Download.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/embeddedApplication/Download.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
*/
package fr.ifremer.echobase.ui.actions.embeddedApplication;
-import fr.ifremer.echobase.services.embeddedapplication.EmbeddedApplicationConfiguration;
+import fr.ifremer.echobase.services.service.embeddedapplication.EmbeddedApplicationConfiguration;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.io.BufferedInputStream;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Configure.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Configure.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Configure.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,8 +24,8 @@
package fr.ifremer.echobase.ui.actions.exportDb;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.exportdb.ExportDbConfiguration;
-import fr.ifremer.echobase.services.exportdb.ExportDbMode;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbConfiguration;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbMode;
import fr.ifremer.echobase.ui.actions.AbstractConfigureAction;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
@@ -85,14 +85,14 @@
@Override
protected void prepareInputAction(ExportDbConfiguration model) {
- modes = decorateEnums(ExportDbMode.values());
+ modes = decoratorService.decorateEnums(ExportDbMode.values());
if (model.getExportDbMode() == null) {
model.setExportDbMode(ExportDbMode.ALL);
}
- voyages = loadSortAndDecorate(Voyage.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
}
@Override
@@ -109,7 +109,7 @@
}
if (model.getExportDbMode() == ExportDbMode.ALL) {
- voyages = loadSortAndDecorate(Voyage.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
Set<String> ids = voyages.keySet();
model.setVoyageIds(ids.toArray(new String[ids.size()]));
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Download.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Download.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Download.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
*/
package fr.ifremer.echobase.ui.actions.exportDb;
-import fr.ifremer.echobase.services.exportdb.ExportDbConfiguration;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbConfiguration;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.io.BufferedInputStream;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Export.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Export.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportDb/Export.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.exportDb;
-import fr.ifremer.echobase.services.exportdb.ExportDbConfiguration;
-import fr.ifremer.echobase.services.exportdb.ExportDbService;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbConfiguration;
+import fr.ifremer.echobase.services.service.exportdb.ExportDbService;
import fr.ifremer.echobase.ui.actions.AbstractWaitAndExecAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/DownloadExportQueryResult.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/DownloadExportQueryResult.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/DownloadExportQueryResult.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
package fr.ifremer.echobase.ui.actions.exportQuery;
import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.io.ByteArrayInputStream;
@@ -48,38 +48,38 @@
*/
protected String queryId;
+ public void setQueryId(String queryId) {
+ this.queryId = queryId;
+ }
+
/** Input stream of the file to download. */
protected transient InputStream inputStream;
+ public InputStream getInputStream() {
+ return inputStream;
+ }
+
/** File name of the download. */
protected String fileName;
- /** Length of the file to download. */
- protected int contentLength;
-
- /** Content type of the file to download. */
- protected String contentType;
-
- public void setQueryId(String queryId) {
- this.queryId = queryId;
- }
-
public void setFileName(String fileName) {
this.fileName = fileName;
}
- public InputStream getInputStream() {
- return inputStream;
- }
-
public String getFileName() {
return fileName;
}
+ /** Length of the file to download. */
+ protected int contentLength;
+
public int getContentLength() {
return contentLength;
}
+ /** Content type of the file to download. */
+ protected String contentType;
+
public String getContentType() {
return contentType;
}
@@ -87,13 +87,21 @@
@Override
public String execute() throws Exception {
- ExportQueryService service = getService(ExportQueryService.class);
-
contentType = "text/csv";
- String content = service.createCsvFileContent(queryId);
+ String content = exportQueryService.createCsvFileContent(queryId);
contentLength = content.length();
inputStream = new ByteArrayInputStream(content.getBytes());
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient ExportQueryService exportQueryService;
+
+ public void setExportQueryService(ExportQueryService exportQueryService) {
+ this.exportQueryService = exportQueryService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ExportQueryResult.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ExportQueryResult.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ExportQueryResult.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,7 +25,7 @@
import fr.ifremer.echobase.EchoBaseTechnicalException;
import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -51,9 +51,21 @@
*/
protected String queryId;
+ public void setQueryId(String queryId) {
+ this.queryId = queryId;
+ }
+
+ public String getQueryId() {
+ return queryId;
+ }
+
/** Default file name for export. */
protected String fileName;
+ public String getFileName() {
+ return fileName;
+ }
+
/** names of columns from the executed sql request. */
protected String[] columnNames;
@@ -61,28 +73,15 @@
return columnNames;
}
- public String getFileName() {
- return fileName;
- }
-
- public String getQueryId() {
- return queryId;
- }
-
- public void setQueryId(String queryId) {
- this.queryId = queryId;
- }
-
@Override
public String execute() throws Exception {
// obtain columNames from the request
- ExportQueryService service = getService(ExportQueryService.class);
- String sql = service.getSqlQuery(queryId);
+ String sql = exportQueryService.getSqlQuery(queryId);
try {
- columnNames = service.getColumnNames(sql);
+ columnNames = exportQueryService.getColumnNames(sql);
} catch (EchoBaseTechnicalException e) {
//TODO add a real nice message
addFlashError(e.getMessage());
@@ -96,4 +95,14 @@
fileName = "export.csv";
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient ExportQueryService exportQueryService;
+
+ public void setExportQueryService(ExportQueryService exportQueryService) {
+ this.exportQueryService = exportQueryService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/GetExportQueryResult.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/GetExportQueryResult.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/GetExportQueryResult.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
package fr.ifremer.echobase.ui.actions.exportQuery;
import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
import fr.ifremer.echobase.ui.actions.AbstractJSONPaginedAction;
import java.util.Map;
@@ -47,22 +47,31 @@
*/
protected String queryId;
- /** Datas of the given table. */
- protected Map<?, ?>[] datas;
-
public void setQueryId(String queryId) {
this.queryId = queryId;
}
+ /** Datas of the given table. */
+ protected Map<?, ?>[] datas;
+
public Map<?, ?>[] getDatas() {
return datas;
}
@Override
public String execute() throws Exception {
- ExportQueryService service = getService(ExportQueryService.class);
- datas = service.executeExportquery(queryId, pager);
+ datas = exportQueryService.executeExportquery(queryId, pager);
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient ExportQueryService exportQueryService;
+
+ public void setExportQueryService(ExportQueryService exportQueryService) {
+ this.exportQueryService = exportQueryService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ManageExportQuery.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ManageExportQuery.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/ManageExportQuery.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,9 +26,10 @@
import com.opensymphony.xwork2.Preparable;
import fr.ifremer.echobase.entities.EchoBaseUser;
import fr.ifremer.echobase.entities.ExportQuery;
-import fr.ifremer.echobase.services.exportquery.ExportQueryInvalidNameException;
-import fr.ifremer.echobase.services.exportquery.ExportQueryNameAlreadyExistException;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.InternalDbPersistenceService;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryInvalidNameException;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryNameAlreadyExistException;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
@@ -49,68 +50,59 @@
/** Logger. */
private static final Log log = LogFactory.getLog(ManageExportQuery.class);
- /** All available queries from database. */
- protected Map<String, String> queries;
-
/** Selected query loaded from database if his id is not empty. */
protected ExportQuery query;
- protected boolean newQuery;
-
- protected boolean newLibreOfficeQuery;
-
- protected boolean queryExists;
-
- protected boolean canUpdateQuery;
-
- protected transient ExportQueryService service;
-
- public ExportQueryService getService() {
- if (service == null) {
- service = getService(ExportQueryService.class);
- }
- return service;
- }
-
public ExportQuery getQuery() {
if (query == null) {
- query = getService().newExportQuery();
+ query = exportQueryService.newExportQuery();
}
return query;
}
- public Map<String, String> getQueries() {
- return queries;
- }
+ protected boolean newQuery;
- public Map<String, String> getTableNames() {
- return queries;
+ public void setNewQuery(boolean newQuery) {
+ this.newQuery = newQuery;
}
public boolean isNewQuery() {
return newQuery;
}
- public void setNewQuery(boolean newQuery) {
- this.newQuery = newQuery;
+ protected boolean newLibreOfficeQuery;
+
+ public void setNewLibreOfficeQuery(boolean newLibreOfficeQuery) {
+ this.newLibreOfficeQuery = newLibreOfficeQuery;
}
public boolean isNewLibreOfficeQuery() {
return newLibreOfficeQuery;
}
- public void setNewLibreOfficeQuery(boolean newLibreOfficeQuery) {
- this.newLibreOfficeQuery = newLibreOfficeQuery;
+ protected boolean queryExists;
+
+ public boolean isQueryExists() {
+ return StringUtils.isNotEmpty(getQuery().getTopiaId());
}
+ protected boolean canUpdateQuery;
+
public boolean isCanUpdateQuery() {
return canUpdateQuery;
}
- public boolean isQueryExists() {
- return StringUtils.isNotEmpty(getQuery().getTopiaId());
+ /** All available queries from database. */
+ protected Map<String, String> queries;
+
+ public Map<String, String> getQueries() {
+ return queries;
}
+ public Map<String, String> getTableNames() {
+ return queries;
+ }
+
public String saveQuery() throws Exception {
String result = INPUT;
@@ -119,14 +111,14 @@
if (safeSql) {
try {
- query = getService().createOrUpdate(
+ query = exportQueryService.createOrUpdate(
getQuery(), getEchoBaseSession().getUser());
result = SUCCESS;
} catch (ExportQueryInvalidNameException e) {
addFieldError("query.name",
_("echobase.error.query.invalid.name"));
- }catch (ExportQueryNameAlreadyExistException e) {
+ } catch (ExportQueryNameAlreadyExistException e) {
addFieldError("query.name",
_("echobase.error.query.name.already.exists"));
}
@@ -138,8 +130,8 @@
getQuery().setTopiaId(null);
getQuery().setName(getQuery().getName() + "-clone");
- query = getService().createOrUpdate(getQuery(),
- getEchoBaseSession().getUser()
+ query = exportQueryService.createOrUpdate(getQuery(),
+ getEchoBaseSession().getUser()
);
return SUCCESS;
}
@@ -152,7 +144,7 @@
public String deleteQuery() throws Exception {
//TODO : do validation
- service.delete(getQuery().getTopiaId());
+ exportQueryService.delete(getQuery().getTopiaId());
query = null;
return SUCCESS;
}
@@ -171,7 +163,7 @@
@Override
public void prepare() throws Exception {
- queries = loadSortAndDecorate(ExportQuery.class);
+ queries = internalDbPersistenceService.loadSortAndDecorate(ExportQuery.class);
if (queries.isEmpty()) {
@@ -195,7 +187,7 @@
} else {
// load query from database
- query = getService().getExportQuery(selectedQueryId);
+ query = exportQueryService.getExportQuery(selectedQueryId);
EchoBaseUser echoBaseUser =
getEchoBaseSession().getUser();
@@ -217,7 +209,7 @@
boolean result;
try {
- getService().testSql(getQuery().getSqlQuery());
+ exportQueryService.testSql(getQuery().getSqlQuery());
result = true;
} catch (Exception e) {
Throwable cause = e.getCause();
@@ -230,4 +222,20 @@
}
return result;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient ExportQueryService exportQueryService;
+
+ public void setExportQueryService(ExportQueryService exportQueryService) {
+ this.exportQueryService = exportQueryService;
+ }
+
+ protected transient InternalDbPersistenceService internalDbPersistenceService;
+
+ public void setInternalDbPersistenceService(InternalDbPersistenceService internalDbPersistenceService) {
+ this.internalDbPersistenceService = internalDbPersistenceService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/NewLibreOfficeQuery.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/NewLibreOfficeQuery.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/exportQuery/NewLibreOfficeQuery.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
*/
package fr.ifremer.echobase.ui.actions.exportQuery;
-import fr.ifremer.echobase.services.exportquery.ExportQueryService;
+import fr.ifremer.echobase.services.service.exportquery.ExportQueryService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -43,24 +43,24 @@
protected String libreOfficeQuery;
- protected String resultQuery;
+ public void setLibreOfficeQuery(String libreOfficeQuery) {
+ this.libreOfficeQuery = libreOfficeQuery;
+ }
public String getLibreOfficeQuery() {
return libreOfficeQuery;
}
- public void setLibreOfficeQuery(String libreOfficeQuery) {
- this.libreOfficeQuery = libreOfficeQuery;
+ protected String resultQuery;
+
+ public void setResultQuery(String resultQuery) {
+ this.resultQuery = resultQuery;
}
public String getResultQuery() {
return resultQuery;
}
- public void setResultQuery(String resultQuery) {
- this.resultQuery = resultQuery;
- }
-
@Override
public String execute() {
@@ -68,13 +68,22 @@
log.info("Incoming query = " + libreOfficeQuery);
}
- ExportQueryService service = getService(ExportQueryService.class);
+ resultQuery = exportQueryService.processLibreOfficeSqlQuery(libreOfficeQuery);
- resultQuery = service.processLibreOfficeSqlQuery(libreOfficeQuery);
-
if (log.isInfoEnabled()) {
log.info("Processed query " + resultQuery);
}
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient ExportQueryService exportQueryService;
+
+ public void setExportQueryService(ExportQueryService exportQueryService) {
+ this.exportQueryService = exportQueryService;
+ }
+
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractConfigureImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractConfigureImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractConfigureImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,7 +25,7 @@
import fr.ifremer.echobase.io.EchoBaseIOUtil;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdata.AbstractImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.AbstractImportConfiguration;
import fr.ifremer.echobase.ui.actions.AbstractConfigureAction;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractLaunchImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractLaunchImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/AbstractLaunchImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
-import fr.ifremer.echobase.services.importdata.AbstractImportConfiguration;
-import fr.ifremer.echobase.services.importdata.AbstractImportDataService;
+import fr.ifremer.echobase.services.service.importdata.AbstractImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.AbstractImportDataService;
import fr.ifremer.echobase.ui.actions.AbstractWaitAndExecAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureAcousticImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureAcousticImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureAcousticImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,8 +24,8 @@
package fr.ifremer.echobase.ui.actions.importData;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.importdata.AcousticImportConfiguration;
-import fr.ifremer.echobase.services.importdata.CellPositionReference;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.CellPositionReference;
import java.io.File;
import java.util.Map;
@@ -56,8 +56,8 @@
@Override
protected void prepareInputAction(AcousticImportConfiguration model) {
- voyages = loadSortAndDecorate(Voyage.class);
- cellPositionReferences = decorateEnums(CellPositionReference.values());
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
+ cellPositionReferences = decoratorService.decorateEnums(CellPositionReference.values());
if (model.getCellPositionReference() == null) {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCatchesImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCatchesImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCatchesImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
package fr.ifremer.echobase.ui.actions.importData;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.importdata.CatchesImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.CatchesImportConfiguration;
import java.io.File;
import java.util.Map;
@@ -53,7 +53,7 @@
@Override
protected void prepareInputAction(CatchesImportConfiguration model) {
- voyages = loadSortAndDecorate(Voyage.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
}
public Map<String, String> getVoyages() {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCommonImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCommonImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureCommonImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -28,7 +28,7 @@
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.AreaOfOperation;
import fr.ifremer.echobase.entities.references.Mission;
-import fr.ifremer.echobase.services.importdata.CommonImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.CommonImportConfiguration;
import java.io.File;
import java.util.Map;
@@ -66,10 +66,10 @@
@Override
protected void prepareInputAction(CommonImportConfiguration model) {
- missions = loadSortAndDecorate(Mission.class);
- voyages = loadSortAndDecorate(Voyage.class);
- areaOfOperations = loadSortAndDecorate(AreaOfOperation.class);
- importTypes = decorateEnums(ImportType.getCommonImportType());
+ missions = workingDbPersistenceService.loadSortAndDecorate(Mission.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
+ areaOfOperations = workingDbPersistenceService.loadSortAndDecorate(AreaOfOperation.class);
+ importTypes = decoratorService.decorateEnums(ImportType.getCommonImportType());
if (model.getImportType() == null) {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureOperationImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureOperationImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureOperationImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
package fr.ifremer.echobase.ui.actions.importData;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.importdata.OperationImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.OperationImportConfiguration;
import java.io.File;
import java.util.Map;
@@ -53,7 +53,7 @@
@Override
protected void prepareInputAction(OperationImportConfiguration model) {
- voyages = loadSortAndDecorate(Voyage.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
}
public Map<String, String> getVoyages() {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureResultsImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureResultsImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/ConfigureResultsImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,7 +27,7 @@
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.Vessel;
-import fr.ifremer.echobase.services.importdata.ResultsImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.ResultsImportConfiguration;
import java.io.File;
import java.util.Map;
@@ -64,9 +64,9 @@
@Override
protected void prepareInputAction(ResultsImportConfiguration model) {
- voyages = loadSortAndDecorate(Voyage.class);
- vessels = loadSortAndDecorate(Vessel.class);
- importTypes = decorateEnums(ImportType.getResultImportType());
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
+ vessels = workingDbPersistenceService.loadSortAndDecorate(Vessel.class);
+ importTypes = decoratorService.decorateEnums(ImportType.getResultImportType());
if (model.getImportType() == null) {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/CreateMission.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/CreateMission.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/CreateMission.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,8 +26,8 @@
import com.google.common.base.Preconditions;
import fr.ifremer.echobase.entities.references.Mission;
import fr.ifremer.echobase.entities.references.MissionImpl;
-import fr.ifremer.echobase.services.importdata.CommonImportService;
-import fr.ifremer.echobase.services.importdata.MissionNameAlreadyExistException;
+import fr.ifremer.echobase.services.service.importdata.CommonImportService;
+import fr.ifremer.echobase.services.service.importdata.MissionNameAlreadyExistException;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -63,9 +63,7 @@
String result = INPUT;
try {
- CommonImportService service =
- getService(CommonImportService.class);
- Mission missionSaved = service.createMission(mission);
+ Mission missionSaved = commonImportService.createMission(mission);
if (log.isInfoEnabled()) {
log.info("Created mission : " + missionSaved.getTopiaId());
@@ -79,4 +77,14 @@
}
return result;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient CommonImportService commonImportService;
+
+ public void setCommonImportService(CommonImportService commonImportService) {
+ this.commonImportService = commonImportService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetDataProcessingsForVoyage.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetDataProcessingsForVoyage.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetDataProcessingsForVoyage.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,7 +26,8 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.importdata.ResultsImportService;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
+import fr.ifremer.echobase.services.service.importdata.ResultsImportService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
@@ -63,18 +64,31 @@
} else {
- ResultsImportService service =
- getService(ResultsImportService.class);
+ Voyage voyage = workingDbPersistenceService.getVoyageDAO().findByTopiaId(voyageId);
- Voyage voyage = service.getEntityById(Voyage.class, voyageId);
-
Preconditions.checkNotNull(
voyage,
"Could not find voyage with id " + voyageId);
- dataProcessings = service.getDataProcessings(voyage);
+ dataProcessings = resultsImportService.getDataProcessings(voyage);
}
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient ResultsImportService resultsImportService;
+
+ public void setResultsImportService(ResultsImportService resultsImportService) {
+ this.resultsImportService = resultsImportService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetVesselsForVoyage.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetVesselsForVoyage.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/GetVesselsForVoyage.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,8 +27,8 @@
import com.google.common.collect.Maps;
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.Vessel;
-import fr.ifremer.echobase.services.DecoratorService;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.nuiton.decorator.Decorator;
@@ -49,12 +49,12 @@
/** Selected voyage id. */
protected String voyageId;
- protected Map<String, String> vessels;
-
public void setVoyageId(String voyageId) {
this.voyageId = voyageId;
}
+ protected Map<String, String> vessels;
+
public Map<String, String> getVessels() {
return vessels;
}
@@ -66,17 +66,12 @@
if (StringUtils.isNotEmpty(voyageId)) {
- EchoBaseServiceSupport service =
- getService(EchoBaseServiceSupport.class);
+ Voyage voyage = workingDbPersistenceService.getVoyageDAO().findByTopiaId(voyageId);
- Voyage voyage = service.getEntityById(Voyage.class, voyageId);
-
Preconditions.checkNotNull(voyage,
"Could not find voyage with id " + voyageId);
if (!voyage.isTransitEmpty()) {
- DecoratorService decoratorService =
- service.getService(DecoratorService.class);
Decorator<Vessel> decorator =
decoratorService.getDecorator(getLocale(),
Vessel.class,
@@ -94,4 +89,20 @@
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient DecoratorService decoratorService;
+
+ public void setDecoratorService(DecoratorService decoratorService) {
+ this.decoratorService = decoratorService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchAcousticImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchAcousticImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchAcousticImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
-import fr.ifremer.echobase.services.importdata.AcousticImportConfiguration;
-import fr.ifremer.echobase.services.importdata.AcousticImportService;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.AcousticImportService;
/**
* Configure a accoustic data import.
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCatchesImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCatchesImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCatchesImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
-import fr.ifremer.echobase.services.importdata.CatchesImportConfiguration;
-import fr.ifremer.echobase.services.importdata.CatchesImportService;
+import fr.ifremer.echobase.services.service.importdata.CatchesImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.CatchesImportService;
/**
* Configure a accoustic data import.
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCommonImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCommonImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchCommonImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
-import fr.ifremer.echobase.services.importdata.CommonImportConfiguration;
-import fr.ifremer.echobase.services.importdata.CommonImportService;
+import fr.ifremer.echobase.services.service.importdata.CommonImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.CommonImportService;
/**
* Configure a accoustic data import.
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchOperationImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchOperationImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchOperationImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
-import fr.ifremer.echobase.services.importdata.OperationImportConfiguration;
-import fr.ifremer.echobase.services.importdata.OperationImportService;
+import fr.ifremer.echobase.services.service.importdata.OperationImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.OperationImportService;
/**
* TODO
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchResultsImport.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchResultsImport.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/LaunchResultsImport.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
-import fr.ifremer.echobase.services.importdata.ResultsImportConfiguration;
-import fr.ifremer.echobase.services.importdata.ResultsImportService;
+import fr.ifremer.echobase.services.service.importdata.ResultsImportConfiguration;
+import fr.ifremer.echobase.services.service.importdata.ResultsImportService;
/**
* Configure a "result" import.
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/SelectImportType.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/SelectImportType.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importData/SelectImportType.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,6 +23,7 @@
*/
package fr.ifremer.echobase.ui.actions.importData;
+import fr.ifremer.echobase.services.service.DecoratorService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.util.Map;
@@ -39,24 +40,24 @@
protected ImportMode mode;
- /** Universe of possible import modes. */
- protected Map<String, String> modes;
-
- public Map<String, String> getModes() {
- return modes;
+ public void setMode(ImportMode mode) {
+ this.mode = mode;
}
public ImportMode getMode() {
return mode;
}
- public void setMode(ImportMode mode) {
- this.mode = mode;
+ /** Universe of possible import modes. */
+ protected Map<String, String> modes;
+
+ public Map<String, String> getModes() {
+ return modes;
}
@Override
public String input() throws Exception {
- modes = decorateEnums(ImportMode.values());
+ modes = decoratorService.decorateEnums(ImportMode.values());
if (mode == null) {
mode = ImportMode.Common;
@@ -68,4 +69,14 @@
public String execute() throws Exception {
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient DecoratorService decoratorService;
+
+ public void setDecoratorService(DecoratorService decoratorService) {
+ this.decoratorService = decoratorService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Configure.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Configure.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Configure.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,8 +26,8 @@
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import fr.ifremer.echobase.io.EchoBaseIOUtil;
import fr.ifremer.echobase.io.InputFile;
-import fr.ifremer.echobase.services.importdb.ImportDbConfiguration;
-import fr.ifremer.echobase.services.importdb.ImportDbMode;
+import fr.ifremer.echobase.services.service.importdb.ImportDbConfiguration;
+import fr.ifremer.echobase.services.service.importdb.ImportDbMode;
import fr.ifremer.echobase.ui.actions.AbstractConfigureAction;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
@@ -69,7 +69,7 @@
@Override
protected void prepareInputAction(ImportDbConfiguration model) {
- modes = decorateEnums(ImportDbMode.values());
+ modes = decoratorService.decorateEnums(ImportDbMode.values());
if (model.getImportDbMode() == null) {
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Import.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Import.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/importDb/Import.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,9 +24,8 @@
package fr.ifremer.echobase.ui.actions.importDb;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.importdb.ImportDbConfiguration;
-import fr.ifremer.echobase.services.importdb.ImportDbMode;
-import fr.ifremer.echobase.services.importdb.ImportDbService;
+import fr.ifremer.echobase.services.service.importdb.ImportDbConfiguration;
+import fr.ifremer.echobase.services.service.importdb.ImportDbService;
import fr.ifremer.echobase.ui.actions.AbstractWaitAndExecAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -60,7 +59,6 @@
@Override
protected String getResultMessage(ImportDbConfiguration model) {
- ImportDbMode importDbMode = model.getImportDbMode();
String message;
switch (model.getImportDbMode()) {
case REFERENTIAL:
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ConfirmDelete.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ConfirmDelete.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ConfirmDelete.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,13 +24,10 @@
*/
import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.DecoratorService;
-import fr.ifremer.echobase.services.EchoBaseServiceSupport;
-import fr.ifremer.echobase.services.removedata.RemoveDataConfiguration;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataConfiguration;
import fr.ifremer.echobase.ui.actions.AbstractConfigureAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -79,22 +76,20 @@
@Override
protected void prepareInputAction(RemoveDataConfiguration model) {
- importTypes = decorateEnums(ImportType.values());
+ importTypes = decoratorService.decorateEnums(ImportType.values());
importLogs = Lists.newArrayList();
- EchoBaseServiceSupport service =
- getService(EchoBaseServiceSupport.class);
+ Decorator<Voyage> decorator = decoratorService.getDecorator(getLocale(), Voyage.class, null);
- Decorator<Voyage> decorator = getService(DecoratorService.class).getDecorator(getLocale(), Voyage.class, null);
-
for (String id : model.getImportLogIds()) {
if (log.isInfoEnabled()) {
log.info("Load import log " + id);
}
- ImportLog importLog = service.getEntityById(ImportLog.class, id);
+ ImportLog importLog = workingDbPersistenceService.getImportLogDAO().findByTopiaId(id);
- Voyage voyageEntity = service.getEntityById(Voyage.class, importLog.getVoyageId());
+ Voyage voyageEntity = workingDbPersistenceService.getVoyageDAO().findByTopiaId(importLog.getVoyageId());
+
String voyage = decorator.toString(voyageEntity);
String importType = importTypes.get(importLog.getImportType().name());
String result = _("echobase.common.importLogToDelete",
@@ -103,6 +98,6 @@
importLog.getImportDate());
importLogs.add(result);
}
-
}
+
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/Delete.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/Delete.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/Delete.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,8 +23,8 @@
* #L%
*/
-import fr.ifremer.echobase.services.removedata.RemoveDataConfiguration;
-import fr.ifremer.echobase.services.removedata.RemoveDataService;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataConfiguration;
+import fr.ifremer.echobase.services.service.removedata.RemoveDataService;
import fr.ifremer.echobase.ui.actions.AbstractWaitAndExecAction;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ImportLogs.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ImportLogs.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/removeData/ImportLogs.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,6 +24,7 @@
*/
import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import java.util.Map;
@@ -57,8 +58,18 @@
@Override
public String execute() throws Exception {
- voyages = loadSortAndDecorate(Voyage.class);
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
}
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/AbstractGetVoyage.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/AbstractGetVoyage.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/AbstractGetVoyage.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,96 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.Map;
+
+/**
+ * Obtain all echotypes used for a given voyage.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public abstract class AbstractGetVoyage extends EchoBaseActionSupport {
+
+ private static final long serialVersionUID = 1L;
+
+ /** Selected voyage id. */
+ protected String voyageId;
+
+ public void setVoyageId(String voyageId) {
+ this.voyageId = voyageId;
+ }
+
+ /** Universe of result. */
+ protected Map<String, String> data;
+
+ protected abstract Map<String, String> buildData(SpatialService service,
+ Voyage voyage);
+
+ public abstract Map<String, String> getData();
+
+ @Override
+ public String execute() throws Exception {
+
+ if (StringUtils.isEmpty(voyageId)) {
+ data = Maps.newLinkedHashMap();
+
+ } else {
+
+ Voyage voyage = workingDbPersistenceService.getVoyageDAO().findByTopiaId(voyageId);
+
+ Preconditions.checkNotNull(
+ voyage,
+ "Could not find voyage with id " + voyageId);
+
+ data = buildData(spatialService, voyage);
+ }
+
+ return SUCCESS;
+ }
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient SpatialService spatialService;
+
+ public void setSpatialService(SpatialService spatialService) {
+ this.spatialService = spatialService;
+ }
+}
\ No newline at end of file
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/AbstractGetVoyage.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,83 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL:$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
+
+import java.util.Map;
+
+/**
+ * To configure and show spatial datas.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class ConfigureShowSpatialData extends EchoBaseActionSupport {
+
+ private static final long serialVersionUID = 1L;
+
+ protected final ShowSpatialModel model = new ShowSpatialModel();
+
+ /** Universe of existing voyages. */
+ protected Map<String, String> voyages;
+
+ public ShowSpatialModel getModel() {
+ return model;
+ }
+
+ public Map<String, String> getVoyages() {
+ return voyages;
+ }
+
+ @Override
+ public String execute() throws Exception {
+
+ model.setJdbcUrl(getServiceContext().getWorkgingDbUrl());
+ model.setWithSpatial(spatialService.isSpatialAware());
+
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
+
+ return SUCCESS;
+ }
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient SpatialService spatialService;
+
+ public void setSpatialService(SpatialService spatialService) {
+ this.spatialService = spatialService;
+ }
+
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ConfigureShowSpatialData.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,73 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import com.google.common.base.Preconditions;
+import fr.ifremer.echobase.entities.spatial.SpatialData;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
+
+import java.util.Set;
+
+/**
+ * Otain all dataMetadata used for a given voyage.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class GetSpatialData extends EchoBaseActionSupport {
+
+ private static final long serialVersionUID = 1L;
+
+ protected final ShowSpatialModel model = new ShowSpatialModel();
+
+ public ShowSpatialModel getModel() {
+ return model;
+ }
+
+ @Override
+ public String execute() throws Exception {
+
+ boolean withSpatial = getModel().isWithSpatial();
+ Preconditions.checkArgument(withSpatial, "Database is not spatial aware.");
+
+ model.setJdbcUrl(getServiceContext().getWorkgingDbUrl());
+
+ Set<SpatialData> spatialData = spatialService.getSpatialData(model);
+ getModel().setSpatialData(spatialData);
+ getModel().setWithData(true);
+
+ return SUCCESS;
+ }
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient SpatialService spatialService;
+
+ public void setSpatialService(SpatialService spatialService) {
+ this.spatialService = spatialService;
+ }
+}
\ No newline at end of file
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetSpatialData.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageDataMetadata.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageDataMetadata.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageDataMetadata.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,53 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.references.DataMetadata;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+
+import java.util.Map;
+
+/**
+ * Obtain all dataMetadata used for a given voyage.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class GetVoyageDataMetadata extends AbstractGetVoyage {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Map<String, String> getData() {
+ return data;
+ }
+
+ @Override
+ protected Map<String, String> buildData(SpatialService service,
+ Voyage voyage) {
+ Map<String, String> result = workingDbPersistenceService.loadSortAndDecorate(DataMetadata.class);
+ return result;
+ }
+}
\ No newline at end of file
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageDataMetadata.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageEchotype.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageEchotype.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageEchotype.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,54 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.data.Echotype;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+
+import java.util.Map;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class GetVoyageEchotype extends AbstractGetVoyage {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Map<String, String> getData() {
+ return data;
+ }
+
+ @Override
+ protected Map<String, String> buildData(SpatialService service,
+ Voyage voyage) {
+
+ Map<String, String> result = workingDbPersistenceService.loadSortAndDecorate(Echotype.class);
+ return result;
+ }
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageEchotype.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageSpecies.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageSpecies.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageSpecies.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,54 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.references.Species;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+
+import java.util.Map;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class GetVoyageSpecies extends AbstractGetVoyage {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Map<String, String> getData() {
+ return data;
+ }
+
+ @Override
+ protected Map<String, String> buildData(SpatialService service,
+ Voyage voyage) {
+
+ Map<String, String> result = workingDbPersistenceService.loadSortAndDecorate(Species.class);
+ return result;
+ }
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/GetVoyageSpecies.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,36 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL:$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+/**
+ * To save the selected spatial data.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class Save {
+
+ protected final ShowSpatialModel model = new ShowSpatialModel();
+
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/Save.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,102 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import com.opensymphony.xwork2.Preparable;
+import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
+import fr.ifremer.echobase.entities.data.Voyage;
+import fr.ifremer.echobase.entities.spatial.SpatialData;
+import fr.ifremer.echobase.services.service.WorkingDbPersistenceService;
+import fr.ifremer.echobase.services.service.spatial.SpatialService;
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
+
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * To configure and show spatial datas.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class ShowSpatialData extends EchoBaseActionSupport implements Preparable {
+
+ private static final long serialVersionUID = 1L;
+
+ protected final ShowSpatialModel model = new ShowSpatialModel();
+
+ public ShowSpatialModel getModel() {
+ return model;
+ }
+
+ /** Universe of existing voyages. */
+ protected Map<String, String> voyages;
+
+ public Map<String, String> getVoyages() {
+ return voyages;
+ }
+
+ @Override
+ public void prepare() throws Exception {
+ voyages = workingDbPersistenceService.loadSortAndDecorate(Voyage.class);
+
+ model.setJdbcUrl(getServiceContext().getWorkgingDbUrl());
+ }
+
+ @Override
+ public String input() throws Exception {
+
+ model.setWithSpatial(spatialService.isSpatialAware());
+
+ return SUCCESS;
+ }
+
+ @InputConfig(methodName = "input")
+ @Override
+ public String execute() throws Exception {
+
+ Set<SpatialData> spatialData = spatialService.getSpatialData(model);
+
+ getModel().setSpatialData(spatialData);
+ getModel().setWithData(true);
+
+ return SUCCESS;
+ }
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient WorkingDbPersistenceService workingDbPersistenceService;
+
+ public void setWorkingDbPersistenceService(WorkingDbPersistenceService workingDbPersistenceService) {
+ this.workingDbPersistenceService = workingDbPersistenceService;
+ }
+
+ protected transient SpatialService spatialService;
+
+ public void setSpatialService(SpatialService spatialService) {
+ this.spatialService = spatialService;
+ }
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialData.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,78 @@
+package fr.ifremer.echobase.ui.actions.spatial;
+
+/*
+ * #%L
+ * EchoBase :: UI
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ * %%
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * #L%
+ */
+
+import fr.ifremer.echobase.entities.spatial.SpatialConfiguration;
+import fr.ifremer.echobase.entities.spatial.SpatialData;
+
+import java.io.Serializable;
+import java.util.Set;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.2
+ */
+public class ShowSpatialModel extends SpatialConfiguration implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Loaded spatial data.
+ */
+ protected Set<SpatialData> spatialData;
+
+ /**
+ * Can we use spatial data ?
+ */
+ protected boolean withSpatial;
+
+ protected boolean withData;
+
+ public boolean isWithSpatial() {
+ return withSpatial;
+ }
+
+ public void setWithSpatial(boolean withSpatial) {
+ this.withSpatial = withSpatial;
+ }
+
+ public Set<SpatialData> getSpatialData() {
+ return spatialData;
+ }
+
+ public void setSpatialData(Set<SpatialData> spatialData) {
+ this.spatialData = spatialData;
+ }
+
+ public boolean isWithData() {
+ return withData;
+ }
+
+ public void setWithData(boolean withData) {
+ this.withData = withData;
+ }
+
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/spatial/ShowSpatialModel.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Create.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Create.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Create.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
package fr.ifremer.echobase.ui.actions.user;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.UserService;
+import fr.ifremer.echobase.services.service.UserService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
@@ -46,7 +46,7 @@
public EchoBaseUser getUser() {
if (user == null) {
- user = getService(UserService.class).newUser();
+ user = userService.newUser();
}
return user;
}
@@ -61,7 +61,7 @@
}
// create user
- getService(UserService.class).createOrUpdate(userToCreate);
+ userService.createOrUpdate(userToCreate);
// add info message
addFlashMessage(_("echobase.info.user.create", userEmail));
@@ -85,7 +85,7 @@
// check login not already used
EchoBaseUser login;
try {
- login = getService(UserService.class).getUserByEmail(userEmail);
+ login = userService.getUserByEmail(userEmail);
} catch (Exception e) {
// could not get user
@@ -107,4 +107,14 @@
}
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient UserService userService;
+
+ public void setUserService(UserService userService) {
+ this.userService = userService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Delete.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Delete.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Delete.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,13 +25,15 @@
import com.opensymphony.xwork2.Preparable;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.UserService;
+import fr.ifremer.echobase.services.service.UserService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ParameterAware;
+import java.util.Map;
+
/**
* To delete a user.
*
@@ -48,18 +50,18 @@
public EchoBaseUser getUser() {
if (user == null) {
- user = getService(UserService.class).newUser();
+ user = userService.newUser();
}
return user;
}
@Override
public void prepare() throws Exception {
- String userId = getParameters().get("user.topiaId")[0];
+ String userId = parameters.get("user.topiaId")[0];
if (!StringUtils.isEmpty(userId)) {
// load user
- user = getService(UserService.class).getUserById(userId);
+ user = userService.getUserById(userId);
// do not want to have the password
user.setPassword("");
if (log.isInfoEnabled()) {
@@ -79,10 +81,27 @@
}
// delete user
- getService(UserService.class).delete(userToDelete);
+ userService.delete(userToDelete);
// add info message
addFlashMessage(_("echobase.info.user.delete", userEmail));
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ private transient Map<String, String[]> parameters;
+
+ @Override
+ public void setParameters(Map<String, String[]> parameters) {
+ this.parameters = parameters;
+ }
+
+ protected transient UserService userService;
+
+ public void setUserService(UserService userService) {
+ this.userService = userService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/GetUsers.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/GetUsers.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/GetUsers.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,7 +24,7 @@
package fr.ifremer.echobase.ui.actions.user;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.UserService;
+import fr.ifremer.echobase.services.service.UserService;
import fr.ifremer.echobase.ui.actions.AbstractJSONPaginedAction;
import org.nuiton.util.beans.Binder;
import org.nuiton.util.beans.BinderFactory;
@@ -51,8 +51,7 @@
@Override
public String execute() throws Exception {
- List<EchoBaseUser> allUsers =
- getService(UserService.class).getUsers(pager);
+ List<EchoBaseUser> allUsers = userService.getUsers(pager);
datas = new Map[allUsers.size()];
Binder<EchoBaseUser, EchoBaseUser> binder =
@@ -67,4 +66,14 @@
return SUCCESS;
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient UserService userService;
+
+ public void setUserService(UserService userService) {
+ this.userService = userService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Login.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Login.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Login.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,7 +26,7 @@
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.interceptor.I18nInterceptor;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.UserService;
+import fr.ifremer.echobase.services.service.UserService;
import fr.ifremer.echobase.ui.EchoBaseSession;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
@@ -50,10 +50,6 @@
protected String email;
- protected String password;
-
- protected String redirectAction;
-
public String getEmail() {
return email;
}
@@ -62,6 +58,8 @@
this.email = email;
}
+ protected String password;
+
public String getPassword() {
return password;
}
@@ -70,6 +68,8 @@
this.password = password;
}
+ protected String redirectAction;
+
public String getRedirectAction() {
return redirectAction;
}
@@ -81,7 +81,7 @@
@Override
public String execute() throws Exception {
- EchoBaseUser user = getService(UserService.class).getUserByEmail(email);
+ EchoBaseUser user = userService.getUserByEmail(email);
EchoBaseSession userSession = getEchoBaseSession();
@@ -91,8 +91,6 @@
// let's register
getEchoBaseApplicationContext().registerEchoBaseSession(userSession);
- Map<String,Object> session = getSession();
-
// add locale in echoBaseSession if required
Object o = session.get(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE);
if (o == null) {
@@ -109,4 +107,21 @@
}
return "redirect";
}
+
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ private transient Map<String, Object> session;
+
+ @Override
+ public void setSession(Map<String, Object> session) {
+ this.session = session;
+ }
+
+ protected transient UserService userService;
+
+ public void setUserService(UserService userService) {
+ this.userService = userService;
+ }
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Logout.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Logout.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Logout.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,6 +23,7 @@
* #L%
*/
+import com.opensymphony.xwork2.ActionContext;
import fr.ifremer.echobase.ui.EchoBaseSession;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
@@ -45,7 +46,7 @@
getEchoBaseApplicationContext().destroyEchoBaseSession(userSession);
// clean it from ActionContext (we never know...)
- EchoBaseSession.removeEchoBaseSession(getActionContext());
+ EchoBaseSession.removeEchoBaseSession(ActionContext.getContext());
return SUCCESS;
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Update.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Update.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/user/Update.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,13 +25,15 @@
import com.opensymphony.xwork2.Preparable;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.UserService;
+import fr.ifremer.echobase.services.service.UserService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ParameterAware;
+import java.util.Map;
+
/**
* To update a user.
*
@@ -48,7 +50,7 @@
public EchoBaseUser getUser() {
if (user == null) {
- user = getService(UserService.class).newUser();
+ user = userService.newUser();
}
return user;
}
@@ -63,7 +65,7 @@
}
// update user
- getService(UserService.class).createOrUpdate(userToUpdate);
+ userService.createOrUpdate(userToUpdate);
// add info message
addFlashMessage(_("echobase.info.user.update", userEmail));
@@ -72,11 +74,11 @@
@Override
public void prepare() throws Exception {
- String userId = getParameters().get("user.topiaId")[0];
+ String userId = parameters.get("user.topiaId")[0];
if (!StringUtils.isEmpty(userId)) {
// load user
- user = getService(UserService.class).getUserById(userId);
+ user = userService.getUserById(userId);
// do not want to update password
user.setPassword("");
if (log.isInfoEnabled()) {
@@ -85,4 +87,20 @@
}
}
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ private transient Map<String, String[]> parameters;
+
+ @Override
+ public void setParameters(Map<String, String[]> parameters) {
+ this.parameters = parameters;
+ }
+
+ protected transient UserService userService;
+
+ public void setUserService(UserService userService) {
+ this.userService = userService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/AbstractWorkingDbAction.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/AbstractWorkingDbAction.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/AbstractWorkingDbAction.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -26,7 +26,9 @@
import com.opensymphony.xwork2.Preparable;
import fr.ifremer.echobase.entities.DriverType;
import fr.ifremer.echobase.entities.WorkingDbConfiguration;
-import fr.ifremer.echobase.services.workingDb.WorkingDbConfigurationService;
+import fr.ifremer.echobase.services.service.DecoratorService;
+import fr.ifremer.echobase.services.service.InternalDbPersistenceService;
+import fr.ifremer.echobase.services.service.workingDb.WorkingDbConfigurationService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
@@ -68,7 +70,7 @@
public final WorkingDbConfiguration getConf() {
if (conf == null) {
- conf = getService().newConfiguration();
+ conf = workingDbConfigurationService.newConfiguration();
}
return conf;
}
@@ -84,9 +86,9 @@
@Override
public void prepare() throws Exception {
- driverTypes = decorateEnums(DriverType.values());
+ driverTypes = decoratorService.decorateEnums(DriverType.values());
- confs = loadSortAndDecorate(WorkingDbConfiguration.class);
+ confs = internalDbPersistenceService.loadSortAndDecorate(WorkingDbConfiguration.class);
if (confs.isEmpty()) {
@@ -95,20 +97,45 @@
_("echobase.info.no.workingDbConfiguration.saved"));
}
- String[] ids = getParameters().get("conf.topiaId");
+ String[] ids = parameters.get("conf.topiaId");
String id = ids == null || ids.length == 0 ? null : ids[0];
if (!StringUtils.isEmpty(id)) {
// load conf
- conf = getService().getEditableConf(id);
+ conf = workingDbConfigurationService.getEditableConf(id);
if (log.isInfoEnabled()) {
log.info("Selected conf " + conf.getUrl());
}
}
}
- protected final WorkingDbConfigurationService getService() {
- return getService(WorkingDbConfigurationService.class);
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ private transient Map<String, String[]> parameters;
+
+ @Override
+ public void setParameters(Map<String, String[]> parameters) {
+ this.parameters = parameters;
}
+ protected transient InternalDbPersistenceService internalDbPersistenceService;
+
+ public void setInternalDbPersistenceService(InternalDbPersistenceService internalDbPersistenceService) {
+ this.internalDbPersistenceService = internalDbPersistenceService;
+ }
+
+ protected transient WorkingDbConfigurationService workingDbConfigurationService;
+
+ public void setWorkingDbConfigurationService(WorkingDbConfigurationService workingDbConfigurationService) {
+ this.workingDbConfigurationService = workingDbConfigurationService;
+ }
+
+ protected transient DecoratorService decoratorService;
+
+ public void setDecoratorService(DecoratorService decoratorService) {
+ this.decoratorService = decoratorService;
+ }
+
}
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Create.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Create.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Create.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -65,7 +65,7 @@
@Override
public String execute() throws Exception {
- conf = getService().create(getConf());
+ conf = workingDbConfigurationService.create(getConf());
addFlashMessage(_("echobase.info.workingDbconfiguration.created",
conf.getUrl()));
@@ -87,7 +87,7 @@
// when creating a request
// check this url does not exists
- boolean urlUsed = getService().isUrlAlreadyUsed(getConf().getUrl());
+ boolean urlUsed = workingDbConfigurationService.isUrlAlreadyUsed(getConf().getUrl());
if (urlUsed) {
addFieldError("conf.url",
_("echobase.error.workingDbConfiguration.url.already.exists"));
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Delete.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Delete.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Delete.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -50,7 +50,7 @@
String result = INPUT;
try {
- getService().delete(getConf().getTopiaId());
+ workingDbConfigurationService.delete(getConf().getTopiaId());
addFlashMessage(_("echobase.info.workingDbconfiguration.deleted",
conf.getUrl()));
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/DownloadDriver.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/DownloadDriver.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/DownloadDriver.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
* #L%
*/
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
import fr.ifremer.echobase.persistence.JdbcConfiguration;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
@@ -42,45 +42,46 @@
private static final long serialVersionUID = 1L;
- /** Input stream of the file to download. */
- protected transient InputStream inputStream;
-
/** File name of the download. */
protected String fileName;
- /** Length of the file to download. */
- protected long contentLength;
-
- /** Content type of the file to download. */
- protected String contentType;
-
public void setFileName(String fileName) {
this.fileName = fileName;
}
+ public String getFileName() {
+ return fileName;
+ }
+
+ /** Input stream of the file to download. */
+ protected transient InputStream inputStream;
+
public InputStream getInputStream() {
return inputStream;
}
+ /** Length of the file to download. */
+ protected long contentLength;
+
public long getContentLength() {
return contentLength;
}
+ /** Content type of the file to download. */
+ protected String contentType;
+
public String getContentType() {
return contentType;
}
- public String getFileName() {
- return fileName;
- }
-
@Override
public String execute() throws Exception {
EchoBaseConfiguration configuration =
getEchoBaseApplicationContext().getConfiguration();
- JdbcConfiguration dbConfiguration = getEchoBaseSession().getWorkingDbConfiguration();
+ JdbcConfiguration dbConfiguration =
+ getEchoBaseSession().getWorkingDbConfiguration();
fileName =
dbConfiguration.getDriverType().getPilotFileName(configuration);
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetImportLogDetail.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetImportLogDetail.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetImportLogDetail.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,7 +27,8 @@
import fr.ifremer.echobase.entities.ImportLog;
import fr.ifremer.echobase.entities.ImportType;
import fr.ifremer.echobase.entities.data.Voyage;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
+import fr.ifremer.echobase.services.service.DecoratorService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.nuiton.topia.persistence.metadata.TableMeta;
@@ -45,12 +46,12 @@
protected String importLogId;
- protected Map data;
-
public void setImportLogId(String importLogId) {
this.importLogId = importLogId;
}
+ protected Map data;
+
public Map<?, ?> getData() {
return data;
}
@@ -58,20 +59,34 @@
@Override
public String execute() throws Exception {
- DbEditorService service = getService(DbEditorService.class);
- TableMeta<EchoBaseEntityEnum> tableMeta = service.getTableMeta(EchoBaseEntityEnum.ImportLog);
- data = service.getData(tableMeta, importLogId);
+ TableMeta<EchoBaseEntityEnum> tableMeta =
+ dbEditorService.getTableMeta(EchoBaseEntityEnum.ImportLog);
+ data = dbEditorService.getData(tableMeta, importLogId);
-
// decorate import type
- Map<String, String> importTypes = decorateEnums(ImportType.values());
+ Map<String, String> importTypes = decoratorService.decorateEnums(ImportType.values());
String importType = (String) data.get(ImportLog.PROPERTY_IMPORT_TYPE);
data.put(ImportLog.PROPERTY_IMPORT_TYPE, importTypes.get(importType));
// decorate foreign keys
- service.decorateForeignKey(data, Voyage.class, ImportLog.PROPERTY_VOYAGE_ID, null);
+ dbEditorService.decorateForeignKey(data, Voyage.class, ImportLog.PROPERTY_VOYAGE_ID, null);
return SUCCESS;
}
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
+
+ protected transient DecoratorService decoratorService;
+
+ public void setDecoratorService(DecoratorService decoratorService) {
+ this.decoratorService = decoratorService;
+ }
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetVoyage.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetVoyage.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/GetVoyage.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -28,7 +28,7 @@
import fr.ifremer.echobase.entities.data.Voyage;
import fr.ifremer.echobase.entities.references.AreaOfOperation;
import fr.ifremer.echobase.entities.references.Mission;
-import fr.ifremer.echobase.services.DbEditorService;
+import fr.ifremer.echobase.services.service.DbEditorService;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.nuiton.topia.persistence.metadata.TableMeta;
@@ -46,12 +46,12 @@
protected String voyageId;
- protected Map data;
-
public void setVoyageId(String voyageId) {
this.voyageId = voyageId;
}
+ protected Map data;
+
public Map<?, ?> getData() {
return data;
}
@@ -59,16 +59,25 @@
@Override
public String execute() throws Exception {
- DbEditorService service = getService(DbEditorService.class);
- TableMeta<EchoBaseEntityEnum> tableMeta = service.getTableMeta(EchoBaseEntityEnum.Voyage);
- data = service.getData(tableMeta, voyageId);
+ TableMeta<EchoBaseEntityEnum> tableMeta =
+ dbEditorService.getTableMeta(EchoBaseEntityEnum.Voyage);
+ data = dbEditorService.getData(tableMeta, voyageId);
// decorate foreign keys
- service.decorateForeignKey(data, Mission.class, Voyage.PROPERTY_MISSION, null);
- service.decorateForeignKey(data, AreaOfOperation.class, Voyage.PROPERTY_AREA_OF_OPERATION, null);
+ dbEditorService.decorateForeignKey(data, Mission.class, Voyage.PROPERTY_MISSION, null);
+ dbEditorService.decorateForeignKey(data, AreaOfOperation.class, Voyage.PROPERTY_AREA_OF_OPERATION, null);
return SUCCESS;
}
+ //------------------------------------------------------------------------//
+ //-- Injected objects //
+ //------------------------------------------------------------------------//
+ protected transient DbEditorService dbEditorService;
+
+ public void setDbEditorService(DbEditorService dbEditorService) {
+ this.dbEditorService = dbEditorService;
+ }
+
}
\ No newline at end of file
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Information.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Information.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/actions/workingDb/Information.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -23,7 +23,7 @@
* #L%
*/
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
import fr.ifremer.echobase.persistence.JdbcConfiguration;
import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckLogguedInterceptor.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckLogguedInterceptor.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckLogguedInterceptor.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -24,9 +24,9 @@
package fr.ifremer.echobase.ui.interceptors;
import com.opensymphony.xwork2.ActionInvocation;
-import fr.ifremer.echobase.EchoBaseConfiguration;
+import fr.ifremer.echobase.config.EchoBaseConfiguration;
+import fr.ifremer.echobase.ui.EchoBaseApplicationContext;
import fr.ifremer.echobase.ui.EchoBaseSession;
-import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import fr.ifremer.echobase.ui.actions.user.Login;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -56,15 +56,16 @@
@Override
protected boolean doCheck(ActionInvocation invocation) {
- EchoBaseActionSupport action = (EchoBaseActionSupport) invocation.getAction();
- EchoBaseSession echoBaseSession = action.getEchoBaseSession();
+ EchoBaseSession echoBaseSession = EchoBaseSession.getEchoBaseSession(
+ invocation.getInvocationContext());
+
boolean userLoggued = echoBaseSession.getUser() != null;
if (!userLoggued) {
boolean autoLogin =
- EchoBaseActionSupport.getEchoBaseApplicationContext()
+ EchoBaseApplicationContext.getApplicationContext(invocation.getInvocationContext())
.getConfiguration()
.getOptionAsBoolean(EchoBaseConfiguration.OPTION_AUTO_LOGIN);
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckUserIsAdmin.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckUserIsAdmin.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckUserIsAdmin.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,7 +27,6 @@
import com.opensymphony.xwork2.ActionInvocation;
import fr.ifremer.echobase.entities.EchoBaseUser;
import fr.ifremer.echobase.ui.EchoBaseSession;
-import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -46,10 +45,9 @@
@Override
protected boolean doCheck(ActionInvocation invocation) {
- EchoBaseActionSupport action = (EchoBaseActionSupport) invocation.getAction();
+ EchoBaseSession echoBaseSession = EchoBaseSession.getEchoBaseSession(
+ invocation.getInvocationContext());
- EchoBaseSession echoBaseSession = action.getEchoBaseSession();
-
EchoBaseUser user = echoBaseSession.getUser();
Preconditions.checkNotNull(user, "No user found is session");
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckWorkingDbSelected.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckWorkingDbSelected.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/CheckWorkingDbSelected.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -50,7 +50,8 @@
EchoBaseActionSupport action = (EchoBaseActionSupport)
invocation.getAction();
- EchoBaseSession echoBaseSession = action.getEchoBaseSession();
+ EchoBaseSession echoBaseSession = EchoBaseSession.getEchoBaseSession(
+ invocation.getInvocationContext());
boolean dbSelected = echoBaseSession.isWorkingDbSelected();
if (!dbSelected) {
action.addFlashMessage(l_(action.getLocale(),
Added: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java (rev 0)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,177 @@
+package fr.ifremer.echobase.ui.interceptors;
+
+import com.google.common.base.Preconditions;
+import com.opensymphony.xwork2.ActionInvocation;
+import com.opensymphony.xwork2.interceptor.Interceptor;
+import fr.ifremer.echobase.services.EchoBaseService;
+import fr.ifremer.echobase.services.EchoBaseServiceContext;
+import fr.ifremer.echobase.ui.EchoBaseApplicationContext;
+import fr.ifremer.echobase.ui.EchoBaseInternalDbTransactionFilter;
+import fr.ifremer.echobase.ui.EchoBaseSession;
+import fr.ifremer.echobase.ui.EchoBaseWorkingDbTransactionFilter;
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.util.beans.BeanUtil;
+
+import java.beans.PropertyDescriptor;
+import java.util.Locale;
+import java.util.Set;
+
+public class EchoBaseInjectInterceptor implements Interceptor {
+
+ private static final Log log =
+ LogFactory.getLog(EchoBaseInjectInterceptor.class);
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void init() {
+
+ if (log.isInfoEnabled()) {
+ log.info("init " + this);
+ }
+
+ }
+
+ @Override
+ public String intercept(ActionInvocation invocation) throws Exception {
+
+ Object action = invocation.getAction();
+
+ if (action instanceof EchoBaseActionSupport) {
+ EchoBaseActionSupport echoBaseActionSupport = (EchoBaseActionSupport) action;
+
+ EchoBaseSession userSession = getEchoBaseSession(invocation);
+
+ EchoBaseServiceContext serviceContext = newServiceContext(
+ invocation,
+ echoBaseActionSupport.getLocale());
+
+ Set<PropertyDescriptor> descriptors =
+ BeanUtil.getDescriptors(
+ action.getClass(),
+ BeanUtil.IS_WRITE_DESCRIPTOR);
+
+ for (PropertyDescriptor propertyDescriptor : descriptors) {
+
+ Class<?> propertyType = propertyDescriptor.getPropertyType();
+
+ Object toInject = null;
+
+ if (EchoBaseServiceContext.class.isAssignableFrom(propertyType)) {
+ toInject = serviceContext;
+ } else if (EchoBaseService.class.isAssignableFrom(propertyType)) {
+
+ Class<? extends EchoBaseService> serviceClass =
+ (Class<? extends EchoBaseService>) propertyType;
+
+ toInject = serviceContext.newService(serviceClass);
+
+ } else if (EchoBaseSession.class.isAssignableFrom(propertyType)) {
+
+ toInject = userSession;
+
+ } else if (EchoBaseApplicationContext.class.isAssignableFrom(propertyType)) {
+
+ toInject = getEchoBaseApplicationContext(invocation);
+
+ }
+
+ if (toInject != null) {
+
+ if (log.isTraceEnabled()) {
+ log.trace("injecting " + toInject + " in action " + action);
+ }
+
+ propertyDescriptor.getWriteMethod().invoke(action, toInject);
+
+ }
+ }
+
+ try {
+
+ return invocation.invoke();
+
+ } finally {
+
+ // serviceContext.getPersistenceContext().getEntityTransaction().rollback();
+
+ }
+
+ } else {
+
+ // not an action, just process
+
+ return invocation.invoke();
+
+ }
+
+ }
+
+ protected EchoBaseSession getEchoBaseSession(ActionInvocation invocation) {
+
+ EchoBaseSession session = EchoBaseSession.getEchoBaseSession(
+ invocation.getInvocationContext());
+
+// if (session == null) {
+//
+// session = new EchoBaseSession();
+//
+// invocation.getInvocationContext().getSession().put(EchoBaseSession.SESSION_PARAMETER, session);
+//
+// }
+
+ return session;
+
+ }
+
+ protected EchoBaseApplicationContext getEchoBaseApplicationContext(ActionInvocation invocation) {
+
+ EchoBaseApplicationContext applicationContext =
+ EchoBaseApplicationContext.getApplicationContext(
+ invocation.getInvocationContext());
+
+ Preconditions.checkNotNull(
+ "application context must be initialized before calling an action",
+ applicationContext);
+
+ return applicationContext;
+
+ }
+
+ protected EchoBaseServiceContext newServiceContext(ActionInvocation invocation,
+ Locale locale) {
+
+
+ TopiaContext topiaInternalContext =
+ EchoBaseInternalDbTransactionFilter.getTransaction(
+ invocation.getInvocationContext());
+
+ TopiaContext topiaContext =
+ EchoBaseWorkingDbTransactionFilter.getTransaction(
+ invocation.getInvocationContext());
+
+ EchoBaseApplicationContext applicationContext =
+ getEchoBaseApplicationContext(invocation);
+
+ EchoBaseServiceContext serviceContext =
+ applicationContext.newServiceContext(locale,
+ topiaInternalContext,
+ topiaContext);
+
+ return serviceContext;
+
+ }
+
+ @Override
+ public void destroy() {
+
+ if (log.isInfoEnabled()) {
+ log.info("destroy " + this);
+ }
+
+ }
+
+}
Property changes on: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/interceptors/EchoBaseInjectInterceptor.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/validators/LoginValidator.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/validators/LoginValidator.java 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/validators/LoginValidator.java 2013-08-15 10:53:16 UTC (rev 842)
@@ -25,8 +25,8 @@
import com.opensymphony.xwork2.validator.ValidationException;
import fr.ifremer.echobase.entities.EchoBaseUser;
-import fr.ifremer.echobase.services.ServiceFactoryAware;
-import fr.ifremer.echobase.services.UserService;
+import fr.ifremer.echobase.services.service.UserService;
+import fr.ifremer.echobase.ui.actions.EchoBaseActionSupport;
/**
* Check user login.
@@ -39,10 +39,10 @@
@Override
public void validateWhenNotSkip(Object object) throws ValidationException {
- ServiceFactoryAware serviceFactoryAware = (ServiceFactoryAware) object;
+ EchoBaseActionSupport action = (EchoBaseActionSupport) object;
UserService userService =
- serviceFactoryAware.getService(UserService.class);
+ action.getServiceContext().newService(UserService.class);
String login = (String) getFieldValue("email", object);
String password = (String) getFieldValue("password", object);
Added: trunk/echobase-ui/src/main/resources/config/struts-spatial.xml
===================================================================
--- trunk/echobase-ui/src/main/resources/config/struts-spatial.xml (rev 0)
+++ trunk/echobase-ui/src/main/resources/config/struts-spatial.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ #%L
+ EchoBase :: UI
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 Ifremer, Codelutin
+ %%
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ #L%
+ -->
+<!DOCTYPE struts PUBLIC
+ "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
+ "http://struts.apache.org/dtds/struts-2.3.dtd">
+
+<struts>
+
+ <package name="spatial" extends="logguedAndWithDb" namespace="/spatial">
+
+ <!-- Configure import -->
+ <action name="configure"
+ class="fr.ifremer.echobase.ui.actions.spatial.ConfigureShowSpatialData">
+ <interceptor-ref name="basicStackLogguedWithdb"/>
+ <result>/WEB-INF/jsp/spatial/showData.jsp</result>
+ </action>
+
+ <!-- Reconfigure import -->
+ <action name="reconfigure"
+ class="fr.ifremer.echobase.ui.actions.spatial.ConfigureShowSpatialData">
+ <interceptor-ref name="basicStackLogguedWithdb"/>
+ <result type="redirectAction">
+ <param name="namespace">/spatial</param>
+ <param name="actionName">configure</param>
+ </result>
+ </action>
+
+ <!-- Show spatial map from the given selected data -->
+ <action name="showSpatial"
+ class="fr.ifremer.echobase.ui.actions.spatial.ShowSpatialData">
+ <interceptor-ref name="prepareParamsStackLogguedWithDb"/>
+ <result>/WEB-INF/jsp/spatial/showData.jsp</result>
+ </action>
+
+ <!-- Get all data of a voyage -->
+ <action name="getVoyage*"
+ class="fr.ifremer.echobase.ui.actions.spatial.GetVoyage{1}">
+ <interceptor-ref name="basicStackLogguedWithdb"/>
+ <result type="json"/>
+ </action>
+
+ </package>
+
+</struts>
+
Property changes on: trunk/echobase-ui/src/main/resources/config/struts-spatial.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/resources/config/struts-user.xml
===================================================================
--- trunk/echobase-ui/src/main/resources/config/struts-user.xml 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/resources/config/struts-user.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -36,29 +36,29 @@
method="execute">
<result name="input">/WEB-INF/jsp/user/login.jsp</result>
<result name="redirect" type="redirect">${redirectAction}</result>
- <interceptor-ref name="paramsPrepareParamsStack"/>
+ <interceptor-ref name="echobaseDefaultStack"/>
</action>
<!-- Logout -->
<action name="logout" class="fr.ifremer.echobase.ui.actions.user.Logout">
<result type="redirectToHome"/>
<interceptor-ref name="checkUserLoggued"/>
- <interceptor-ref name="basicStack"/>
+ <interceptor-ref name="echobaseBasicStack"/>
</action>
<!-- Display lists of users -->
<action name="userList"
class="fr.ifremer.echobase.ui.actions.EchoBaseActionSupport">
+ <interceptor-ref name="checkUserIsAdmin"/>
<interceptor-ref name="basicStackLoggued"/>
- <interceptor-ref name="checkUserIsAdmin"/>
<result>/WEB-INF/jsp/user/userList.jsp</result>
</action>
<!-- CRUD on user -->
<action name="user-*"
class="fr.ifremer.echobase.ui.actions.user.{1}">
+ <interceptor-ref name="checkUserIsAdmin"/>
<interceptor-ref name="prepareParamsStackLoggued"/>
- <interceptor-ref name="checkUserIsAdmin"/>
<result name="input">/WEB-INF/jsp/user/{1}.jsp</result>
<result>/WEB-INF/jsp/user/userList.jsp</result>
</action>
Added: trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml
===================================================================
--- trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml (rev 0)
+++ trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,40 @@
+<!--
+ #%L
+ EchoBase :: UI
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ %%
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
+ "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
+<validators>
+
+ <field name="model.voyageId">
+ <field-validator type="nrequiredstring">
+ <message key="echobase.error.showData.voyage.required"/>
+ </field-validator>
+ </field>
+
+ <field name="model.dataMetadataId">
+ <field-validator type="nrequiredstring">
+ <message key="echobase.error.showData.dataMetadata.required"/>
+ </field-validator>
+ </field>
+
+
+</validators>
\ No newline at end of file
Property changes on: trunk/echobase-ui/src/main/resources/fr/ifremer/echobase/ui/actions/spatial/ShowSpatial-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/resources/i18n/echobase-ui_en_GB.properties
===================================================================
--- trunk/echobase-ui/src/main/resources/i18n/echobase-ui_en_GB.properties 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/resources/i18n/echobase-ui_en_GB.properties 2013-08-15 10:53:16 UTC (rev 842)
@@ -12,6 +12,7 @@
echobase.action.createWorkingDbConfiguration=Save
echobase.action.delete=Delete
echobase.action.delete.selectedImport=Delete selected imports
+echobase.action.display=Display spatial data
echobase.action.downloadEmbeddedApplicationFile=Download the portable database
echobase.action.downloadExportDbFile=Download database export file
echobase.action.export=Export
@@ -34,6 +35,7 @@
echobase.action.show.exportDb.documentation=How to export a database
echobase.action.show.import.documentation=How to import data
echobase.action.show.importDb.documentation=How to import a database
+echobase.action.show.showData.documentation=How to display spatial data
echobase.action.toEnglish=English
echobase.action.toFrench=French
echobase.action.usingEnglish=English
@@ -59,12 +61,14 @@
echobase.common.cellRegionsFile=
echobase.common.dataCentre=Data center
echobase.common.dataCentreEmail=Data center email
+echobase.common.dataMetadata=Data Metadata
echobase.common.dataProcessing=DataProcessing
echobase.common.dataProcessingNotes=Data processing notes
echobase.common.datum=Datum
echobase.common.description=Description
echobase.common.digitThreshold=Digitization threshold
echobase.common.distributionStatement=Distribution statement
+echobase.common.echotype=Echotype
echobase.common.echotypeFile=
echobase.common.email=E-mail
echobase.common.entityId=ID
@@ -113,6 +117,7 @@
echobase.common.modificationUser=User
echobase.common.moviesFile=
echobase.common.name=Name
+echobase.common.nbSpatialData=Number of result
echobase.common.operationFile=
echobase.common.operationMetadataFile=
echobase.common.organisationLevelAcknowledgements=organisationLevelAcknowledgements
@@ -131,6 +136,7 @@
echobase.common.soundSpeedCalculationsME70=Sound speed calculation method (ME70 instrument)
echobase.common.sounderConstant=Sounder constant (if relevant)
echobase.common.source=Source
+echobase.common.species=Species
echobase.common.startEndDate=Start - End date
echobase.common.startEndPort=Start - End port
echobase.common.subSampleFile=
@@ -216,6 +222,8 @@
echobase.error.query.name.already.exists=Query name already exists
echobase.error.required.email=E-mail address required
echobase.error.required.password=Password is required
+echobase.error.showData.dataMetadata.required=DataMetadata required
+echobase.error.showData.voyage.required=Voyage required
echobase.error.warlocation.notFound=Database .war file not found at location %s
echobase.error.workingDbConfiguration.couldNotConnect=Could not connect to database (%s)
echobase.error.workingDbConfiguration.description.required=Mandatory description
@@ -309,6 +317,8 @@
echobase.legend.libreOfficeQuery=Translate a SQL query from Libre Office
echobase.legend.removeData.resume=Results of Import removal
echobase.legend.select.voyage=Voyage filter
+echobase.legend.showData.configure=Configure what to display
+echobase.legend.showData.result=Spatial result to display
echobase.legend.sqlQuery.configuration=Query definition
echobase.legend.sqlQuery.result=Query results
echobase.legend.workingDbConfiguration.create=Create a working database configuration
@@ -323,6 +333,7 @@
echobase.menu.importDb=Database import
echobase.menu.logs=Change log
echobase.menu.removeData=Remove data
+echobase.menu.showSpatialData=Show spatial data
echobase.menu.users=Manage users
echobase.menu.viewData=Display data
echobase.message.clickToShowImportDefail=Click to show import detail
@@ -331,6 +342,7 @@
echobase.message.exportDb.result=Export of database (mode %s) was successful (file %s) in %s.
echobase.message.importData.result=Data import successful in %s \:\n%s
echobase.message.no.row.selected=No data selected
+echobase.message.no.spatial.database.support=The working db you are using is not compatible with postgis 2.
echobase.message.noEntrySelection=No field selected
echobase.message.noImportLogSelected=No import selected
echobase.message.noVoyageSelected=No voyage selected
@@ -368,6 +380,7 @@
echobase.title.newLibreOfficeQuery=Translate a SQL query from Libre Office
echobase.title.removeDataProgress=Remove import data
echobase.title.removeDataResult=Result of remove import data
+echobase.title.show.spatial=Show spatial data
echobase.title.users=Administrate users
echobase.title.voyage.detail=Voyage detail
echobase.title.welcome=Welcome to Echobase
Modified: trunk/echobase-ui/src/main/resources/i18n/echobase-ui_fr_FR.properties
===================================================================
--- trunk/echobase-ui/src/main/resources/i18n/echobase-ui_fr_FR.properties 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/resources/i18n/echobase-ui_fr_FR.properties 2013-08-15 10:53:16 UTC (rev 842)
@@ -12,6 +12,7 @@
echobase.action.createWorkingDbConfiguration=Enregistrer
echobase.action.delete=Suppression
echobase.action.delete.selectedImport=Supprimer les imports sélectionnés
+echobase.action.display=Afficher les données
echobase.action.downloadEmbeddedApplicationFile=Télécharger l'application embarquée
echobase.action.downloadExportDbFile=Télécharger le fichier d'export de la base complète
echobase.action.export=Exporter
@@ -34,6 +35,7 @@
echobase.action.show.exportDb.documentation=Comment exporter une base
echobase.action.show.import.documentation=Comment importer des données
echobase.action.show.importDb.documentation=Comment importer une base
+echobase.action.show.showData.documentation=Comment visualiser des données
echobase.action.toEnglish=En anglais
echobase.action.toFrench=En français
echobase.action.usingEnglish=Version anglaise
@@ -60,12 +62,14 @@
echobase.common.cellRegionsFile=
echobase.common.dataCentre=Centre de données
echobase.common.dataCentreEmail=Courriel du centre de données
+echobase.common.dataMetadata=Type de donnée
echobase.common.dataProcessing=DataProcessing
echobase.common.dataProcessingNotes=Notes sur le pré-traitement des données
echobase.common.datum=Référenciel
echobase.common.description=Description
echobase.common.digitThreshold=Seuil de numérisation
echobase.common.distributionStatement=Conditions de diffusion des données
+echobase.common.echotype=Échotype
echobase.common.echotypeFile=
echobase.common.email=Courriel
echobase.common.entityId=Identifiant de l'entité
@@ -114,6 +118,7 @@
echobase.common.modificationUser=Utilisateur
echobase.common.moviesFile=
echobase.common.name=Nom
+echobase.common.nbSpatialData=Nombre de cellules
echobase.common.operationFile=
echobase.common.operationMetadataFile=
echobase.common.organisationLevelAcknowledgements=organisationLevelAcknowledgements
@@ -132,6 +137,7 @@
echobase.common.soundSpeedCalculationsME70=Méthode de calcul de la célérité du son (ME70)
echobase.common.sounderConstant=Constante sondeur (si besoin)
echobase.common.source=Source
+echobase.common.species=Espèce
echobase.common.startEndDate=Date de début - fin
echobase.common.startEndPort=Port de départ - arrivé
echobase.common.subSampleFile=
@@ -217,6 +223,8 @@
echobase.error.query.name.already.exists=Nom de requête déjà utilisé
echobase.error.required.email=Courriel obligatoire
echobase.error.required.password=Le mot de passe est obligatoire
+echobase.error.showData.dataMetadata.required=La sélection d'un type de donnée est obligatoire
+echobase.error.showData.voyage.required=La sélection d'une campagne est obligatoire
echobase.error.warlocation.notFound=L'application n'a pas été trouvée à l'emplacement suivant %s
echobase.error.workingDbConfiguration.couldNotConnect=Impossible de se connecter (%s)
echobase.error.workingDbConfiguration.description.required=Description obligatoire
@@ -310,6 +318,8 @@
echobase.legend.libreOfficeQuery=Traduire une requête SQL issue de Libre Office
echobase.legend.removeData.resume=Résumé de la suppression d'un import
echobase.legend.select.voyage=Filtre Campagne
+echobase.legend.showData.configure=Configurer les données à visualiser
+echobase.legend.showData.result=Résultats à visualiser
echobase.legend.sqlQuery.configuration=Définition de la requête
echobase.legend.sqlQuery.result=Résultats de la requête
echobase.legend.workingDbConfiguration.create=Création d'une configuration de base de travail
@@ -324,6 +334,7 @@
echobase.menu.importDb=Importer une base
echobase.menu.logs=Journal des modifications
echobase.menu.removeData=Supprimer des données
+echobase.menu.showSpatialData=Voir les données spatiales
echobase.menu.users=Gérer les utilisateurs
echobase.menu.viewData=Visualiser les données
echobase.message.clickToShowImportDefail=Cliquer pour obtenir les détails de l'import
@@ -332,6 +343,7 @@
echobase.message.exportDb.result=L'export de la base (mode %s) a réussi (fichier %s) en %s
echobase.message.importData.result=Import de données réussi en %s \:\n%s
echobase.message.no.row.selected=Aucune donnée sélectionnée
+echobase.message.no.spatial.database.support=La base de travail que vous utilisez ne possède pas de support spatiale.
echobase.message.noEntrySelection=Pas de champ sélectionné
echobase.message.noImportLogSelected=Pas d'import sélectionné
echobase.message.noVoyageSelected=Pas de campagne sélectionné
@@ -369,6 +381,7 @@
echobase.title.newLibreOfficeQuery=Traduire une requête SQL issue de Libre Office
echobase.title.removeDataProgress=Suppression d'un import en cours...
echobase.title.removeDataResult=Résultat de la suppression d'un import
+echobase.title.show.spatial=Visualisation des données
echobase.title.users=Administration des utilisateurs
echobase.title.voyage.detail=Détail de la campagne
echobase.title.welcome=Bienvenue dans EchoBase
Modified: trunk/echobase-ui/src/main/resources/struts.xml
===================================================================
--- trunk/echobase-ui/src/main/resources/struts.xml 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/resources/struts.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -31,7 +31,8 @@
<struts>
<bean type="org.apache.struts2.dispatcher.StaticContentLoader"
- class="fr.ifremer.echobase.ui.EchoBaseStaticContentLoader" name="default" />
+ class="fr.ifremer.echobase.ui.EchoBaseStaticContentLoader"
+ name="default" />
<bean class="org.nuiton.web.struts2.I18nTextProvider"
name="i18nTextProvider"
@@ -94,6 +95,52 @@
<param name="redirectAction">/home</param>
</interceptor>
+ <interceptor name="echobaseInjector"
+ class="fr.ifremer.echobase.ui.interceptors.EchoBaseInjectInterceptor"/>
+
+ <interceptor-stack name="echobaseBasicStack">
+ <interceptor-ref name="exception"/>
+ <interceptor-ref name="servletConfig"/>
+ <interceptor-ref name="echobaseInjector"/>
+ <interceptor-ref name="prepare"/>
+ <interceptor-ref name="checkbox"/>
+ <interceptor-ref name="multiselect"/>
+ <interceptor-ref name="actionMappingParams"/>
+ <interceptor-ref name="params">
+ <param name="excludeParams">^_$,dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>
+ </interceptor-ref>
+ <interceptor-ref name="conversionError"/>
+ </interceptor-stack>
+
+ <!-- authenticated stack with prepare - params-->
+ <interceptor-stack name="echobaseDefaultStack">
+ <interceptor-ref name="exception"/>
+ <interceptor-ref name="alias"/>
+ <interceptor-ref name="servletConfig"/>
+ <interceptor-ref name="echobaseInjector"/>
+ <interceptor-ref name="i18n"/>
+ <interceptor-ref name="prepare"/>
+ <interceptor-ref name="chain"/>
+ <interceptor-ref name="scopedModelDriven"/>
+ <interceptor-ref name="modelDriven"/>
+ <interceptor-ref name="fileUpload"/>
+ <interceptor-ref name="checkbox"/>
+ <interceptor-ref name="multiselect"/>
+ <interceptor-ref name="staticParams"/>
+ <interceptor-ref name="actionMappingParams"/>
+ <interceptor-ref name="params">
+ <param name="excludeParams">^_$,dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>
+ </interceptor-ref>
+ <interceptor-ref name="conversionError"/>
+ <interceptor-ref name="validation">
+ <param name="excludeMethods">input,back,cancel,browse</param>
+ </interceptor-ref>
+ <interceptor-ref name="workflow">
+ <param name="excludeMethods">input,back,cancel,browse</param>
+ </interceptor-ref>
+ <interceptor-ref name="debugging"/>
+ </interceptor-stack>
+
</interceptors>
<!-- default action to use everywhere (fix i18n when not translated) -->
@@ -122,14 +169,17 @@
<interceptor-stack name="basicStackLoggued">
<interceptor-ref name="i18n"/>
<interceptor-ref name="checkUserLoggued"/>
- <interceptor-ref name="basicStack"/>
+ <!--<interceptor-ref name="basicStack"/>-->
+ <interceptor-ref name="echobaseBasicStack"/>
</interceptor-stack>
<!-- authenticated stack with prepare - params-->
<interceptor-stack name="prepareParamsStackLoggued">
<interceptor-ref name="i18n"/>
<interceptor-ref name="checkUserLoggued"/>
- <interceptor-ref name="defaultStack"/>
+ <!--<interceptor-ref name="defaultStack"/>-->
+ <interceptor-ref name="echobaseDefaultStack"/>
+
</interceptor-stack>
<!-- basic authenticated stack -->
@@ -137,7 +187,8 @@
<interceptor-ref name="i18n"/>
<interceptor-ref name="checkUserLoggued"/>
<interceptor-ref name="checkWorkingDbSelected"/>
- <interceptor-ref name="basicStack"/>
+ <!--<interceptor-ref name="basicStack"/>-->
+ <interceptor-ref name="echobaseBasicStack"/>
</interceptor-stack>
<!-- authenticated stack with prepare - params-->
@@ -145,7 +196,8 @@
<interceptor-ref name="i18n"/>
<interceptor-ref name="checkUserLoggued"/>
<interceptor-ref name="checkWorkingDbSelected"/>
- <interceptor-ref name="defaultStack"/>
+ <!--<interceptor-ref name="defaultStack"/>-->
+ <interceptor-ref name="echobaseDefaultStack"/>
</interceptor-stack>
</interceptors>
@@ -161,6 +213,7 @@
<default-interceptor-ref name="basicStackLogguedWithdb"/>
</package>
+
<package name="applicationDefault" extends="default" namespace="/">
<default-action-ref name="home"/>
@@ -170,7 +223,8 @@
<result>/WEB-INF/jsp/home.jsp</result>
- <interceptor-ref name="i18nStack"/>
+ <interceptor-ref name="echobaseBasicStack"/>
+ <interceptor-ref name="i18n"/>
<interceptor-ref name="checkUserLoggued"/>
</action>
@@ -179,7 +233,8 @@
<result type="redirectToHome"/>
- <interceptor-ref name="i18nStack"/>
+ <interceptor-ref name="echobaseBasicStack"/>
+ <interceptor-ref name="i18n"/>
<!-- remove the request_locale parameter from request -->
<interceptor-ref name="paramRemover">
<param name="paramNames">request_locale</param>
@@ -199,6 +254,7 @@
<include file="config/struts-importDb.xml"/>
<include file="config/struts-exportDb.xml"/>
<include file="config/struts-removeData.xml"/>
+ <include file="config/struts-spatial.xml"/>
</struts>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/decorators/layout-default.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/decorators/layout-default.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/decorators/layout-default.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -54,10 +54,10 @@
<h2><d:title default="EchoBase"/></h2>
- <s:if test="hasFlashMessages()">
+ <s:if test="%{#session.echoBaseSession.withFlashMessages}">
<div class="info_success clearfix">
<ul class="actionMessages fleft">
- <s:iterator value="flashMessages" var="message">
+ <s:iterator value="%{#session.echoBaseSession.flashMessages}" var="message">
<li><span><s:property value="#message" escapeHtml="false"/></span>
</li>
</s:iterator>
@@ -65,20 +65,20 @@
</div>
</s:if>
- <s:if test="hasFlashWarnings()">
+ <s:if test="#session.echoBaseSession.withFlashWarnings">
<div class="info_warning clearfix">
<ul class="actionWarnings fleft">
- <s:iterator value="flashWarnings" var="message">
+ <s:iterator value="%{#session.echoBaseSession.flashWarnings}" var="message">
<li><span><s:property value="#message" escapeHtml="false"/></span>
</li>
</s:iterator>
</ul>
</div>
</s:if>
- <s:if test="hasFlashErrors()">
+ <s:if test="#session.echoBaseSession.withFlashErrors">
<div class="info_error clearfix">
<ul class="actionErrors fleft">
- <s:iterator value="flashErrors" var="message">
+ <s:iterator value="%{#session.echoBaseSession.flashErrors}" var="message">
<li><span><s:property value="#message" escapeHtml="false"/></span>
</li>
</s:iterator>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/decorators.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -35,6 +35,7 @@
<pattern>/exportQuery/newLibreOfficeQuery*</pattern>
<pattern>/exportQuery/confirmDelete*</pattern>
<pattern>/importData/get*</pattern>
+ <pattern>/spatial/get*</pattern>
<pattern>/workingDb/confirmDelete*</pattern>
<pattern>/workingDb/get*</pattern>
<!--<pattern>/removeData/confirmDelete*</pattern>-->
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/includes/footer.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/includes/footer.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/includes/footer.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -31,7 +31,7 @@
<ul class="clearfix">
<li>
<span style="font-size: 140%">
- EchoBase <%=EchoBaseActionSupport.getApplicationVersion()%>
+ EchoBase <s:property value="#application.echobaseApplicationContext.configuration.applicationVersion"/>
© 2011-2012
</span>
<a href="http://www.ifremer.fr">Ifremer</a>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/includes/header.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/includes/header.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/includes/header.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -50,7 +50,7 @@
</s:text>
</li>
<li>|</li>
- <s:if test="workingDbSelected">
+ <s:if test="#session.echoBaseSession.workingDbSelected">
<li>
<s:a action="disconnect" namespace="/workingDb" id='disconnect'
title='%{getText("echobase.tooltip.disconnectWorkingDb")}'
@@ -86,8 +86,8 @@
</div>
<div class="cleanBoth menu">
<ul>
- <s:if test="%{admin}">
- <s:if test="%{workingDbSelected}">
+ <s:if test="#session.echoBaseSession.user.admin">
+ <s:if test="#session.echoBaseSession.workingDbSelected">
<li>
<s:a action="configureInput" namespace="/importDb" cssClass="impBase">
<span><s:text name="echobase.menu.importDb"/></s:a></span>
@@ -118,6 +118,13 @@
</s:a>
</li>
<li>
+ <s:a action="configure" namespace="/spatial" cssClass="info">
+ <span>
+ <s:text name="echobase.menu.showSpatialData"/>
+ </span>
+ </s:a>
+ </li>
+ <li>
<s:a action="logs" namespace="/workingDb" cssClass="journal">
<span><s:text name="echobase.menu.logs"/></span>
</s:a>
@@ -150,7 +157,7 @@
</li>
</s:if>
<s:else>
- <s:if test="%{workingDbSelected}">
+ <s:if test="#session.echoBaseSession.workingDbSelected">
<li>
<s:a action="manageExportQuery" namespace="/exportQuery"
cssClass="expDonnee">
@@ -163,6 +170,13 @@
</s:a>
</li>
<li>
+ <s:a action="configure" namespace="/spatial" cssClass="info">
+ <span>
+ <s:text name="echobase.menu.showSpatialData"/>
+ </span>
+ </s:a>
+ </li>
+ <li>
<s:a action="logs" namespace="/workingDb" cssClass="journal">
<span><s:text name="echobase.menu.logs"/></span>
</s:a>
Added: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp (rev 0)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,143 @@
+<%--
+ #%L
+ EchoBase :: UI
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ %%
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ #L%
+ --%>
+<%@page contentType="text/html" pageEncoding="UTF-8" %>
+<%@ taglib prefix="s" uri="/struts-tags" %>
+<%@ taglib prefix="sj" uri="/struts-jquery-tags" %>
+<title>
+ <s:text name="echobase.title.show.spatial"/>
+</title>
+
+<script type="text/javascript"
+ src="<s:url value='/js/gridHelper.js' />"></script>
+
+<s:if test="model.withSpatial">
+
+ <script type="text/javascript">
+
+ jQuery(document).ready(function () {
+
+ var getVoyage = $('[name="model.voyageId"]');
+
+ $.autoSelectVoyageAndDataMetadata(
+ getVoyage,
+ $('[name="model.dataMetadataId"]'),
+ '<s:url action="getVoyageDataMetadata" namespace="/spatial"/>',
+ '<s:property value="model.voyageId"/>',
+ '<s:property value="model.dataMetadataId"/>'
+ );
+
+ $.autoSelectVoyageAndSpecies(
+ getVoyage,
+ $('[name="model.speciesId"]'),
+ '<s:url action="getVoyageSpecies" namespace="/spatial"/>',
+ '<s:property value="model.voyageId"/>',
+ '<s:property value="model.speciesId"/>'
+ );
+
+ $.autoSelectVoyageAndEchotype(
+ getVoyage,
+ $('[name="model.echotypeId"]'),
+ '<s:url action="getVoyageEchotype" namespace="/spatial"/>',
+ '<s:property value="model.voyageId"/>',
+ '<s:property value="model.echotypeId"/>'
+ );
+
+ });
+ </script>
+
+ <s:form namespace="/spatial" method="POST" enctype="multipart/form-data">
+
+ <fieldset>
+ <legend>
+ <s:text name="echobase.legend.showData.configure"/>
+ </legend>
+
+ <div class="cleanBoth help">
+ <s:a href="%{getDocumentation('showData.html', null)}" target="doc">
+ <s:text name="echobase.action.show.showData.documentation"/>
+ </s:a>
+ </div>
+ <br/>
+
+ <s:select key="model.voyageId" requiredLabel="true"
+ label='%{getText("echobase.common.voyage")}'
+ list="voyages" headerKey="" headerValue=""/>
+
+ <sj:select key="model.dataMetadataId" requiredLabel="true"
+ label='%{getText("echobase.common.dataMetadata")}'
+ headerKey="" headerValue=""/>
+
+ <sj:select key="model.speciesId" requiredLabel="false"
+ label='%{getText("echobase.common.species")}'
+ headerKey="" headerValue=""/>
+
+ <sj:select key="model.echotypeId" requiredLabel="false"
+ label='%{getText("echobase.common.echotype")}'
+ headerKey="" headerValue=""/>
+
+ <s:hidden key="model.withData" label=' '/>
+ <s:hidden key="model.withSpatial" label=' '/>
+
+ </fieldset>
+ <br/>
+
+ <div class="toolbar">
+ <ul class="toolbar floatRight">
+ <li>
+ <s:submit action='reconfigure' key="echobase.action.reset"/>
+ </li>
+ <li>
+ <s:submit action='save' key="echobase.action.save"/>
+ </li>
+ <li>
+ <s:submit action="showSpatial" key='echobase.action.display'/>
+ </li>
+ </ul>
+ </div>
+
+ <s:if test="model.withData">
+
+ <fieldset>
+ <legend>
+ <s:text name="echobase.legend.showData.result"/>
+ </legend>
+ <s:textfield label='%{getText("echobase.common.nbSpatialData")}'
+ readonly="true"
+ value="%{model.spatialData.size}" requiredLabel="true"/>
+ </fieldset>
+
+ </s:if>
+ <div id="dataPanel">
+ <center>DOME!</center>
+ </div>
+
+ </s:form>
+</s:if>
+<s:else>
+
+ <p>
+ <s:text name="echobase.message.no.spatial.database.support"/>
+ </p>
+</s:else>
+
+
Property changes on: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showData.jsp
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp (rev 0)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -0,0 +1,43 @@
+<%--
+ #%L
+ EchoBase :: UI
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 - 2013 Ifremer, Codelutin
+ %%
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+ #L%
+ --%>
+<%@page contentType="text/html" pageEncoding="UTF-8" %>
+<%@ taglib prefix="s" uri="/struts-tags" %>
+<%@ taglib prefix="sj" uri="/struts-jquery-tags" %>
+
+<script type="text/javascript"
+ src="<s:url value='/js/gridHelper.js' />"></script>
+
+<s:form namespace="/spatial" method="POST" enctype="multipart/form-data">
+
+ <s:hidden key="model.withData" label=' '/>
+ <s:hidden key="model.withSpatial" label=' '/>
+ <s:hidden key="model.voyageId" label=' '/>
+ <s:hidden key="model.dataMetadataId" label=' '/>
+ <s:hidden key="model.categoryId" label=' '/>
+
+</s:form>
+
+<div id="dataPanel">
+
+</div>
+
Property changes on: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/spatial/showDataMap.jsp
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Create.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Create.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Create.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,7 +27,7 @@
<title><s:text name="echobase.label.admin.user.create"/></title>
-<s:form method="post" validate="true" namespace="/user">
+<s:form method="post" validate="true" namespace="/user" action="user-Create">
<fieldset>
<legend>
<s:text name="echobase.common.user"/>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Delete.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Delete.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Delete.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,7 +27,7 @@
<title><s:text name="echobase.label.admin.user.delete"/></title>
-<s:form method="post" validate="true" namespace="/user">
+<s:form method="post" validate="true" namespace="/user" action="user-Delete">
<fieldset>
<legend>
<s:text name="echobase.common.user"/>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Update.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Update.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/user/Update.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -27,7 +27,7 @@
<title><s:text name="echobase.label.admin.user.edit"/></title>
-<s:form method="post" validate="true" namespace="/user">
+<s:form method="post" validate="true" namespace="/user" action="user-Update">
<fieldset>
<legend>
<s:text name="echobase.common.user"/>
Modified: trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/workingDb/manage.jsp
===================================================================
--- trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/workingDb/manage.jsp 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/WEB-INF/jsp/workingDb/manage.jsp 2013-08-15 10:53:16 UTC (rev 842)
@@ -47,7 +47,7 @@
<title><s:text name="echobase.title.workingDbConfiguration"/></title>
-<s:if test="admin">
+<s:if test="echoBaseSession.user.admin">
<s:form id="createForm" namespace="/workingDb">
<ul class="toolbar floatLeft">
<li>
@@ -105,7 +105,7 @@
<s:submit action="connect" theme="simple"
key="echobase.action.connectToWorkingDb"/>
</li>
- <s:if test="admin">
+ <s:if test="echoBaseSession.user.admin">
<li>
<s:submit action="clone" theme="simple"
key="echobase.action.clone"/>
Modified: trunk/echobase-ui/src/main/webapp/js/gridHelper.js
===================================================================
--- trunk/echobase-ui/src/main/webapp/js/gridHelper.js 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/echobase-ui/src/main/webapp/js/gridHelper.js 2013-08-15 10:53:16 UTC (rev 842)
@@ -21,11 +21,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
-( function ($) {
+(function ($) {
$.fn.extend(
{
- addRowSelectTopic:function (gridId, callback) {
+ addRowSelectTopic: function (gridId, callback) {
$.subscribe(gridId + '-rowSelect', function (event) {
if (event.originalEvent) {
var gridId = event.data.id;
@@ -40,10 +40,10 @@
if (callback) {
callback(event);
}
- }, {id:gridId, callback:callback});
+ }, {id: gridId, callback: callback});
},
- addClearSelectTopic:function (gridId, callback) {
+ addClearSelectTopic: function (gridId, callback) {
$.subscribe(gridId + '-clearSelect', function (event) {
var gridId = event.data.id;
jQuery.struts2_jquery[gridId] = {};
@@ -51,16 +51,16 @@
if (callback) {
callback(event);
}
- }, {id:gridId, callback:callback});
+ }, {id: gridId, callback: callback});
},
- addAddRowTopic:function (gridId, url) {
+ addAddRowTopic: function (gridId, url) {
$.subscribe(gridId + '-rowAdd', function (event) {
window.location = event.data.url;
- }, {id:gridId, url:url});
+ }, {id: gridId, url: url});
},
- addSingleRowTopic:function (gridId, action, url, parameterName) {
+ addSingleRowTopic: function (gridId, action, url, parameterName) {
$.subscribe(gridId + '-row' + action, function (event) {
var gridId = event.data.id;
var opts = jQuery.struts2_jquery[gridId];
@@ -71,10 +71,10 @@
params[parameterName] = selectedId;
window.location = $.prepareUrl(event.data.url, params);
}
- }, {id:gridId, url:url, parameterName:parameterName});
+ }, {id: gridId, url: url, parameterName: parameterName});
},
- addSingleRowTopic2:function (gridId, action, callback) {
+ addSingleRowTopic2: function (gridId, action, callback) {
$.subscribe(gridId + '-row' + action, function (event) {
@@ -84,10 +84,10 @@
if (selectedId) {
event.data.callback(event, selectedId);
}
- }, {id:gridId, callback:callback});
+ }, {id: gridId, callback: callback});
},
- addMultiRowTopic:function (gridId, action, target, checkboxName, callback) {
+ addMultiRowTopic: function (gridId, action, target, checkboxName, callback) {
$.subscribe(gridId + '-row' + action, function (event) {
var gridId = event.data.id;
var prefix = 'jqg_' + gridId + '_';
@@ -111,13 +111,13 @@
}
event.data.target.click();
}
- }, {id:gridId,
- target:target,
- checkboxName:checkboxName,
- callback:callback});
+ }, {id: gridId,
+ target: target,
+ checkboxName: checkboxName,
+ callback: callback});
},
- serializeCheckboxs:function (id, params, newId) {
+ serializeCheckboxs: function (id, params, newId) {
var all = $(':checkbox[name="' + id + '"]');
var selected = $(':checked[name="' + id + '"]');
@@ -135,7 +135,7 @@
}
},
- prepareUrl:function (url, params) {
+ prepareUrl: function (url, params) {
var result = url;
if (url.indexOf("?") > -1) {
result += "&";
@@ -146,7 +146,7 @@
return result;
},
- updateSelectBoxContent:function (url, params, jsonTarget, target, callback) {
+ updateSelectBoxContent: function (url, params, jsonTarget, target, callback) {
// call url to obtain datas to injetc in target select box
jQuery.getJSON(url, params, function (result) {
@@ -170,7 +170,7 @@
},
// Ajoute les classes even et odd à tous les tableaux de la page
- addEvenAndOddClasses:function (gridId) {
+ addEvenAndOddClasses: function (gridId) {
// On souscrit au topic qui appelle la fonction addEvenAndOddClasses
$.subscribe(gridId + '-CompleteTopics', function () {
@@ -181,13 +181,13 @@
},
// auto-selection des voyages - vessel
- autoSelectVoyageAndVessel:function (voyageSelectBox, vesselSelectBox, getUrl, voyageId, vesselId) {
+ autoSelectVoyageAndVessel: function (voyageSelectBox, vesselSelectBox, getUrl, voyageId, vesselId) {
- voyageSelectBox.change({vesselSelectBox:vesselSelectBox,
- getUrl:getUrl}, function (event) {
+ voyageSelectBox.change({vesselSelectBox: vesselSelectBox,
+ getUrl: getUrl}, function (event) {
$.updateSelectBoxContent(event.data.getUrl,
- {voyageId:this.value},
+ {voyageId: this.value},
'vessels',
event.data.vesselSelectBox
);
@@ -198,7 +198,7 @@
voyageSelectBox.change(voyageId);
$.updateSelectBoxContent(getUrl,
- {voyageId:voyageId},
+ {voyageId: voyageId},
'vessels',
vesselSelectBox, function () {
@@ -212,15 +212,15 @@
},
// auto-selection des voyages - dataProcessing
- autoSelectVoyageAndDataProcessing:function (voyageSelectBox, datapPocessingSelectBox, getUrl, voyageId, dataProcessingId) {
+ autoSelectVoyageAndDataProcessing: function (voyageSelectBox, datapProcessingSelectBox, getUrl, voyageId, dataProcessingId) {
- voyageSelectBox.change({datapPocessingSelectBox:datapPocessingSelectBox,
- getUrl:getUrl}, function (event) {
+ voyageSelectBox.change({datapProcessingSelectBox: datapProcessingSelectBox,
+ getUrl: getUrl}, function (event) {
$.updateSelectBoxContent(event.data.getUrl,
- {voyageId:this.value},
+ {voyageId: this.value},
'dataProcessings',
- event.data.datapPocessingSelectBox
+ event.data.datapProcessingSelectBox
);
});
@@ -229,61 +229,163 @@
voyageSelectBox.change(voyageId);
$.updateSelectBoxContent(getUrl,
- {voyageId:voyageId},
+ {voyageId: voyageId},
'dataProcessings',
- datapPocessingSelectBox, function () {
+ datapProcessingSelectBox, function () {
if (dataProcessingId) {
- datapPocessingSelectBox.val(dataProcessingId);
+ datapProcessingSelectBox.val(dataProcessingId);
}
}
);
}
+ },
+
+ // auto-selection des voyages - dataMetadata
+ autoSelectVoyageAndDataMetadata: function (voyageSelectBox, datapMetadataSelectBox, getUrl, voyageId, dataMetadataId) {
+
+ voyageSelectBox.change({datapMetadataSelectBox: datapMetadataSelectBox,
+ getUrl: getUrl}, function (event) {
+
+ $.updateSelectBoxContent(event.data.getUrl,
+ {voyageId: this.value},
+ 'data',
+ event.data.datapMetadataSelectBox
+ );
+ });
+
+ if (voyageId) {
+
+ voyageSelectBox.change(voyageId);
+
+ $.updateSelectBoxContent(getUrl,
+ {voyageId: voyageId},
+ 'data',
+ datapMetadataSelectBox, function () {
+
+ if (dataMetadataId) {
+
+ datapMetadataSelectBox.val(dataMetadataId);
+ }
+ }
+ );
+ }
+ },
+
+ // auto-selection des voyages - species
+ autoSelectVoyageAndSpecies: function (voyageSelectBox, speciesSelectBox, getUrl, voyageId, speciesId) {
+
+ voyageSelectBox.change({speciesSelectBox: speciesSelectBox,
+ getUrl: getUrl}, function (event) {
+
+ $.updateSelectBoxContent(event.data.getUrl,
+ {voyageId: this.value},
+ 'data',
+ event.data.speciesSelectBox
+ );
+ });
+
+ if (voyageId) {
+
+ voyageSelectBox.change(voyageId);
+
+ $.updateSelectBoxContent(getUrl,
+ {voyageId: voyageId},
+ 'data',
+ speciesSelectBox, function () {
+
+ if (speciesId) {
+
+ speciesSelectBox.val(speciesId);
+ }
+ }
+ );
+ }
+ },
+
+ // auto-selection des voyages - species
+ autoSelectVoyageAndEchotype: function (voyageSelectBox, echotypeSelectBox, getUrl, voyageId, echotypeId) {
+
+ voyageSelectBox.change({echotypeSelectBox: echotypeSelectBox,
+ getUrl: getUrl}, function (event) {
+
+ $.updateSelectBoxContent(event.data.getUrl,
+ {voyageId: this.value},
+ 'data',
+ event.data.echotypeSelectBox
+ );
+ });
+
+ if (voyageId) {
+
+ voyageSelectBox.change(voyageId);
+
+ $.updateSelectBoxContent(getUrl,
+ {voyageId: voyageId},
+ 'data',
+ echotypeSelectBox, function () {
+
+ if (echotypeId) {
+
+ echotypeSelectBox.val(echotypeId);
+ }
+ }
+ );
+ }
}
});
$.extend({
- addRowSelectTopic:function (gridId, callback) {
+ addRowSelectTopic: function (gridId, callback) {
return $(document).addRowSelectTopic(gridId, callback);
},
- addClearSelectTopic:function (gridId, callback) {
+ addClearSelectTopic: function (gridId, callback) {
return $(document).addClearSelectTopic(gridId, callback);
},
- addAddRowTopic:function (gridId, url) {
+ addAddRowTopic: function (gridId, url) {
return $(document).addAddRowTopic(gridId, url);
},
- addSingleRowTopic:function (gridId, action, url, parameterName) {
+ addSingleRowTopic: function (gridId, action, url, parameterName) {
return $(document).addSingleRowTopic(gridId, action, url, parameterName);
},
- addSingleRowTopic2:function (gridId, action, callback) {
+ addSingleRowTopic2: function (gridId, action, callback) {
return $(document).addSingleRowTopic2(gridId, action, callback);
},
- addMultiRowTopic:function (gridId, action, target, checkboxName, calbback) {
+ addMultiRowTopic: function (gridId, action, target, checkboxName, calbback) {
return $(document).addMultiRowTopic(gridId, action, target, checkboxName, calbback);
},
- serializeCheckboxs:function (id, params, newId) {
+ serializeCheckboxs: function (id, params, newId) {
return $(document).serializeCheckboxs(id, params, newId);
},
- prepareUrl:function (url, params) {
+ prepareUrl: function (url, params) {
return $(document).prepareUrl(url, params);
},
- updateSelectBoxContent:function (url, params, jsonTarget, target, callback) {
+ updateSelectBoxContent: function (url, params, jsonTarget, target, callback) {
return $(document).updateSelectBoxContent(url, params, jsonTarget, target, callback);
},
- addEvenAndOddClasses:function (gridId) {
+ addEvenAndOddClasses: function (gridId) {
return $(document).addEvenAndOddClasses(gridId);
},
- autoSelectVoyageAndVessel:function (voyageSelectBox, vesselSelectBox, getUrl, voyageId, vesselId) {
+ autoSelectVoyageAndVessel: function (voyageSelectBox, vesselSelectBox, getUrl, voyageId, vesselId) {
return $(document).autoSelectVoyageAndVessel(voyageSelectBox, vesselSelectBox, getUrl, voyageId, vesselId);
},
- autoSelectVoyageAndDataProcessing:function (voyageSelectBox, dataProcessingSelectBox, getUrl, voyageId, dataProcessingId) {
+ autoSelectVoyageAndDataProcessing: function (voyageSelectBox, dataProcessingSelectBox, getUrl, voyageId, dataProcessingId) {
return $(document).autoSelectVoyageAndDataProcessing(voyageSelectBox, dataProcessingSelectBox, getUrl, voyageId, dataProcessingId);
+ },
+ autoSelectVoyageAndDataMetadata: function (voyageSelectBox, dataMetadataSelectBox, getUrl, voyageId, dataMetadataId) {
+ return $(document).autoSelectVoyageAndDataMetadata(voyageSelectBox, dataMetadataSelectBox, getUrl, voyageId, dataMetadataId);
+ },
+ autoSelectVoyageAndSpecies: function (voyageSelectBox, speciesSelectBox, getUrl, voyageId, speciesId) {
+ return $(document).autoSelectVoyageAndSpecies(voyageSelectBox, speciesSelectBox, getUrl, voyageId, speciesId);
+ },
+ autoSelectVoyageAndEchotype: function (voyageSelectBox, echotypeSelectBox, getUrl, voyageId, echotypeId) {
+ return $(document).autoSelectVoyageAndEchotype(voyageSelectBox, echotypeSelectBox, getUrl, voyageId, echotypeId);
}
});
})(jQuery);
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-08-09 11:14:40 UTC (rev 841)
+++ trunk/pom.xml 2013-08-15 10:53:16 UTC (rev 842)
@@ -139,8 +139,8 @@
<!-- libraries version -->
- <eugenePluginVersion>2.7</eugenePluginVersion>
- <topiaVersion>3.0-SNAPSHOT</topiaVersion>
+ <eugenePluginVersion>2.7.1-SNAPSHOT</eugenePluginVersion>
+ <topiaVersion>3.0-alpha-3-SNAPSHOT</topiaVersion>
<nuitonUtilsVersion>2.7</nuitonUtilsVersion>
<nuitonI18nVersion>2.5.1</nuitonI18nVersion>
<nuitonWebVersion>1.14</nuitonWebVersion>
1
0
r841 - trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb
by tchemit@users.forge.codelutin.com 09 Aug '13
by tchemit@users.forge.codelutin.com 09 Aug '13
09 Aug '13
Author: tchemit
Date: 2013-08-09 13:14:40 +0200 (Fri, 09 Aug 2013)
New Revision: 841
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/841
Log:
refs #3029: Import de cartes avec param?\195?\168tres non rattach?\195?\169s ?\195?\160 une esp?\195?\168ce de poissons (physique...)
Modified:
trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java
Modified: trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java
===================================================================
--- trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java 2013-08-08 15:19:04 UTC (rev 840)
+++ trunk/echobase-domain/src/main/java/fr/ifremer/echobase/persistence/migration/workingDb/MigrationCallBackForVersion2_2.java 2013-08-09 11:14:40 UTC (rev 841)
@@ -74,7 +74,7 @@
try {
// compute all spatial data
((TopiaSqlSupport) tx).executeSQL("SELECT echobase_compute_all_spatial_data();");
- } catch (TopiaException e) {
+ } catch (Exception e) {
if (log.isErrorEnabled()) {
log.error("Could not update spatial datas", e);
}
1
0
Author: tchemit
Date: 2013-08-08 17:19:04 +0200 (Thu, 08 Aug 2013)
New Revision: 840
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/840
Log:
fixes #3049: Updates mavenpom to 4.0
fixes #2870: Mise ?\195?\160 jour des librairies
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-08-07 17:23:35 UTC (rev 839)
+++ trunk/pom.xml 2013-08-08 15:19:04 UTC (rev 840)
@@ -6,7 +6,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>mavenpom4redmine</artifactId>
- <version>4.0-SNAPSHOT</version>
+ <version>4.0</version>
</parent>
<groupId>fr.ifremer</groupId>
@@ -152,7 +152,7 @@
<slf4jVersion>1.7.5</slf4jVersion>
<jackcessVersion>1.2.13</jackcessVersion>
- <hibernateVersion>4.2.3.Final</hibernateVersion>
+ <hibernateVersion>4.2.4.Final</hibernateVersion>
<googleSearchEnabled>true</googleSearchEnabled>
1
0
08 Aug '13
The EchoBase team is pleased to announce the echobase-2.2-SNAPSHOT release!
The French Institute for the Exploitation of the Sea (Ifremer) has designed
an open software suite for storing fisheries acoustic data and computing
acoustic indicators for survey-based ecosystem monitoring.
It comprises a postgreSQL database designed to store acoustic, navigation
and fishing data from ecosystemic surveys (EchoBase) and a suite of R
codes (EchoR) for computing fish population indicators based on Echobase
data.
Documentation of the project can be found here:
http://maven-site.forge.codelutin.com/echobase
Changes
-------
Changes in this version include:
New features:
o Utiliser le favicon d'echobase pour les application embarquée Issue: 2876. Thanks to Tony Chemit. Resolved by tchemit.
o Permettre l'import séparé des voyages, transits, transects Issue: 3028. Thanks to Tony Chemit. Resolved by tchemit.
o Import de cartes avec paramètres non rattachés à une espèce de poissons (physique...) Issue: 3029. Thanks to Tony Chemit. Resolved by tchemit.
o Pouvoir se connecter à la base de travail avec un autre utilisateur Issue: 2245. Thanks to Tony Chemit. Resolved by tchemit.
Fixed Bugs:
o Paramètres manquants dans la doc d'import de données Issue: 2250. Thanks to Mathieu Doray. Resolved by tchemit.
Changes:
o Normalisation du nom des requètes Issue: 2875. Thanks to Tony Chemit. Resolved by tchemit.
Downloads
---------
For a manual installation, you can download files here:
http://forge.codelutin.com/projects/echobase/files
* echobase-referentiel-2.2-SNAPSHOT.echobase - http://forge.codelutin.com/attachments/download/1030
Maven artifacts
---------------
Artifacts are deployed in nuiton maven repository
http://maven.nuiton.org/other-releases/
Have fun!
-EchoBase team
1
0
08 Aug '13
The EchoBase team is pleased to announce the echobase-2.2-SNAPSHOT release!
The French Institute for the Exploitation of the Sea (Ifremer) has designed
an open software suite for storing fisheries acoustic data and computing
acoustic indicators for survey-based ecosystem monitoring.
It comprises a postgreSQL database designed to store acoustic, navigation
and fishing data from ecosystemic surveys (EchoBase) and a suite of R
codes (EchoR) for computing fish population indicators based on Echobase
data.
Documentation of the project can be found here:
http://maven-site.forge.codelutin.com/echobase
Changes
-------
Changes in this version include:
New features:
o Utiliser le favicon d'echobase pour les application embarquée Issue: 2876. Thanks to Tony Chemit. Resolved by tchemit.
o Permettre l'import séparé des voyages, transits, transects Issue: 3028. Thanks to Tony Chemit. Resolved by tchemit.
o Import de cartes avec paramètres non rattachés à une espèce de poissons (physique...) Issue: 3029. Thanks to Tony Chemit. Resolved by tchemit.
o Pouvoir se connecter à la base de travail avec un autre utilisateur Issue: 2245. Thanks to Tony Chemit. Resolved by tchemit.
Fixed Bugs:
o Paramètres manquants dans la doc d'import de données Issue: 2250. Thanks to Mathieu Doray. Resolved by tchemit.
Changes:
o Normalisation du nom des requètes Issue: 2875. Thanks to Tony Chemit. Resolved by tchemit.
Downloads
---------
For a manual installation, you can download files here:
http://forge.codelutin.com/projects/echobase/files
* echobase-referentiel-2.2-SNAPSHOT.echobase - http://forge.codelutin.com/attachments/download/1029
Maven artifacts
---------------
Artifacts are deployed in nuiton maven repository
http://maven.nuiton.org/other-releases/
Have fun!
-EchoBase team
1
0
07 Aug '13
Author: tchemit
Date: 2013-08-07 19:23:35 +0200 (Wed, 07 Aug 2013)
New Revision: 839
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/839
Log:
add missing license header
Modified:
trunk/echobase-ui/src/main/assembly/dist/help.sql
Modified: trunk/echobase-ui/src/main/assembly/dist/help.sql
===================================================================
--- trunk/echobase-ui/src/main/assembly/dist/help.sql 2013-08-07 17:23:06 UTC (rev 838)
+++ trunk/echobase-ui/src/main/assembly/dist/help.sql 2013-08-07 17:23:35 UTC (rev 839)
@@ -1,3 +1,25 @@
+---
+-- #%L
+-- EchoBase :: UI
+-- $Id:$
+-- $HeadURL:$
+-- %%
+-- Copyright (C) 2011 - 2013 Ifremer, Codelutin
+-- %%
+-- This program is free software: you can redistribute it and/or modify
+-- it under the terms of the GNU Affero General Public License as published by
+-- the Free Software Foundation, either version 3 of the License, or
+-- (at your option) any later version.
+--
+-- This program is distributed in the hope that it will be useful,
+-- but WITHOUT ANY WARRANTY; without even the implied warranty of
+-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+-- GNU General Public License for more details.
+--
+-- You should have received a copy of the GNU Affero General Public License
+-- along with this program. If not, see <http://www.gnu.org/licenses/>.
+-- #L%
+---
DROP FUNCTION IF EXISTS echobase_get_cell_data(cell_id VARCHAR );
CREATE OR REPLACE FUNCTION echobase_get_cell_data(
1
0
Author: tchemit
Date: 2013-08-07 19:23:06 +0200 (Wed, 07 Aug 2013)
New Revision: 838
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/838
Log:
use NG release post process
Modified:
trunk/echobase-ui/pom.xml
Modified: trunk/echobase-ui/pom.xml
===================================================================
--- trunk/echobase-ui/pom.xml 2013-08-07 17:22:32 UTC (rev 837)
+++ trunk/echobase-ui/pom.xml 2013-08-07 17:23:06 UTC (rev 838)
@@ -36,12 +36,8 @@
</deployFiles>
<!-- Post Release configuration -->
+ <skipPostRelease>false</skipPostRelease>
- <skipReleasePublishAttachments>false</skipReleasePublishAttachments>
- <skipReleaseUpdateVersion>false</skipReleaseUpdateVersion>
- <skipReleaseSendEmail>false</skipReleaseSendEmail>
- <skipReleasePublishNews>false</skipReleasePublishNews>
- <skipReleaseNextVersion>false</skipReleaseNextVersion>
</properties>
<build>
1
0
r837 - trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui
by tchemit@users.forge.codelutin.com 07 Aug '13
by tchemit@users.forge.codelutin.com 07 Aug '13
07 Aug '13
Author: tchemit
Date: 2013-08-07 19:22:32 +0200 (Wed, 07 Aug 2013)
New Revision: 837
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/837
Log:
fix memory leak from common-logging
Modified:
trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java
Modified: trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java
===================================================================
--- trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java 2013-08-07 17:19:42 UTC (rev 836)
+++ trunk/echobase-ui/src/main/java/fr/ifremer/echobase/ui/EchoBaseApplicationListener.java 2013-08-07 17:22:32 UTC (rev 837)
@@ -50,6 +50,7 @@
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
+import java.beans.Introspector;
import java.io.File;
import java.io.IOException;
import java.util.Date;
@@ -180,6 +181,12 @@
applicationContext.destroyEchoBaseSession(session);
}
}
+
+ // see http://wiki.apache.org/commons/Logging/FrequentlyAskedQuestions#A_memory_le…
+ ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
+ LogFactory.release(contextClassLoader);
+
+ Introspector.flushCaches();
}
}
1
0
Author: tchemit
Date: 2013-08-07 19:19:42 +0200 (Wed, 07 Aug 2013)
New Revision: 836
Url: http://forge.codelutin.com/projects/echobase/repository/revisions/836
Log:
refs #3049: Updates mavenpom to 4.0
update project description
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-08-07 07:50:32 UTC (rev 835)
+++ trunk/pom.xml 2013-08-07 17:19:42 UTC (rev 836)
@@ -6,7 +6,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>mavenpom4redmine</artifactId>
- <version>3.9</version>
+ <version>4.0-SNAPSHOT</version>
</parent>
<groupId>fr.ifremer</groupId>
@@ -21,7 +21,15 @@
</modules>
<name>EchoBase</name>
- <description>Projet EchoBase</description>
+ <description>
+ The French Institute for the Exploitation of the Sea (Ifremer) has designed
+ an open software suite for storing fisheries acoustic data and computing
+ acoustic indicators for survey-based ecosystem monitoring.
+ It comprises a postgreSQL database designed to store acoustic, navigation
+ and fishing data from ecosystemic surveys (EchoBase) and a suite of R
+ codes (EchoR) for computing fish population indicators based on Echobase
+ data.
+ </description>
<inceptionYear>2011</inceptionYear>
<url>http://maven-site.forge.codelutin.com/echobase</url>
1
0