Isis-fish-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
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- 3175 discussions
r4372 - trunk/src/main/java/fr/ifremer/isisfish/entities
by bpoussin@users.forge.codelutin.com 09 Nov '16
by bpoussin@users.forge.codelutin.com 09 Nov '16
09 Nov '16
Author: bpoussin
Date: 2016-11-09 19:44:50 +0100 (Wed, 09 Nov 2016)
New Revision: 4372
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4372
Log:
amelioration des propositions
Evolution #8737: Export / Import des ?\195?\169l?\195?\169ments d'une r?\195?\169gion, soit pour import dans une autre r?\195?\169gion, soit pour fusion de deux r?\195?\169gions
Modified:
trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-09 17:45:08 UTC (rev 4371)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-09 18:44:50 UTC (rev 4372)
@@ -25,6 +25,7 @@
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import org.apache.commons.beanutils.BeanUtils;
+import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixND;
@@ -50,10 +51,17 @@
public class RegionImportJson {
static public interface RegionMerge {
- static public enum AnwserType {ABORT, IMPORT, IMPORT_ALL_TYPE, IMPORT_ALL, REUSE, NONE};
+ static public enum AnwserType {
+ NONE,
+ REUSE, REUSE_ONE_TYPE, REUSE_ONE,
+ IMPORT, IMPORT_ALL_TYPE, IMPORT_ALL,
+ ABORT
+ };
static public class RegionMergeContext {
protected boolean abort = false;
+ protected boolean reuseOne = false;
+ protected Set<Class> reuseOneType = new HashSet<Class>();
protected boolean importAll = false;
protected Set<Class> importAllType = new HashSet<Class>();
protected AnwserType lastAnswer = null;
@@ -67,6 +75,10 @@
this.importAll = importAll;
}
+ public Class getCurrentType() {
+ return currentType;
+ }
+
public TopiaEntity getReuseEntity() {
return reuseEntity;
}
@@ -75,13 +87,13 @@
return lastAnswer;
}
- protected void setLastAnswer(TopiaEntity e) {
- this.lastAnswer = AnwserType.REUSE;
- this.reuseEntity = e;
+ protected void setLastAnswer(AnwserType lastAnswer) {
+ this.setLastAnswer(lastAnswer, null);
}
- protected void setLastAnswer(AnwserType lastAnswer) {
+ protected void setLastAnswer(AnwserType lastAnswer, TopiaEntity e) {
this.lastAnswer = lastAnswer;
+ this.reuseEntity = e;
switch (lastAnswer) {
case ABORT:
abort = true;
@@ -94,6 +106,14 @@
importAll = true;
this.lastAnswer = AnwserType.IMPORT;
break;
+ case REUSE_ONE_TYPE:
+ reuseOneType.add(currentType);
+ this.lastAnswer = AnwserType.REUSE;
+ break;
+ case REUSE_ONE:
+ reuseOne = true;
+ this.lastAnswer = AnwserType.REUSE;
+ break;
default:
break;
}
@@ -109,6 +129,16 @@
}
return lastAnswer;
}
+
+ public AnwserType initAnswer(Class type, Set<TopiaEntity> possible) {
+ lastAnswer = null;
+ currentType = type;
+ if (possible != null && possible.size() == 1 && (reuseOne || reuseOneType.contains(type))) {
+ lastAnswer = AnwserType.REUSE;
+ this.reuseEntity = possible.iterator().next();
+ }
+ return lastAnswer;
+ }
}
/**
@@ -159,11 +189,30 @@
LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
possible.add(dao.findByTopiaId(id));
- if (details.containsKey("name")) {
- possible.addAll(dao.findAllByProperty("name", details.get("name")));
+ if (Equation.class.isAssignableFrom(context.getCurrentType())) {
+ if (details.containsKey("name") && details.containsKey("category")) {
+ possible.addAll(dao.findAllByProperties("name", details.get("name"), "category", details.get("category")));
+ }
+ } else {
+ if (details.containsKey("name")) {
+ possible.addAll(dao.findAllByProperty("name", details.get("name")));
+ }
}
-// possible.addAll(dao.findAllByProperties(details));
+ context.initAnswer(type, possible);
+
+ if (context.lastAnswer != null) {
+ return context;
+ }
+
+ if (Equation.class.isAssignableFrom(context.getCurrentType())) {
+ if (details.containsKey("category")) {
+ possible.addAll(dao.findAllByProperty("category", details.get("category")));
+ }
+ } else {
+ possible.addAll(dao.findAll());
+ }
+
ask(context, toString, details, possible);
return context;
@@ -178,6 +227,8 @@
Object[] options = new Object[] {
"None", // for null
"Reuse selected object",
+ "Reuse if only one (same type)",
+ "Reuse if only one (all type)",
"Import",
"Import All this type",
"Import All",
@@ -187,12 +238,15 @@
int result = JOptionPane.showOptionDialog(null,
new Object[]{
- String.format("You try to import '%s'", toString),
+ String.format("You try to import '%s' (%s)", toString,
+ ClassUtils.getShortClassName(context.getCurrentType())),
"",
"Possible answer are:",
"None: don't import nor reuse object",
"Reuse: use object already in current Region (make your choice in next combobox).",
select,
+ "Reuse if only one (same type): Answer Reuse and for next time use object found in current Region if only one match 'id' or 'name' for this type",
+ "Reuse if only one (all type): Answer Reuse and for next time use object found in current Region if only one match 'id' or 'name' for all object",
"Import: import object from file.",
"Import All this type: auto answer Import for this question and all next question for same object type",
"Import All: auto answer Import for this question and all next question.",
@@ -205,23 +259,30 @@
options,
options[0]);
+ TopiaEntity selectEntity = (TopiaEntity)select.getSelectedItem();
switch (result) {
case 0:
context.setLastAnswer(AnwserType.NONE);
break;
case 1:
- context.setLastAnswer((TopiaEntity)select.getSelectedItem());
+ context.setLastAnswer(AnwserType.REUSE, selectEntity);
break;
case 2:
+ context.setLastAnswer(AnwserType.REUSE_ONE_TYPE, selectEntity);
+ break;
+ case 3:
+ context.setLastAnswer(AnwserType.REUSE_ONE, selectEntity);
+ break;
+ case 4:
context.setLastAnswer(AnwserType.IMPORT);
break;
- case 3:
+ case 5:
context.setLastAnswer(AnwserType.IMPORT_ALL_TYPE);
break;
- case 4:
+ case 6:
context.setLastAnswer(AnwserType.IMPORT_ALL);
break;
- case 5:
+ case 7:
context.setLastAnswer(AnwserType.ABORT);
break;
default:
1
0
r4371 - trunk/src/main/java/fr/ifremer/isisfish/entities
by bpoussin@users.forge.codelutin.com 09 Nov '16
by bpoussin@users.forge.codelutin.com 09 Nov '16
09 Nov '16
Author: bpoussin
Date: 2016-11-09 18:45:08 +0100 (Wed, 09 Nov 2016)
New Revision: 4371
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4371
Log:
premiere version fonctionnel
Evolution #8737: Export / Import des ?\195?\169l?\195?\169ments d'une r?\195?\169gion, soit pour import dans une autre r?\195?\169gion, soit pour fusion de deux r?\195?\169gions
Modified:
trunk/src/main/java/fr/ifremer/isisfish/entities/MetierImpl.java
trunk/src/main/java/fr/ifremer/isisfish/entities/PopulationImpl.java
trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
trunk/src/main/java/fr/ifremer/isisfish/entities/SpeciesImpl.java
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/MetierImpl.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/MetierImpl.java 2016-11-09 15:24:51 UTC (rev 4370)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/MetierImpl.java 2016-11-09 17:45:08 UTC (rev 4371)
@@ -31,7 +31,9 @@
import fr.ifremer.isisfish.datastore.RegionStorage;
import fr.ifremer.isisfish.datastore.StorageException;
import fr.ifremer.isisfish.types.Month;
+import java.util.List;
+
/**
* Implantation des operations pour l'entité Metier.
*
@@ -59,6 +61,18 @@
}
}
+ /**
+ * Surcharge car avec une aggregation (lien fort) il ne faut pas remplacer
+ * la collection, mais vider celle qui existe et y mettre les nouveaux elements
+ * sinon hibernate perd la tete et leve des exceptions (detecter lors de l'implantation
+ * de l'import json)
+ */
+ @Override
+ public void setMetierSeasonInfo(List<MetierSeasonInfo> metierSeasonInfo) {
+ clearMetierSeasonInfo();
+ addAllMetierSeasonInfo(metierSeasonInfo);
+ }
+
/*
* @see fr.ifremer.isisfish.entities.Metier#getMetierSeasonInfo(fr.ifremer.isisfish.types.Month)
*/
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/PopulationImpl.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/PopulationImpl.java 2016-11-09 15:24:51 UTC (rev 4370)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/PopulationImpl.java 2016-11-09 17:45:08 UTC (rev 4371)
@@ -78,6 +78,31 @@
private static final long serialVersionUID = 1L;
/**
+ * Surcharge car avec une aggregation (lien fort) il ne faut pas remplacer
+ * la collection, mais vider celle qui existe et y mettre les nouveaux elements
+ * sinon hibernate perd la tete et leve des exceptions (detecter lors de l'implantation
+ * de l'import json)
+ * @param populationGroup
+ */
+ @Override
+ public void setPopulationGroup(List<PopulationGroup> populationGroup) {
+ clearPopulationGroup();
+ addAllPopulationGroup(populationGroup);
+ }
+
+ /**
+ * Surcharge car avec une aggregation (lien fort) il ne faut pas remplacer
+ * la collection, mais vider celle qui existe et y mettre les nouveaux elements
+ * sinon hibernate perd la tete et leve des exceptions (detecter lors de l'implantation
+ * de l'import json)
+ */
+ @Override
+ public void setPopulationSeasonInfo(List<PopulationSeasonInfo> populationSeasonInfo) {
+ clearPopulationSeasonInfo();
+ addAllPopulationSeasonInfo(populationSeasonInfo);
+ }
+
+ /**
* Overwrite delete.
* @throws TopiaException
*/
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-09 15:24:51 UTC (rev 4370)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-09 17:45:08 UTC (rev 4371)
@@ -159,7 +159,9 @@
LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
possible.add(dao.findByTopiaId(id));
- possible.addAll(dao.findAllByProperty("name", details.get("name")));
+ if (details.containsKey("name")) {
+ possible.addAll(dao.findAllByProperty("name", details.get("name")));
+ }
// possible.addAll(dao.findAllByProperties(details));
ask(context, toString, details, possible);
@@ -186,6 +188,7 @@
int result = JOptionPane.showOptionDialog(null,
new Object[]{
String.format("You try to import '%s'", toString),
+ "",
"Possible answer are:",
"None: don't import nor reuse object",
"Reuse: use object already in current Region (make your choice in next combobox).",
@@ -245,26 +248,6 @@
}
-// static protected class TopiaTypeResolver extends SimpleAbstractTypeResolver {
-// static private Log log = LogFactory.getLog(TopiaTypeResolver.class);
-// @Override
-// public JavaType findTypeMapping(DeserializationConfig config, JavaType type) {
-// JavaType result = super.findTypeMapping(config, type);
-// if (result == null) {
-// Class<?> src = type.getRawClass();
-// if (TopiaEntity.class.isAssignableFrom(src) && !src.getSimpleName().endsWith("Impl")) {
-// try {
-// Class<?> dest = Class.forName(src.getName() + "Impl");
-// result = config.getTypeFactory().constructSpecializedType(type, dest);
-// } catch (ClassNotFoundException eee) {
-// log.error("Can't create class for " + src.getName() + "Impl", eee);
-// }
-// }
-// }
-// return result;
-// }
-// }
-
/** to use log facility, just put in your code: log.info(\"...\"); */
static private Log log = LogFactory.getLog(RegionImportJson.class);
@@ -273,7 +256,6 @@
protected JsonNode json;
protected LinkedHashMap<String, TopiaEntity> entities;
protected JsonNode jsonEntities;
-// protected ObjectMapper mapper;
protected TopiaEntity currentEntity;
/**
@@ -289,17 +271,6 @@
entities = new LinkedHashMap<String, TopiaEntity>();
-// mapper = new ObjectMapper();
-// mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
-// SimpleModule isisModule = new SimpleModule("IsisModule");
-// isisModule.setAbstractTypes(new TopiaTypeResolver());
-// isisModule.addDeserializer(Month.class, new MonthJsonDeserializer())
-// .addDeserializer(TimeUnit.class, new TimeUnitJsonDeserializer())
-// .addDeserializer(RangeOfValues.class, new RangeOfValuesJsonDeserializer())
-// .addDeserializer(MatrixND.class, new MatrixNDJsonDeserializer(this))
-// .addDeserializer(TopiaEntity.class, new TopiaEntityJsonDeserializer(this));
-// mapper.registerModule(isisModule);
-
ObjectMapper m = new ObjectMapper();
json = m.readTree(r);
jsonEntities = json.get("#entities");
@@ -344,57 +315,6 @@
}
}
-// /**
-// * Return entity with given id. If not already converted, convert it and
-// * add it in global entities converted pool
-// * @param id
-// * @return
-// */
-// private TopiaEntity getEntity(String id, DeserializationContext ctxt) {
-// try {
-// TopiaEntity result = entities.get(id);
-// if (result == null) {
-// JsonNode node = jsonEntities.get(id);
-//
-// Map<String, Object> details = new HashMap<String, Object>();
-// for (Iterator<Entry<String, JsonNode>> i = node.fields(); i.hasNext();) {
-// Entry<String, JsonNode> e = i.next();
-// if (!e.getKey().startsWith("#")) {
-// details.put(e.getKey(), e.getValue().asText());
-// }
-// }
-//
-// TopiaEntity o;
-// String toString = node.get("#toString").asText();
-// merge.choice(mergeContext, id, toString, details);
-// switch (mergeContext.lastAnswer) {
-// case ABORT:
-// throw new IsisFishRuntimeException("Import aborted by user");
-// case NONE:
-// o = null;
-// break;
-// case REUSE:
-// o = mergeContext.getReuseEntity();
-// break;
-// default:
-// // import
-// Class clazz = Class.forName(node.get("#class").asText());
-// o = (TopiaEntity)clazz.newInstance();
-// JavaType type = ctxt.constructType(clazz);
-// JsonDeserializer<Object> des = ctxt.findNonContextualValueDeserializer(type);
-// o = (TopiaEntity)des.deserialize(node.traverse(), ctxt, o);
-//// o = (TopiaEntity)mapper.convertValue(node, clazz);
-// break;
-// }
-//
-// entities.put(id, o);
-// }
-// return result;
-// } catch (Exception eee) {
-// throw new RuntimeException(eee);
-// }
-// }
-
static protected class RegionVisitor implements EntityVisitor {
protected RegionMerge merge;
@@ -579,89 +499,4 @@
public void clear() {
}
}
-
-
-
-//
-// private static class MatrixNDJsonDeserializer extends JsonDeserializer<MatrixND> {
-//
-// protected RegionImportJson importer;
-//
-// public MatrixNDJsonDeserializer(final RegionImportJson importer) {
-// this.importer = importer;
-// }
-//
-// @Override
-// public MatrixND deserialize(JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
-// ObjectCodec oc = p.getCodec();
-// JsonNode node = oc.readTree(p);
-// String mat = node.asText();
-//
-// MatrixCSVHelper matrixCSVHelper = new MatrixCSVHelper(new EntitySemanticsDecorator(
-// new EntitySemanticsDecorator.EntityProvider() {
-// @Override
-// public Object findById(String id) {
-// Object result = importer.getEntity(id, ctxt);
-// return result;
-// }
-// }));
-//
-// MatrixND result = matrixCSVHelper.readMatrix(mat);
-// return result;
-// }
-//
-// }
-//
-// private static class TopiaEntityJsonDeserializer extends JsonDeserializer<TopiaEntity> {
-//
-// protected RegionImportJson importer;
-//
-// public TopiaEntityJsonDeserializer(RegionImportJson importer) {
-// this.importer = importer;
-// }
-//
-// @Override
-// public TopiaEntity deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
-// ObjectCodec oc = p.getCodec();
-// JsonNode node = oc.readTree(p);
-// String id = node.asText();
-// TopiaEntity result = importer.getEntity(id, ctxt);
-// return result;
-// }
-//
-// }
-//
-// private static class MonthJsonDeserializer extends JsonDeserializer<Month> {
-// @Override
-// public Month deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
-// ObjectCodec oc = p.getCodec();
-// JsonNode node = oc.readTree(p);
-// int m = node.asInt();
-// Month result = Month.MONTH[m];
-// return result;
-// }
-// }
-//
-// private static class TimeUnitJsonDeserializer extends JsonDeserializer<TimeUnit> {
-// @Override
-// public TimeUnit deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
-// ObjectCodec oc = p.getCodec();
-// JsonNode node = oc.readTree(p);
-// int v = node.asInt();
-// TimeUnit result = new TimeUnit(v);
-// return result;
-// }
-// }
-//
-// private static class RangeOfValuesJsonDeserializer extends JsonDeserializer<RangeOfValues> {
-// @Override
-// public RangeOfValues deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
-// ObjectCodec oc = p.getCodec();
-// JsonNode node = oc.readTree(p);
-// String v = node.asText();
-// RangeOfValues result = new RangeOfValues(v);
-// return result;
-// }
-// }
-
}
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/SpeciesImpl.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/SpeciesImpl.java 2016-11-09 15:24:51 UTC (rev 4370)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/SpeciesImpl.java 2016-11-09 17:45:08 UTC (rev 4371)
@@ -28,6 +28,7 @@
import fr.ifremer.isisfish.IsisFishRuntimeException;
import fr.ifremer.isisfish.datastore.RegionStorage;
import fr.ifremer.isisfish.datastore.StorageException;
+import java.util.Collection;
/**
* Implantation des operations pour l'entité Species.
@@ -55,6 +56,18 @@
}
}
+ /**
+ * Surcharge car avec une aggregation (lien fort) il ne faut pas remplacer
+ * la collection, mais vider celle qui existe et y mettre les nouveaux elements
+ * sinon hibernate perd la tete et leve des exceptions (detecter lors de l'implantation
+ * de l'import json)
+ */
+ @Override
+ public void setPopulation(Collection<Population> population) {
+ clearPopulation();
+ addAllPopulation(population);
+ }
+
/*
* @see fr.ifremer.isisfish.entities.FisheryRegionAbstract#toString()
*/
1
0
r4370 - in trunk/src/main/java/fr/ifremer/isisfish: entities ui/input
by bpoussin@users.forge.codelutin.com 09 Nov '16
by bpoussin@users.forge.codelutin.com 09 Nov '16
09 Nov '16
Author: bpoussin
Date: 2016-11-09 16:24:51 +0100 (Wed, 09 Nov 2016)
New Revision: 4370
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4370
Log:
work in progress: Evolution #8737: Export / Import des ?\195?\169l?\195?\169ments d'une r?\195?\169gion, soit pour import dans une autre r?\195?\169gion, soit pour fusion de deux r?\195?\169gions.
Modified:
trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java
trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java 2016-11-04 15:05:55 UTC (rev 4369)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java 2016-11-09 15:24:51 UTC (rev 4370)
@@ -364,33 +364,4 @@
decorator = null;
}
-
-// abstract public void visit(Cell v);
-// abstract public void visit(EffortDescription v);
-// abstract public void visit(FisheryRegion region);
-// abstract public void visit(Gear v);
-// abstract public void visit(Metier v);
-// abstract public void visit(MetierSeasonInfo v);
-// abstract public void visit(PopulationGroup v);
-// abstract public void visit(Population v);
-// abstract public void visit(PopulationSeasonInfo v);
-// abstract public void visit(Port v);
-// abstract public void visit(Season v);
-// abstract public void visit(Selectivity v);
-// abstract public void visit(SetOfVessels v);
-// abstract public void visit(Species v);
-// abstract public void visit(Strategy v);
-// abstract public void visit(StrategyMonthInfo v);
-// abstract public void visit(TargetSpecies v);
-// abstract public void visit(TripType v);
-// abstract public void visit(Variable v);
-// abstract public void visit(VariableType v);
-// abstract public void visit(VesselType v);
-// abstract public void visit(Zone v);
-// abstract public void visit(Equation v);
-// abstract public void visit(MatrixND v);
-// abstract public void visit(String v);
-// abstract public void visit(int v);
-// abstract public void visit(float v);
-
}
Modified: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-04 15:05:55 UTC (rev 4369)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-09 15:24:51 UTC (rev 4370)
@@ -1,15 +1,10 @@
package fr.ifremer.isisfish.entities;
-import com.fasterxml.jackson.core.JsonParser;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.ObjectCodec;
-import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.module.SimpleModule;
import fr.ifremer.isisfish.IsisFishDAOHelper;
+import fr.ifremer.isisfish.IsisFishRuntimeException;
import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.types.RangeOfValues;
import fr.ifremer.isisfish.types.TimeUnit;
@@ -18,15 +13,26 @@
import java.io.IOException;
import java.io.Reader;
import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
+import javax.swing.JComboBox;
+import javax.swing.JOptionPane;
+import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixND;
import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaId;
/**
* Classe permettant d'importer des données dans une region a partir d'un
@@ -44,246 +50,255 @@
public class RegionImportJson {
static public interface RegionMerge {
- public TopiaEntity choice(TopiaEntity e);
- }
+ static public enum AnwserType {ABORT, IMPORT, IMPORT_ALL_TYPE, IMPORT_ALL, REUSE, NONE};
- static public class RegionMergeDatabase implements RegionMerge {
- protected TopiaContext tx;
+ static public class RegionMergeContext {
+ protected boolean abort = false;
+ protected boolean importAll = false;
+ protected Set<Class> importAllType = new HashSet<Class>();
+ protected AnwserType lastAnswer = null;
+ protected TopiaEntity reuseEntity;
+ protected Class currentType;
- public RegionMergeDatabase(TopiaContext tx) {
- this.tx = tx;
- }
+ public RegionMergeContext() {
+ }
- @Override
- public TopiaEntity choice(TopiaEntity e) {
- TopiaEntity result;
-
- if (e instanceof FisheryRegion) {
- result = choice((FisheryRegion)e);
- } else if (e instanceof Cell) {
- result = choice((Cell)e);
- } else if (e instanceof Zone) {
- result = choice((Zone)e);
- } else if (e instanceof Port) {
- result = choice((Port)e);
- } else if (e instanceof Species) {
- result = choice((Species)e);
- } else if (e instanceof Population) {
- result = choice((Population)e);
- } else if (e instanceof Gear) {
- result = choice((Gear)e);
- } else if (e instanceof Metier) {
- result = choice((Metier)e);
- } else if (e instanceof TripType) {
- result = choice((TripType)e);
- } else if (e instanceof VesselType) {
- result = choice((VesselType)e);
- } else if (e instanceof SetOfVessels) {
- result = choice((SetOfVessels)e);
- } else if (e instanceof Strategy) {
- result = choice((Strategy)e);
- } else if (e instanceof Observation) {
- result = choice((Observation)e);
- } else {
- log.info("Not supported entity type: " + e.getClass().getSimpleName());
- result = genericChoice(e);
+ public RegionMergeContext(boolean importAll) {
+ this.importAll = importAll;
}
- return result;
- }
+ public TopiaEntity getReuseEntity() {
+ return reuseEntity;
+ }
- protected TopiaEntity ask(TopiaEntity e, Collection<TopiaEntity> possible) {
- System.out.println("Choice between:" + e + " and " + possible);
- return e; // FIXME
- }
+ public AnwserType getLastAnswer() {
+ return lastAnswer;
+ }
- protected TopiaEntity genericChoice(TopiaEntity e) {
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+ protected void setLastAnswer(TopiaEntity e) {
+ this.lastAnswer = AnwserType.REUSE;
+ this.reuseEntity = e;
+ }
- possible.add(tx.findByTopiaId(e.getTopiaId()));
+ protected void setLastAnswer(AnwserType lastAnswer) {
+ this.lastAnswer = lastAnswer;
+ switch (lastAnswer) {
+ case ABORT:
+ abort = true;
+ break;
+ case IMPORT_ALL_TYPE:
+ importAllType.add(currentType);
+ this.lastAnswer = AnwserType.IMPORT;
+ break;
+ case IMPORT_ALL:
+ importAll = true;
+ this.lastAnswer = AnwserType.IMPORT;
+ break;
+ default:
+ break;
+ }
+ }
- TopiaEntity result = ask(e, possible);
- return result;
+ public AnwserType initAnswer(Class type) {
+ lastAnswer = null;
+ currentType = type;
+ if (abort) {
+ lastAnswer = AnwserType.ABORT;
+ } else if (importAll || importAllType.contains(type)) {
+ lastAnswer = AnwserType.IMPORT;
+ }
+ return lastAnswer;
+ }
}
- protected TopiaEntity choice(FisheryRegion e) {
- FisheryRegionDAO dao = IsisFishDAOHelper.getFisheryRegionDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+ /**
+ * Ask how to merge entity
+ * @param context
+ * @param id
+ * @param toString
+ * @param details
+ * @return
+ */
+ public RegionMergeContext choice(RegionMergeContext context, String id, String toString, Map<String, Object> details);
+ /**
+ * If exist return entity with id in parameter
+ * @param id
+ * @return null or TopiaEntity
+ */
+ public TopiaEntity getEntity(String id);
+ }
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
+ static public class RegionMergeDatabase implements RegionMerge {
+ protected TopiaContext tx;
- TopiaEntity result = ask(e, possible);
- return result;
+ public RegionMergeDatabase(TopiaContext tx) {
+ this.tx = tx;
}
- protected TopiaEntity choice(Cell e) {
- CellDAO dao = IsisFishDAOHelper.getCellDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
+ @Override
+ public TopiaEntity getEntity(String id) {
+ TopiaEntity result = tx.findByTopiaId(id);
return result;
}
-
- protected TopiaEntity choice(Zone e) {
- ZoneDAO dao = IsisFishDAOHelper.getZoneDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
+ @Override
+ public RegionMergeContext choice(RegionMergeContext context, String id, String toString, Map<String, Object> details) {
+ Class type = TopiaId.getClassName(id);
+ if (context == null) {
+ context = new RegionMergeContext();
+ } else {
+ context.initAnswer(type);
+ }
- TopiaEntity result = ask(e, possible);
- return result;
- }
+ if (context.lastAnswer != null) {
+ return context;
+ }
- protected TopiaEntity choice(Port e) {
- PortDAO dao = IsisFishDAOHelper.getPortDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+ TopiaDAO<TopiaEntity> dao = IsisFishDAOHelper.getDAO(tx, type);
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
- }
-
- protected TopiaEntity choice(Species e) {
- SpeciesDAO dao = IsisFishDAOHelper.getSpeciesDAO(tx);
LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
+ possible.add(dao.findByTopiaId(id));
+ possible.addAll(dao.findAllByProperty("name", details.get("name")));
+// possible.addAll(dao.findAllByProperties(details));
- TopiaEntity result = ask(e, possible);
- return result;
- }
+ ask(context, toString, details, possible);
- protected TopiaEntity choice(Population e) {
- PopulationDAO dao = IsisFishDAOHelper.getPopulationDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
+ return context;
}
- protected TopiaEntity choice(Gear e) {
- GearDAO dao = IsisFishDAOHelper.getGearDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+ protected void ask(RegionMergeContext context, String toString,
+ Map<String, Object> details, Collection<TopiaEntity> possible) {
+ System.out.println("Choice between:" + toString + " and " + possible);
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
+ JComboBox select = new JComboBox(possible.toArray());
- TopiaEntity result = ask(e, possible);
- return result;
- }
+ Object[] options = new Object[] {
+ "None", // for null
+ "Reuse selected object",
+ "Import",
+ "Import All this type",
+ "Import All",
+ "Abort"
+ };
- protected TopiaEntity choice(Metier e) {
- MetierDAO dao = IsisFishDAOHelper.getMetierDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
+ int result = JOptionPane.showOptionDialog(null,
+ new Object[]{
+ String.format("You try to import '%s'", toString),
+ "Possible answer are:",
+ "None: don't import nor reuse object",
+ "Reuse: use object already in current Region (make your choice in next combobox).",
+ select,
+ "Import: import object from file.",
+ "Import All this type: auto answer Import for this question and all next question for same object type",
+ "Import All: auto answer Import for this question and all next question.",
+ "Abort: Cancel this import (import nothing)"
+ },
+ "Make a choice",
+ JOptionPane.DEFAULT_OPTION,
+ JOptionPane.QUESTION_MESSAGE,
+ null,
+ options,
+ options[0]);
- TopiaEntity result = ask(e, possible);
- return result;
+ switch (result) {
+ case 0:
+ context.setLastAnswer(AnwserType.NONE);
+ break;
+ case 1:
+ context.setLastAnswer((TopiaEntity)select.getSelectedItem());
+ break;
+ case 2:
+ context.setLastAnswer(AnwserType.IMPORT);
+ break;
+ case 3:
+ context.setLastAnswer(AnwserType.IMPORT_ALL_TYPE);
+ break;
+ case 4:
+ context.setLastAnswer(AnwserType.IMPORT_ALL);
+ break;
+ case 5:
+ context.setLastAnswer(AnwserType.ABORT);
+ break;
+ default:
+ ask(context, toString, details, possible);
+ break;
+ }
}
+ }
- protected TopiaEntity choice(TripType e) {
- TripTypeDAO dao = IsisFishDAOHelper.getTripTypeDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
+ static public class RegionMergeImportAll implements RegionMerge {
+ @Override
+ public TopiaEntity getEntity(String id) {
+ return null;
}
- protected TopiaEntity choice(VesselType e) {
- VesselTypeDAO dao = IsisFishDAOHelper.getVesselTypeDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
+ @Override
+ public RegionMergeContext choice(RegionMergeContext context, String id, String toString, Map<String, Object> details) {
+ if (context == null) {
+ context = new RegionMergeContext();
+ }
+ context.setLastAnswer(AnwserType.IMPORT);
+ return context;
}
- protected TopiaEntity choice(SetOfVessels e) {
- SetOfVesselsDAO dao = IsisFishDAOHelper.getSetOfVesselsDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
- }
-
- protected TopiaEntity choice(Strategy e) {
- StrategyDAO dao = IsisFishDAOHelper.getStrategyDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
- }
-
- protected TopiaEntity choice(Observation e) {
- ObservationDAO dao = IsisFishDAOHelper.getObservationDAO(tx);
- LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
-
- possible.add(dao.findByTopiaId(e.getTopiaId()));
- possible.addAll(dao.findAllByName(e.getName()));
-
- TopiaEntity result = ask(e, possible);
- return result;
- }
}
- static public class RegionMergeNoMerge implements RegionMerge {
- @Override
- public TopiaEntity choice(TopiaEntity e) {
- return e;
- }
- }
+// static protected class TopiaTypeResolver extends SimpleAbstractTypeResolver {
+// static private Log log = LogFactory.getLog(TopiaTypeResolver.class);
+// @Override
+// public JavaType findTypeMapping(DeserializationConfig config, JavaType type) {
+// JavaType result = super.findTypeMapping(config, type);
+// if (result == null) {
+// Class<?> src = type.getRawClass();
+// if (TopiaEntity.class.isAssignableFrom(src) && !src.getSimpleName().endsWith("Impl")) {
+// try {
+// Class<?> dest = Class.forName(src.getName() + "Impl");
+// result = config.getTypeFactory().constructSpecializedType(type, dest);
+// } catch (ClassNotFoundException eee) {
+// log.error("Can't create class for " + src.getName() + "Impl", eee);
+// }
+// }
+// }
+// return result;
+// }
+// }
/** to use log facility, just put in your code: log.info(\"...\"); */
static private Log log = LogFactory.getLog(RegionImportJson.class);
protected RegionMerge merge;
+ protected RegionMerge.RegionMergeContext mergeContext;
protected JsonNode json;
protected LinkedHashMap<String, TopiaEntity> entities;
protected JsonNode jsonEntities;
- protected ObjectMapper mapper;
+// protected ObjectMapper mapper;
+ protected TopiaEntity currentEntity;
/**
*
* @param r reader contains json
- * @param merge use to choice entity in Json or entity in current region
+ * @param merge use to choice entity in Json or entity in current region,
+ * if no merge object is passed in arguement "import all" object in reader
*/
public RegionImportJson(Reader r, RegionMerge merge) {
try {
- this.merge = merge != null ? merge : new RegionMergeNoMerge();
+ this.merge = merge != null ? merge : new RegionMergeImportAll();
+ this.mergeContext = new RegionMerge.RegionMergeContext();
+
entities = new LinkedHashMap<String, TopiaEntity>();
- mapper = new ObjectMapper();
- SimpleModule isisModule = new SimpleModule("IsisModule")
- .addDeserializer(Month.class, new MonthJsonDeserializer())
- .addDeserializer(TimeUnit.class, new TimeUnitJsonDeserializer())
- .addDeserializer(RangeOfValues.class, new RangeOfValuesJsonDeserializer())
- .addDeserializer(MatrixND.class, new MatrixNDJsonDeserializer(this))
- .addDeserializer(TopiaEntity.class, new TopiaEntityJsonDeserializer(this));
- mapper.registerModule(isisModule);
+// mapper = new ObjectMapper();
+// mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+// SimpleModule isisModule = new SimpleModule("IsisModule");
+// isisModule.setAbstractTypes(new TopiaTypeResolver());
+// isisModule.addDeserializer(Month.class, new MonthJsonDeserializer())
+// .addDeserializer(TimeUnit.class, new TimeUnitJsonDeserializer())
+// .addDeserializer(RangeOfValues.class, new RangeOfValuesJsonDeserializer())
+// .addDeserializer(MatrixND.class, new MatrixNDJsonDeserializer(this))
+// .addDeserializer(TopiaEntity.class, new TopiaEntityJsonDeserializer(this));
+// mapper.registerModule(isisModule);
ObjectMapper m = new ObjectMapper();
json = m.readTree(r);
@@ -297,7 +312,7 @@
* Return all entities available in Json reader
* @return
*/
- public Collection<TopiaEntity> getEntity() {
+ public Collection<TopiaEntity> getEntities() {
try {
JsonNode info = json.with("#info");
boolean isRegion = info.get("region").asBoolean(false);
@@ -304,7 +319,9 @@
if (!isRegion) {
// il n'y a qu'un objet dans le json, on le deserialize
String rootId = info.get("rootId").asText();
- getEntity(rootId);
+ RegionVisitor v = new RegionVisitor(merge, mergeContext, rootId, entities, jsonEntities);
+ // no assigment, collect of entities is done during deserialize
+ v.loadEntity();
} else {
// il y a toute une region, on lit les listes d'id des objets
// principaux (cell, zone, port, ...)
@@ -313,7 +330,9 @@
// les champs commencant par des # sont #info et #entities
if (!field.getKey().startsWith("#")) {
for (JsonNode id : field.getValue()) {
- getEntity(id.asText());
+ RegionVisitor v = new RegionVisitor(merge, mergeContext, id.asText(), entities, jsonEntities);
+ // no assigment, collect of entities is done during deserialize
+ v.loadEntity();
}
}
}
@@ -325,104 +344,324 @@
}
}
- /**
- * Return entity with given id. If not already converted, convert it and
- * add it in global entities converted pool
- * @param id
- * @return
- */
- public TopiaEntity getEntity(String id) {
- try {
- TopiaEntity result = entities.get(id);
- if (result == null) {
- JsonNode node = jsonEntities.get(id);
- Class clazz = Class.forName(node.get("#class").asText());
- TopiaEntity o = (TopiaEntity)mapper.convertValue(node, clazz);
- o = merge.choice(o);
- entities.put(id, o);
+// /**
+// * Return entity with given id. If not already converted, convert it and
+// * add it in global entities converted pool
+// * @param id
+// * @return
+// */
+// private TopiaEntity getEntity(String id, DeserializationContext ctxt) {
+// try {
+// TopiaEntity result = entities.get(id);
+// if (result == null) {
+// JsonNode node = jsonEntities.get(id);
+//
+// Map<String, Object> details = new HashMap<String, Object>();
+// for (Iterator<Entry<String, JsonNode>> i = node.fields(); i.hasNext();) {
+// Entry<String, JsonNode> e = i.next();
+// if (!e.getKey().startsWith("#")) {
+// details.put(e.getKey(), e.getValue().asText());
+// }
+// }
+//
+// TopiaEntity o;
+// String toString = node.get("#toString").asText();
+// merge.choice(mergeContext, id, toString, details);
+// switch (mergeContext.lastAnswer) {
+// case ABORT:
+// throw new IsisFishRuntimeException("Import aborted by user");
+// case NONE:
+// o = null;
+// break;
+// case REUSE:
+// o = mergeContext.getReuseEntity();
+// break;
+// default:
+// // import
+// Class clazz = Class.forName(node.get("#class").asText());
+// o = (TopiaEntity)clazz.newInstance();
+// JavaType type = ctxt.constructType(clazz);
+// JsonDeserializer<Object> des = ctxt.findNonContextualValueDeserializer(type);
+// o = (TopiaEntity)des.deserialize(node.traverse(), ctxt, o);
+//// o = (TopiaEntity)mapper.convertValue(node, clazz);
+// break;
+// }
+//
+// entities.put(id, o);
+// }
+// return result;
+// } catch (Exception eee) {
+// throw new RuntimeException(eee);
+// }
+// }
+
+ static protected class RegionVisitor implements EntityVisitor {
+
+ protected RegionMerge merge;
+ protected RegionMerge.RegionMergeContext mergeContext;
+ protected JsonNode nodeEntity;
+ protected TopiaEntity currentEntity;
+ protected LinkedHashMap<String, TopiaEntity> entities;
+ protected JsonNode jsonEntities;
+
+ public RegionVisitor(RegionMerge merge, RegionMerge.RegionMergeContext mergeContext,
+ String idEntity,
+ LinkedHashMap<String, TopiaEntity> entities, JsonNode jsonEntities) {
+ this.merge = merge;
+ this.mergeContext = mergeContext;
+ this.nodeEntity = jsonEntities.get(idEntity);
+ this.entities = entities;
+ this.jsonEntities = jsonEntities;
+ }
+
+ public TopiaEntity loadEntity() {
+ String id = nodeEntity.get("#id").asText();
+ currentEntity = entities.get(id);
+ if (currentEntity == null) {
+ currentEntity = ask(id);
}
+ return currentEntity;
+ }
+
+ protected TopiaEntity convertJsonToEntity(JsonNode node) {
+ TopiaEntity result;
+ String id = node.get("#id").asText();
+ String className = node.get("#class").asText();
+ try {
+ // try to reuse entity
+ result = merge.getEntity(id);
+ if (result == null) {
+ // if no entity with same id, create new one
+ Class clazz = Class.forName(className);
+ result = (TopiaEntity)clazz.newInstance();
+ result.setTopiaId(id);
+ }
+ // add in list save after import
+ entities.put(id, result);
+
+ result.accept(this);
+ } catch (Exception eee) {
+ throw new IsisFishRuntimeException("Can't instanciate entity: " + className, eee);
+ }
return result;
- } catch (Exception eee) {
- throw new RuntimeException(eee);
}
- }
- private static class MatrixNDJsonDeserializer extends JsonDeserializer<MatrixND> {
+ protected TopiaEntity ask(String id) {
+ JsonNode node = jsonEntities.get(id);
- protected MatrixCSVHelper matrixCSVHelper;
-
- public MatrixNDJsonDeserializer(final RegionImportJson importer) {
- matrixCSVHelper = new MatrixCSVHelper(new EntitySemanticsDecorator(
- new EntitySemanticsDecorator.EntityProvider() {
- @Override
- public Object findById(String id) {
- Object result = importer.getEntity(id);
- return result;
+ Map<String, Object> details = new HashMap<String, Object>();
+ for (Iterator<Entry<String, JsonNode>> i = node.fields(); i.hasNext();) {
+ Entry<String, JsonNode> e = i.next();
+ if (!e.getKey().startsWith("#")) {
+ details.put(e.getKey(), e.getValue().asText());
}
- }));
- }
+ }
- @Override
- public MatrixND deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- ObjectCodec oc = p.getCodec();
- JsonNode node = oc.readTree(p);
- String mat = node.asText();
- MatrixND result = matrixCSVHelper.readMatrix(mat);
+ TopiaEntity result;
+ String toString = node.get("#toString").asText();
+ merge.choice(mergeContext, id, toString, details);
+ switch (mergeContext.lastAnswer) {
+ case ABORT:
+ throw new IsisFishRuntimeException("Import aborted by user");
+ case NONE:
+ result = null;
+ break;
+ case REUSE:
+ result = mergeContext.getReuseEntity();
+ break;
+ default:
+ result = convertJsonToEntity(node);
+ break;
+ }
return result;
}
- }
+ protected Object readValue(Class<?> type, JsonNode value) {
+ Object result;
+ try {
+ if (value == null || value.isNull() || value.isMissingNode()) {
+ result = null;
+ } else if (TopiaEntity.class.isAssignableFrom(type)) {
+ String id = value.asText();
+ RegionVisitor child = new RegionVisitor(merge, mergeContext, id, entities, jsonEntities);
+ result = child.loadEntity();
+ } else if (MatrixND.class.isAssignableFrom(type)) {
+ String mat = value.asText();
- private static class TopiaEntityJsonDeserializer extends JsonDeserializer<TopiaEntity> {
+ MatrixCSVHelper matrixCSVHelper = new MatrixCSVHelper(new EntitySemanticsDecorator(
+ new EntitySemanticsDecorator.EntityProvider() {
+ @Override
+ public Object findById(String id) {
+ RegionVisitor child = new RegionVisitor(merge, mergeContext, id, entities, jsonEntities);
+ Object result = child.loadEntity();
+ return result;
+ }
+ }));
- protected RegionImportJson importer;
+ result = matrixCSVHelper.readMatrix(mat);
- public TopiaEntityJsonDeserializer(RegionImportJson importer) {
- this.importer = importer;
+ } else if (TimeUnit.class.isAssignableFrom(type)) {
+ result = new TimeUnit(value.asDouble());
+ } else if (RangeOfValues.class.isAssignableFrom(type)) {
+ String v = value.asText();
+ result = new RangeOfValues(v);
+ } else if (Month.class.isAssignableFrom(type)) {
+ int m = value.asInt();
+ result = Month.MONTH[m];
+ } else if (Class.class.isAssignableFrom(type)) {
+ String className = value.asText();
+ result = Class.forName(className);
+ } else if (String.class.isAssignableFrom(type)) {
+ result = value.asText();
+ } else if (Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type)) {
+ result = value.asBoolean();
+ } else if (Number.class.isAssignableFrom(type) || type.isPrimitive()) { // Number must be after Boolean
+ // all other possible primitive type is number (void and char are not admited in json)
+ result = value.asDouble();
+ } else {
+ String message = String.format("Unsupported type: '%s' value class '%s' value '%s'", type, value.getClass().getName(), value);
+ log.error(message);
+ throw new IsisFishRuntimeException(message);
+ }
+ } catch (Exception eee) {
+ throw new IsisFishRuntimeException("Can't convert json value:" + value, eee);
+ }
+ return result;
}
@Override
- public TopiaEntity deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- ObjectCodec oc = p.getCodec();
- JsonNode node = oc.readTree(p);
- String id = node.asText();
- TopiaEntity result = importer.getEntity(id);
- return result;
+ public void start(TopiaEntity entity) {
}
- }
+ @Override
+ public void end(TopiaEntity entity) {
+ }
- private static class MonthJsonDeserializer extends JsonDeserializer<Month> {
@Override
- public Month deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- ObjectCodec oc = p.getCodec();
- JsonNode node = oc.readTree(p);
- int m = node.asInt();
- Month result = Month.MONTH[m];
- return result;
+ public void visit(TopiaEntity entity, String propertyName, Class<?> type, Object value) {
+ JsonNode jsonValue = nodeEntity.get(propertyName);
+ try {
+ value = readValue(type, jsonValue);
+ BeanUtils.setProperty(entity, propertyName, value);
+ } catch (Exception eee) {
+ throw new IsisFishRuntimeException(String.format("Can't set property '%s' from json value: '%s'", propertyName, jsonValue), eee);
+ }
}
- }
- private static class TimeUnitJsonDeserializer extends JsonDeserializer<TimeUnit> {
@Override
- public TimeUnit deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- ObjectCodec oc = p.getCodec();
- JsonNode node = oc.readTree(p);
- int v = node.asInt();
- TimeUnit result = new TimeUnit(v);
- return result;
+ public void visit(TopiaEntity entity, String propertyName, Class<?> collectionType, Class<?> type, Object value) {
+ JsonNode jsonValue = nodeEntity.get(propertyName);
+ try {
+ if (value != null) {
+ Collection c;
+ if (Set.class.isAssignableFrom(collectionType)) {
+ c = new HashSet();
+ } else {
+ c = new LinkedList();
+ }
+ for (JsonNode currentValue : jsonValue) {
+ Object v = readValue(type, currentValue);
+ c.add(v);
+ }
+ BeanUtils.setProperty(entity, propertyName, c);
+ }
+ } catch (Exception eee) {
+ throw new IsisFishRuntimeException(String.format("Can't set property '%s' from json value: '%s'", propertyName, jsonValue), eee);
+ }
}
- }
- private static class RangeOfValuesJsonDeserializer extends JsonDeserializer<RangeOfValues> {
@Override
- public RangeOfValues deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- ObjectCodec oc = p.getCodec();
- JsonNode node = oc.readTree(p);
- String v = node.asText();
- RangeOfValues result = new RangeOfValues(v);
- return result;
+ public void visit(TopiaEntity entity, String propertyName, Class<?> collectionType, Class<?> type, int index, Object value) {
+ throw new UnsupportedOperationException("FIXME a faire, implantation des properties array");
}
+
+ @Override
+ public void clear() {
+ }
}
+
+
+//
+// private static class MatrixNDJsonDeserializer extends JsonDeserializer<MatrixND> {
+//
+// protected RegionImportJson importer;
+//
+// public MatrixNDJsonDeserializer(final RegionImportJson importer) {
+// this.importer = importer;
+// }
+//
+// @Override
+// public MatrixND deserialize(JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
+// ObjectCodec oc = p.getCodec();
+// JsonNode node = oc.readTree(p);
+// String mat = node.asText();
+//
+// MatrixCSVHelper matrixCSVHelper = new MatrixCSVHelper(new EntitySemanticsDecorator(
+// new EntitySemanticsDecorator.EntityProvider() {
+// @Override
+// public Object findById(String id) {
+// Object result = importer.getEntity(id, ctxt);
+// return result;
+// }
+// }));
+//
+// MatrixND result = matrixCSVHelper.readMatrix(mat);
+// return result;
+// }
+//
+// }
+//
+// private static class TopiaEntityJsonDeserializer extends JsonDeserializer<TopiaEntity> {
+//
+// protected RegionImportJson importer;
+//
+// public TopiaEntityJsonDeserializer(RegionImportJson importer) {
+// this.importer = importer;
+// }
+//
+// @Override
+// public TopiaEntity deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+// ObjectCodec oc = p.getCodec();
+// JsonNode node = oc.readTree(p);
+// String id = node.asText();
+// TopiaEntity result = importer.getEntity(id, ctxt);
+// return result;
+// }
+//
+// }
+//
+// private static class MonthJsonDeserializer extends JsonDeserializer<Month> {
+// @Override
+// public Month deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+// ObjectCodec oc = p.getCodec();
+// JsonNode node = oc.readTree(p);
+// int m = node.asInt();
+// Month result = Month.MONTH[m];
+// return result;
+// }
+// }
+//
+// private static class TimeUnitJsonDeserializer extends JsonDeserializer<TimeUnit> {
+// @Override
+// public TimeUnit deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+// ObjectCodec oc = p.getCodec();
+// JsonNode node = oc.readTree(p);
+// int v = node.asInt();
+// TimeUnit result = new TimeUnit(v);
+// return result;
+// }
+// }
+//
+// private static class RangeOfValuesJsonDeserializer extends JsonDeserializer<RangeOfValues> {
+// @Override
+// public RangeOfValues deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+// ObjectCodec oc = p.getCodec();
+// JsonNode node = oc.readTree(p);
+// String v = node.asText();
+// RangeOfValues result = new RangeOfValues(v);
+// return result;
+// }
+// }
+
}
Modified: trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java 2016-11-04 15:05:55 UTC (rev 4369)
+++ trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java 2016-11-09 15:24:51 UTC (rev 4370)
@@ -440,12 +440,15 @@
new GZIPInputStream(new FileInputStream(file)))) {
RegionImportJson json = new RegionImportJson(new InputStreamReader(in, "UTF-8"),
new RegionImportJson.RegionMergeDatabase(tx));
- Collection<TopiaEntity> entities = json.getEntity();
+ Collection<TopiaEntity> entities = json.getEntities();
log.info("Entities to importe: " + entities.size());
for (TopiaEntity e : entities) {
tx.add(e);
}
tx.commitTransaction();
+ } catch (Exception eee) {
+ tx.rollbackTransaction();
+ throw eee;
}
}
} catch (Exception eee) {
1
0
r4369 - in trunk/src/main: java/fr/ifremer/isisfish/datastore java/fr/ifremer/isisfish/entities java/fr/ifremer/isisfish/ui/input java/fr/ifremer/isisfish/util resources/i18n
by bpoussin@users.forge.codelutin.com 04 Nov '16
by bpoussin@users.forge.codelutin.com 04 Nov '16
04 Nov '16
Author: bpoussin
Date: 2016-11-04 16:05:55 +0100 (Fri, 04 Nov 2016)
New Revision: 4369
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4369
Log:
debut d'implantation de l'evolution #8737: Export / Import des ?\195?\169l?\195?\169ments d'une r?\195?\169gion, soit pour import dans une autre r?\195?\169gion, soit pour fusion de deux r?\195?\169gions.
Added:
trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java
trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
trunk/src/main/java/fr/ifremer/isisfish/util/EntitySemanticsDecorator.java
trunk/src/main/java/fr/ifremer/isisfish/util/MatrixCSVHelper.java
Modified:
trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultMappedStorage.java
trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageAbstract.java
trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageCSV.java
trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java
trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputUI.jaxx
trunk/src/main/resources/i18n/isis-fish_en_GB.properties
trunk/src/main/resources/i18n/isis-fish_fr_FR.properties
Modified: trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultMappedStorage.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultMappedStorage.java 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultMappedStorage.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -26,6 +26,7 @@
package fr.ifremer.isisfish.datastore;
+import fr.ifremer.isisfish.util.EntitySemanticsDecorator;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
@@ -292,7 +293,9 @@
public MatrixND getMatrix(TopiaContext tx) {
// on met la matrice dans un decorateur pour convertir automatiquement les semantiques
- MatrixND result = new MatrixSemanticsDecorator(matrix, new EntitySemanticsDecorator(tx));
+ MatrixND result = new MatrixSemanticsDecorator(matrix,
+ new EntitySemanticsDecorator(
+ new EntitySemanticsDecorator.EntityTxProvider(tx)));
return result;
}
}
Modified: trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageAbstract.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageAbstract.java 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageAbstract.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -25,6 +25,8 @@
package fr.ifremer.isisfish.datastore;
+import fr.ifremer.isisfish.util.EntitySemanticsDecorator;
+
import static org.nuiton.i18n.I18n.t;
import java.util.ArrayList;
@@ -33,18 +35,13 @@
import java.util.Map;
import java.util.Set;
-import org.apache.commons.collections4.BidiMap;
-import org.apache.commons.collections4.bidimap.DualHashBidiMap;
-import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixIterator;
import org.nuiton.math.matrix.MatrixND;
import org.nuiton.math.matrix.MatrixSemanticsDecorator;
-import org.nuiton.math.matrix.SemanticsDecorator;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.util.ArrayUtil;
import org.nuiton.util.HashList;
@@ -62,7 +59,6 @@
import fr.ifremer.isisfish.simulator.SimulationPlan;
import fr.ifremer.isisfish.simulator.SimulationResultGetter;
import fr.ifremer.isisfish.simulator.SimulationResultListener;
-import fr.ifremer.isisfish.types.Month;
import fr.ifremer.isisfish.types.TimeStep;
import java.util.LinkedHashMap;
import org.nuiton.math.matrix.MatrixFactory;
@@ -92,87 +88,7 @@
/** result enabled */
transient protected Set<String> enabledResult = null;
- /**
- * Convertie une entite, month, timestep en string et inversement.
- * Entity = "TopiaId:Entity.toString"
- */
- static protected class EntitySemanticsDecorator implements SemanticsDecorator<Object, String> {
- static final private String SEP = ":";
- protected TopiaContext tx;
- /** en cle les representation interne (get) en valeur les valeurs decoree (getKey) */
- protected BidiMap<String, Object> cache = new DualHashBidiMap<>();
-
- public EntitySemanticsDecorator() {
- }
-
- public EntitySemanticsDecorator(TopiaContext tx) {
- this.tx = tx;
- }
-
- @Override
- public Object decorate(String internalValue) {
- Object result = cache.get(internalValue);
- if (result == null && internalValue != null) {
- // on retrouve souvent les memes semantiques dans les matrices
- // pour minimiser les chaines en memoire, on prend la representation
- // interne avant de l'utiliser comme cle.
- internalValue = internalValue.intern();
- result = internalValue;
- if (StringUtils.startsWith(internalValue, "Month")) {
- String val = StringUtils.substringAfter(internalValue, SEP);
- int monthNumber = Integer.parseInt(val);
- result = Month.MONTH[monthNumber];
- } else if (StringUtils.startsWith(internalValue, "TimeStep")) {
- String val = StringUtils.substringAfter(internalValue, SEP);
- int stepNumber = Integer.parseInt(val);
- result = new TimeStep(stepNumber);
- } else if (StringUtils.startsWith(internalValue, "fr.ifremer.isisfish.entities.")) {
- if (tx == null) {
- result = StringUtils.substringAfter(internalValue, SEP);
- } else {
- try {
- String id = StringUtils.substringBefore(internalValue, SEP);
- result = tx.findByTopiaId(id);
- } catch (TopiaException eee) {
- log.info("Fallback use string representation because"
- + " i can't decorate (String->Entity): "
- + internalValue, eee);
- // si on arrive pas a convertir cette fois-ci, on
- // renvoi internalValue pour que le undecorate est toutes les infos
- // et donc que la prochaine fois on y arrive peut etre
- }
- }
- }
- cache.put(internalValue, result);
- }
- return result;
- }
-
- @Override
- public String undecorate(Object decoratedValue) {
- String result = cache.getKey(decoratedValue);
- if (result == null && decoratedValue != null) {
- if (decoratedValue instanceof Month) {
- result = "Month" + SEP + ((Month)decoratedValue).getMonthNumber();
- } else if (decoratedValue instanceof TimeStep) {
- result = "TimeStep" + SEP + ((TimeStep)decoratedValue).getStep();
- } else if (decoratedValue instanceof TopiaEntity) {
- result = ((TopiaEntity)decoratedValue).getTopiaId() + SEP + decoratedValue;
- } else {
- result = String.valueOf(decoratedValue);
- }
- // on retrouve souvent les memes semantiques dans les matrices
- // pour minimiser les chaines en memoire, on prend la representation
- // interne avant de l'utiliser comme cle.
- result = result.intern();
- cache.put(result, decoratedValue);
- }
- return result;
- }
-
- }
-
/**
* Return one result for step and name. Matrix returned must be undecorated
* (semantics must be string representation of object)
@@ -245,7 +161,9 @@
// on decore la matrice resultat au dernier moment, tous les calcules
// ce font avec les strings
tx = getTx(tx);
- result = new MatrixSemanticsDecorator(mat, new EntitySemanticsDecorator(tx));
+ result = new MatrixSemanticsDecorator(mat,
+ new EntitySemanticsDecorator(
+ new EntitySemanticsDecorator.EntityTxProvider(tx)));
}
return result;
}
Modified: trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageCSV.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageCSV.java 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/java/fr/ifremer/isisfish/datastore/ResultStorageCSV.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -29,17 +29,15 @@
import fr.ifremer.isisfish.simulator.SimulationContext;
import fr.ifremer.isisfish.simulator.SimulationControl;
import fr.ifremer.isisfish.types.TimeStep;
-import fr.ifremer.isisfish.util.SimpleParser;
-import java.io.BufferedWriter;
+import fr.ifremer.isisfish.util.MatrixCSVHelper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
-import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.util.ArrayList;
+import java.io.Reader;
+import java.io.Writer;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@@ -55,7 +53,6 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.math.matrix.MatrixIterator;
import org.nuiton.math.matrix.MatrixND;
import org.nuiton.util.StringUtil;
@@ -132,6 +129,8 @@
*/
protected int maxGapWithCurrentStepReadOnDisk = 0;
+ protected MatrixCSVHelper matrixCSVHelper;
+
LinkedHashMap<TimeStep, Map<String, MatrixND>> cache =
new LinkedHashMap<TimeStep, Map<String, MatrixND>>() {
private static final long serialVersionUID = 1L;
@@ -146,8 +145,17 @@
storeOnDiskStep = IsisFish.config.getSimulationStoreResultOnDisk();
cacheStep = IsisFish.config.getSimulationStoreResultCacheStep();
+
}
+ protected MatrixCSVHelper getMatrixCSVHelper() {
+ if (matrixCSVHelper == null) {
+ matrixCSVHelper = new MatrixCSVHelper(decorator);
+ }
+ return matrixCSVHelper;
+ }
+
+
@Override
public String getInfo() {
String oldest = "";
@@ -222,51 +230,13 @@
protected MatrixND readMatrix(String file) throws IOException {
MatrixND result = null;
- LineNumberReader in = null;
+ Reader in = null;
try {
- in = new LineNumberReader(new InputStreamReader(
- new GZIPInputStream(new FileInputStream(file)), IsisConfig.charset));
+ in = new InputStreamReader(
+ new GZIPInputStream(new FileInputStream(file)), IsisConfig.charset);
- SimpleParser sp = new SimpleParser(in, true);
+ result = getMatrixCSVHelper().readMatrix(in);
- // lecture du nom de la matrice
- String name = sp.readString('\n');
-
-
- // lecture du nom des dimensions et des semantics
- List<String> dimNames = new ArrayList<String>();
- List<List<String>> semantics = new ArrayList<List<String>>();
-
- String dimName = sp.readString(':');
- while (!sp.isEOL() || StringUtils.isNotBlank(dimName)) {
- dimNames.add(dimName);
- List<String> sems = new ArrayList<String>();
- semantics.add(sems);
- while (!sp.isEOL()) {
- String sem = sp.readString(';');
- sems.add(sem);
- }
- dimName = sp.readString(':');
- }
-
- // creation de la matrice resultat avec les infos collectes
- result = getMatrixFactory().create(name,
- semantics.toArray(new List[semantics.size()]),
- dimNames.toArray(new String[dimNames.size()]));
-
-
- // lecture des data
- int nbDim = dimNames.size();
- int[] coord = new int[nbDim];
-
- while (!sp.isEOF()) {
- for (int i=0; i<nbDim; i++) {
- coord[i] = sp.readInt(';');
- }
- double v = sp.readDouble(';');
- result.setValue(coord, v);
- }
-
} finally {
IOUtils.closeQuietly(in);
}
@@ -382,47 +352,16 @@
File file = getMatrixFile(step, name);
file.getParentFile().mkdirs();
- PrintWriter out = null;
+ Writer out = null;
CountingOutputStream counter = null;
try {
- out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
+ out = new OutputStreamWriter(
new GZIPOutputStream(counter = new CountingOutputStream(new FileOutputStream(file))),
IsisConfig.charset
- )));
+ );
- out.print(name);
- out.println();
+ getMatrixCSVHelper().writeMatrix(out, name, mat);
- List[] sems = mat.getSemantics();
- for (int i=0, maxi=sems.length; i<maxi; i++) {
- String dimName = mat.getDimensionName(i);
- out.print(dimName);
-
- List l = sems[i];
- char sep = ':';
- for (Object o : l) {
- out.print(sep);
- out.print(o);
- sep = ';';
- }
- out.println();
- }
-
- // blank line to separate header and data
- out.println();
-
- for (MatrixIterator i = mat.iteratorNotZero(); i.hasNext();) {
- i.next();
- int[] pos = i.getCoordinates();
- double value = i.getValue();
- for (int p : pos) {
- out.print(p);
- out.print(';');
- }
- out.print(value);
- out.println();
- }
-
// result file is writen without error, add it to fileExistCache
addFileExist(file);
} catch (Exception eee) {
Added: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java (rev 0)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -0,0 +1,396 @@
+package fr.ifremer.isisfish.entities;
+
+
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import fr.ifremer.isisfish.IsisConfig;
+import fr.ifremer.isisfish.types.Month;
+import fr.ifremer.isisfish.types.RangeOfValues;
+import fr.ifremer.isisfish.types.TimeUnit;
+import fr.ifremer.isisfish.util.EntitySemanticsDecorator;
+import fr.ifremer.isisfish.util.MatrixCSVHelper;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaEntity;
+
+/**
+ * Classe permettant d'exporter en Json une region
+ *
+ * Format du JSON:
+ *
+ * {
+ * "#info": {
+ * "formatVersion": int
+ * "isisVersion": String
+ * "region": boolean if true contains one region, if false contains one Entity
+ * "root": toString representation of root entity
+ * "rootId": id of root entity
+ * },
+ * "#entities": {
+ * " <id>": {<entity field>},
+ * ...
+ * },
+ * "FisheryRegion" : [<id>],
+ * "Cell": [<id>, ...],
+ * "Zone": [<id>, ...],
+ * ...
+ * }
+ *
+ * @author poussin
+ * @version $Revision$
+ *
+ * Last update: $Date$
+ * by : $Author$
+ */
+public class RegionExportJson implements EntityVisitor {
+
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private Log log = LogFactory.getLog(RegionExportJson.class);
+
+ final static public int FORMAT_VERSION = 1;
+
+ protected LinkedList<TopiaEntity> toVisit;
+ protected Set<String> visited;
+ protected LinkedHashMap<String, List<String>> isisEntities;
+ protected boolean doVisit = false;
+ protected MatrixCSVHelper matrixCSVHelper;
+ protected EntitySemanticsDecorator decorator;
+ protected JsonGenerator g;
+
+ public RegionExportJson(Writer w) {
+ try {
+ JsonFactory f = new JsonFactory();
+ g = f.createGenerator(w);
+
+ toVisit = new LinkedList<TopiaEntity>();
+ visited = new HashSet<String>();
+ matrixCSVHelper = new MatrixCSVHelper(
+ decorator = new EntitySemanticsDecorator());
+
+ isisEntities = new LinkedHashMap<String, List<String>>();
+ isisEntities.put("FisheryRegion", new ArrayList<String>());
+ isisEntities.put("Cell", new ArrayList<String>());
+ isisEntities.put("Zone", new ArrayList<String>());
+ isisEntities.put("Port", new ArrayList<String>());
+ isisEntities.put("Species", new ArrayList<String>());
+ isisEntities.put("Population", new ArrayList<String>());
+ isisEntities.put("Gear", new ArrayList<String>());
+ isisEntities.put("Metier", new ArrayList<String>());
+ isisEntities.put("TripType", new ArrayList<String>());
+ isisEntities.put("VesselType", new ArrayList<String>());
+ isisEntities.put("SetOfVessels", new ArrayList<String>());
+ isisEntities.put("Strategy", new ArrayList<String>());
+ isisEntities.put("Observation", new ArrayList<String>());
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Export la region et tous les elements de la region.
+ * @param fisheryRegion
+ */
+ public void export(FisheryRegion fisheryRegion) {
+ toVisit.addAll(fisheryRegion.getCell());
+ toVisit.addAll(fisheryRegion.getZone());
+ toVisit.addAll(fisheryRegion.getPort());
+ toVisit.addAll(fisheryRegion.getSpecies());
+ toVisit.addAll(fisheryRegion.getGear());
+ toVisit.addAll(fisheryRegion.getMetier());
+ toVisit.addAll(fisheryRegion.getTripType());
+ toVisit.addAll(fisheryRegion.getVesselType()) ;
+ toVisit.addAll(fisheryRegion.getSetOfVessels());
+ toVisit.addAll(fisheryRegion.getStrategy());
+ toVisit.addAll(fisheryRegion.getObservations());
+
+ export(fisheryRegion, true);
+ }
+
+ /**
+ * Export seulement l'entity et ses dépendances.
+ * @param entity
+ */
+ public void export(TopiaEntity entity) {
+ if (entity instanceof FisheryRegion) {
+ export((FisheryRegion)entity);
+ } else {
+ export(entity, false);
+ }
+ }
+
+ protected void export(TopiaEntity entity, boolean isRegion) {
+ try {
+ this.start();
+ g.writeObjectFieldStart("#info");
+ g.writeNumberField("formatVersion", FORMAT_VERSION);
+ g.writeStringField("isisVersion", IsisConfig.getVersion());
+ g.writeBooleanField("region", isRegion);
+ g.writeStringField("root", entity.toString());
+ g.writeStringField("rootId", entity.getTopiaId());
+ g.writeEndObject();
+
+ g.writeObjectFieldStart("#entities");
+
+ toVisit.push(entity);
+
+ TopiaEntity e;
+ while(toVisit.peek() != null) {
+ while((e = toVisit.poll()) != null) {
+ e.accept(this);
+ }
+
+ // add all TopiaEntity in matrix semantics
+ Collection<Object> decoratedObject = decorator.getDecoratedObject();
+ for (Object o : decoratedObject) {
+ if (o instanceof TopiaEntity && !visited.contains(((TopiaEntity)o).getTopiaId())) {
+ toVisit.add((TopiaEntity)o);
+ }
+ }
+ }
+
+ g.writeEndObject();
+ this.end();
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ protected void writeValue(Class<?> type, Object value) {
+ try {
+ if (value == null) {
+ g.writeNull();
+ } else if (TopiaEntity.class.isAssignableFrom(type)) {
+ g.writeString(((TopiaEntity)value).getTopiaId());
+ toVisit.add((TopiaEntity)value);
+ } else if (MatrixND.class.isAssignableFrom(type)) {
+ MatrixND m = (MatrixND)value;
+ String s = matrixCSVHelper.writeMatrix(m.getName(), m);
+ g.writeString(s);
+ } else if (TimeUnit.class.isAssignableFrom(type)) {
+ g.writeNumber(((TimeUnit)value).getTime());
+ } else if (RangeOfValues.class.isAssignableFrom(type)) {
+ g.writeString(((RangeOfValues)value).getAsString());
+ } else if (Month.class.isAssignableFrom(type)) {
+ g.writeNumber(((Month)value).getMonthNumber());
+ } else if (Number.class.isAssignableFrom(type) || value instanceof Number) {
+ g.writeNumber(((Number)value).doubleValue());
+ } else if (String.class.isAssignableFrom(type)) {
+ g.writeString(((String)value));
+ } else if (Boolean.class.isAssignableFrom(type) || value instanceof Boolean) {
+ g.writeBoolean(((Boolean)value));
+ } else if (Class.class.isAssignableFrom(type)) {
+ g.writeString(((Class)value).getName());
+ } else {
+ String message = String.format("Unsupported type: '%s' value class '%s' value '%s'", type, value.getClass().getName(), value);
+ log.error(message);
+ g.writeString(message);
+// throw new RuntimeException(message);
+ }
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ public void start() {
+ try {
+ g.writeStartObject();
+ ObjectMapper m = new ObjectMapper();
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ public void end() {
+ try {
+ for (Map.Entry<String, List<String>> e : isisEntities.entrySet()) {
+ g.writeArrayFieldStart(e.getKey());
+ for (String id : e.getValue()) {
+ g.writeString(id);
+ }
+ g.writeEndArray();
+ }
+ g.writeEndObject();
+ g.close();
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Start the visit of the given entity.
+ *
+ * @param entity the visited entity
+ */
+ @Override
+ public void start(TopiaEntity entity) {
+ try {
+ String id = entity.getTopiaId();
+ doVisit = !visited.contains(id);
+ if (doVisit) {
+ visited.add(id);
+ g.writeObjectFieldStart(id);
+ String className = entity.getClass().getName();
+ String name = StringUtils.removeEnd(entity.getClass().getSimpleName(), "Impl");
+ List<String> list = isisEntities.get(name);
+ if (list != null) {
+ list.add(id);
+ }
+
+ g.writeStringField("#class", className);
+ g.writeStringField("#id", id);
+ g.writeStringField("#toString", entity.toString());
+ }
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Ends the visit of the given entity.
+ *
+ * @param entity the visited entity
+ */
+ @Override
+ public void end(TopiaEntity entity) {
+ try {
+ if (doVisit) {
+ g.writeEndObject();
+ }
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Visit a none indexed property for the given entity.
+ *
+ * The property visited is defined by the other parameters.
+ *
+ * @param entity the visited entity
+ * @param propertyName the name of the visited property
+ * @param type the type of the visited property
+ * @param value the value of the visited property
+ */
+ @Override
+ public void visit(TopiaEntity entity, String propertyName, Class<?> type, Object value) {
+ try {
+ if (doVisit) {
+ g.writeFieldName(propertyName);
+ writeValue(type, value);
+ }
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Visit a collection property for the given entity.
+ *
+ * The property visited is defined by the other parameters.
+ *
+ * @param entity the visited entity
+ * @param propertyName the name of the visited property
+ * @param collectionType the type of the visited collection
+ * @param type the type of the visited property
+ * @param value the value of the visited property
+ */
+ @Override
+ public void visit(TopiaEntity entity, String propertyName,
+ Class<?> collectionType, Class<?> type, Object value) {
+ try {
+ if (doVisit) {
+ g.writeFieldName(propertyName);
+ g.writeStartArray();
+ if (value != null) {
+ for (Object currentValue : (Collection<?>)value) {
+ writeValue(type, currentValue);
+ }
+ }
+ g.writeEndArray();
+ }
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Visit a indexed value from a collection property for the given entity.
+ *
+ * The property visited is defined by the other parameters.
+ *
+ * @param entity the visited entity
+ * @param propertyName the name of the visited property
+ * @param collectionType the type of the container of the visited property
+ * @param type the type of the visited property
+ * @param index the index of the visited property in his container
+ * @param value the value of the visited property
+ */
+ @Override
+ public void visit(TopiaEntity entity, String propertyName,
+ Class<?> collectionType, Class<?> type, int index, Object value) {
+ if (doVisit) {
+ throw new UnsupportedOperationException("FIXME a faire, implantation des properties array");
+ }
+ }
+
+ /**
+ * Reset all states of the visitor.
+ *
+ * If you use internal states inside the visitor, this method should clean
+ * all of them.
+ *
+ * This method should be invoked after usage of the visitor.
+ */
+ @Override
+ public void clear() {
+ toVisit = null;
+ visited = null;
+ isisEntities = null;
+ matrixCSVHelper = null;
+ decorator = null;
+ }
+
+
+// abstract public void visit(Cell v);
+// abstract public void visit(EffortDescription v);
+// abstract public void visit(FisheryRegion region);
+// abstract public void visit(Gear v);
+// abstract public void visit(Metier v);
+// abstract public void visit(MetierSeasonInfo v);
+// abstract public void visit(PopulationGroup v);
+// abstract public void visit(Population v);
+// abstract public void visit(PopulationSeasonInfo v);
+// abstract public void visit(Port v);
+// abstract public void visit(Season v);
+// abstract public void visit(Selectivity v);
+// abstract public void visit(SetOfVessels v);
+// abstract public void visit(Species v);
+// abstract public void visit(Strategy v);
+// abstract public void visit(StrategyMonthInfo v);
+// abstract public void visit(TargetSpecies v);
+// abstract public void visit(TripType v);
+// abstract public void visit(Variable v);
+// abstract public void visit(VariableType v);
+// abstract public void visit(VesselType v);
+// abstract public void visit(Zone v);
+// abstract public void visit(Equation v);
+// abstract public void visit(MatrixND v);
+// abstract public void visit(String v);
+// abstract public void visit(int v);
+// abstract public void visit(float v);
+
+}
Property changes on: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionExportJson.java
___________________________________________________________________
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision HeadURL
\ No newline at end of property
Added: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java (rev 0)
+++ trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -0,0 +1,428 @@
+package fr.ifremer.isisfish.entities;
+
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.ObjectCodec;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import fr.ifremer.isisfish.IsisFishDAOHelper;
+import fr.ifremer.isisfish.types.Month;
+import fr.ifremer.isisfish.types.RangeOfValues;
+import fr.ifremer.isisfish.types.TimeUnit;
+import fr.ifremer.isisfish.util.EntitySemanticsDecorator;
+import fr.ifremer.isisfish.util.MatrixCSVHelper;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.Map.Entry;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixND;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.persistence.TopiaEntity;
+
+/**
+ * Classe permettant d'importer des données dans une region a partir d'un
+ * export Json.
+ * L'import se fait le plus possible de façon automatique, s'il y a des
+ * choix a faire durant la fusion, les questions sont posées au travers de
+ * l'objet passé en paramètre
+ *
+ * @author poussin
+ * @version $Revision$
+ *
+ * Last update: $Date$
+ * by : $Author$
+ */
+public class RegionImportJson {
+
+ static public interface RegionMerge {
+ public TopiaEntity choice(TopiaEntity e);
+ }
+
+ static public class RegionMergeDatabase implements RegionMerge {
+ protected TopiaContext tx;
+
+ public RegionMergeDatabase(TopiaContext tx) {
+ this.tx = tx;
+ }
+
+ @Override
+ public TopiaEntity choice(TopiaEntity e) {
+ TopiaEntity result;
+
+ if (e instanceof FisheryRegion) {
+ result = choice((FisheryRegion)e);
+ } else if (e instanceof Cell) {
+ result = choice((Cell)e);
+ } else if (e instanceof Zone) {
+ result = choice((Zone)e);
+ } else if (e instanceof Port) {
+ result = choice((Port)e);
+ } else if (e instanceof Species) {
+ result = choice((Species)e);
+ } else if (e instanceof Population) {
+ result = choice((Population)e);
+ } else if (e instanceof Gear) {
+ result = choice((Gear)e);
+ } else if (e instanceof Metier) {
+ result = choice((Metier)e);
+ } else if (e instanceof TripType) {
+ result = choice((TripType)e);
+ } else if (e instanceof VesselType) {
+ result = choice((VesselType)e);
+ } else if (e instanceof SetOfVessels) {
+ result = choice((SetOfVessels)e);
+ } else if (e instanceof Strategy) {
+ result = choice((Strategy)e);
+ } else if (e instanceof Observation) {
+ result = choice((Observation)e);
+ } else {
+ log.info("Not supported entity type: " + e.getClass().getSimpleName());
+ result = genericChoice(e);
+ }
+
+ return result;
+ }
+
+ protected TopiaEntity ask(TopiaEntity e, Collection<TopiaEntity> possible) {
+ System.out.println("Choice between:" + e + " and " + possible);
+ return e; // FIXME
+ }
+
+ protected TopiaEntity genericChoice(TopiaEntity e) {
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(tx.findByTopiaId(e.getTopiaId()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(FisheryRegion e) {
+ FisheryRegionDAO dao = IsisFishDAOHelper.getFisheryRegionDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Cell e) {
+ CellDAO dao = IsisFishDAOHelper.getCellDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Zone e) {
+ ZoneDAO dao = IsisFishDAOHelper.getZoneDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Port e) {
+ PortDAO dao = IsisFishDAOHelper.getPortDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Species e) {
+ SpeciesDAO dao = IsisFishDAOHelper.getSpeciesDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Population e) {
+ PopulationDAO dao = IsisFishDAOHelper.getPopulationDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Gear e) {
+ GearDAO dao = IsisFishDAOHelper.getGearDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Metier e) {
+ MetierDAO dao = IsisFishDAOHelper.getMetierDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(TripType e) {
+ TripTypeDAO dao = IsisFishDAOHelper.getTripTypeDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(VesselType e) {
+ VesselTypeDAO dao = IsisFishDAOHelper.getVesselTypeDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(SetOfVessels e) {
+ SetOfVesselsDAO dao = IsisFishDAOHelper.getSetOfVesselsDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Strategy e) {
+ StrategyDAO dao = IsisFishDAOHelper.getStrategyDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+
+ protected TopiaEntity choice(Observation e) {
+ ObservationDAO dao = IsisFishDAOHelper.getObservationDAO(tx);
+ LinkedHashSet<TopiaEntity> possible = new LinkedHashSet<TopiaEntity>();
+
+ possible.add(dao.findByTopiaId(e.getTopiaId()));
+ possible.addAll(dao.findAllByName(e.getName()));
+
+ TopiaEntity result = ask(e, possible);
+ return result;
+ }
+ }
+
+ static public class RegionMergeNoMerge implements RegionMerge {
+ @Override
+ public TopiaEntity choice(TopiaEntity e) {
+ return e;
+ }
+ }
+
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private Log log = LogFactory.getLog(RegionImportJson.class);
+
+ protected RegionMerge merge;
+ protected JsonNode json;
+ protected LinkedHashMap<String, TopiaEntity> entities;
+ protected JsonNode jsonEntities;
+ protected ObjectMapper mapper;
+
+ /**
+ *
+ * @param r reader contains json
+ * @param merge use to choice entity in Json or entity in current region
+ */
+ public RegionImportJson(Reader r, RegionMerge merge) {
+ try {
+ this.merge = merge != null ? merge : new RegionMergeNoMerge();
+ entities = new LinkedHashMap<String, TopiaEntity>();
+
+ mapper = new ObjectMapper();
+ SimpleModule isisModule = new SimpleModule("IsisModule")
+ .addDeserializer(Month.class, new MonthJsonDeserializer())
+ .addDeserializer(TimeUnit.class, new TimeUnitJsonDeserializer())
+ .addDeserializer(RangeOfValues.class, new RangeOfValuesJsonDeserializer())
+ .addDeserializer(MatrixND.class, new MatrixNDJsonDeserializer(this))
+ .addDeserializer(TopiaEntity.class, new TopiaEntityJsonDeserializer(this));
+ mapper.registerModule(isisModule);
+
+ ObjectMapper m = new ObjectMapper();
+ json = m.readTree(r);
+ jsonEntities = json.get("#entities");
+ } catch (IOException eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Return all entities available in Json reader
+ * @return
+ */
+ public Collection<TopiaEntity> getEntity() {
+ try {
+ JsonNode info = json.with("#info");
+ boolean isRegion = info.get("region").asBoolean(false);
+ if (!isRegion) {
+ // il n'y a qu'un objet dans le json, on le deserialize
+ String rootId = info.get("rootId").asText();
+ getEntity(rootId);
+ } else {
+ // il y a toute une region, on lit les listes d'id des objets
+ // principaux (cell, zone, port, ...)
+ for (Iterator<Entry<String, JsonNode>> i = json.fields(); i.hasNext();) {
+ Entry<String, JsonNode> field = i.next();
+ // les champs commencant par des # sont #info et #entities
+ if (!field.getKey().startsWith("#")) {
+ for (JsonNode id : field.getValue()) {
+ getEntity(id.asText());
+ }
+ }
+ }
+ }
+
+ return entities.values();
+ } catch (Exception eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ /**
+ * Return entity with given id. If not already converted, convert it and
+ * add it in global entities converted pool
+ * @param id
+ * @return
+ */
+ public TopiaEntity getEntity(String id) {
+ try {
+ TopiaEntity result = entities.get(id);
+ if (result == null) {
+ JsonNode node = jsonEntities.get(id);
+ Class clazz = Class.forName(node.get("#class").asText());
+ TopiaEntity o = (TopiaEntity)mapper.convertValue(node, clazz);
+ o = merge.choice(o);
+ entities.put(id, o);
+ }
+ return result;
+ } catch (Exception eee) {
+ throw new RuntimeException(eee);
+ }
+ }
+
+ private static class MatrixNDJsonDeserializer extends JsonDeserializer<MatrixND> {
+
+ protected MatrixCSVHelper matrixCSVHelper;
+
+ public MatrixNDJsonDeserializer(final RegionImportJson importer) {
+ matrixCSVHelper = new MatrixCSVHelper(new EntitySemanticsDecorator(
+ new EntitySemanticsDecorator.EntityProvider() {
+ @Override
+ public Object findById(String id) {
+ Object result = importer.getEntity(id);
+ return result;
+ }
+ }));
+ }
+
+ @Override
+ public MatrixND deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+ ObjectCodec oc = p.getCodec();
+ JsonNode node = oc.readTree(p);
+ String mat = node.asText();
+ MatrixND result = matrixCSVHelper.readMatrix(mat);
+ return result;
+ }
+
+ }
+
+ private static class TopiaEntityJsonDeserializer extends JsonDeserializer<TopiaEntity> {
+
+ protected RegionImportJson importer;
+
+ public TopiaEntityJsonDeserializer(RegionImportJson importer) {
+ this.importer = importer;
+ }
+
+ @Override
+ public TopiaEntity deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+ ObjectCodec oc = p.getCodec();
+ JsonNode node = oc.readTree(p);
+ String id = node.asText();
+ TopiaEntity result = importer.getEntity(id);
+ return result;
+ }
+
+ }
+
+ private static class MonthJsonDeserializer extends JsonDeserializer<Month> {
+ @Override
+ public Month deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+ ObjectCodec oc = p.getCodec();
+ JsonNode node = oc.readTree(p);
+ int m = node.asInt();
+ Month result = Month.MONTH[m];
+ return result;
+ }
+ }
+
+ private static class TimeUnitJsonDeserializer extends JsonDeserializer<TimeUnit> {
+ @Override
+ public TimeUnit deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+ ObjectCodec oc = p.getCodec();
+ JsonNode node = oc.readTree(p);
+ int v = node.asInt();
+ TimeUnit result = new TimeUnit(v);
+ return result;
+ }
+ }
+
+ private static class RangeOfValuesJsonDeserializer extends JsonDeserializer<RangeOfValues> {
+ @Override
+ public RangeOfValues deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
+ ObjectCodec oc = p.getCodec();
+ JsonNode node = oc.readTree(p);
+ String v = node.asText();
+ RangeOfValues result = new RangeOfValues(v);
+ return result;
+ }
+ }
+
+}
Property changes on: trunk/src/main/java/fr/ifremer/isisfish/entities/RegionImportJson.java
___________________________________________________________________
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision HeadURL
\ No newline at end of property
Modified: trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputHandler.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -23,6 +23,9 @@
package fr.ifremer.isisfish.ui.input;
+
+import cern.colt.Arrays;
+
import static org.nuiton.i18n.I18n.n;
import static org.nuiton.i18n.I18n.t;
@@ -57,6 +60,8 @@
import fr.ifremer.isisfish.datastore.StorageException;
import fr.ifremer.isisfish.entities.FisheryRegion;
import fr.ifremer.isisfish.entities.Population;
+import fr.ifremer.isisfish.entities.RegionExportJson;
+import fr.ifremer.isisfish.entities.RegionImportJson;
import fr.ifremer.isisfish.entities.Species;
import fr.ifremer.isisfish.entities.SpeciesDAO;
import fr.ifremer.isisfish.mexico.export.RegionExplorer;
@@ -71,6 +76,19 @@
import fr.ifremer.isisfish.ui.input.tree.loadors.PopulationsNodeLoador;
import fr.ifremer.isisfish.ui.models.common.GenericComboModel;
import fr.ifremer.isisfish.vcs.VCSException;
+import java.awt.Component;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.util.Collection;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+import org.nuiton.topia.persistence.TopiaEntity;
/**
* Main handler for fishery edition action.
@@ -362,6 +380,81 @@
}
}
+ /**
+ * Exporter une entite json gzip
+ */
+ protected void exportJson(TopiaEntity e) {
+ try {
+ File file = FileUtil.getFile(".*.isonz$",
+ t("isisfish.message.import.region.zipped"));
+
+ if (file != null) {
+ // add .isonz extension is not set
+ if (!file.getAbsolutePath().endsWith(".isonz")) {
+ file = new File(file.getAbsolutePath() + ".isonz");
+ }
+
+ int resp = JOptionPane.YES_OPTION;
+ if (file.exists()) {
+ resp = JOptionPane.showConfirmDialog(inputUI,
+ t("isisfish.message.file.overwrite"));
+ }
+ if (resp == JOptionPane.YES_OPTION) {
+ try (OutputStream out = new BufferedOutputStream(
+ new GZIPOutputStream(new FileOutputStream(file)))) {
+ RegionExportJson json = new RegionExportJson(new OutputStreamWriter(out, "UTF-8"));
+ json.export(e);
+ }
+ }
+ }
+ } catch (Exception eee) {
+ throw new IsisFishRuntimeException("Can't export region", eee);
+ }
+ }
+
+ public void exportEntityJson() {
+ Component[] cs = inputUI.getInputPane().getComponents();
+ if (cs != null && cs.length == 1 && cs[0] instanceof InputContentUI) {
+ InputContentUI inputContentUI = (InputContentUI)cs[0];
+ TopiaEntityContextable e = inputContentUI.getBean();
+ if (e != null) {
+ log.info("try to export json version of: " + e);
+ exportJson(e);
+ } else {
+ log.error("Can't find entity in : " + inputContentUI);
+ }
+ } else {
+ log.error("Can't find InputContentUI in : " + Arrays.toString(cs));
+ }
+ }
+
+ public void importEntityJson() {
+ setStatusMessage(inputUI, t("isisfish.message.import.zip"), true);
+ try {
+ File file = FileUtil.getFile(".*\\.isonz$",
+ t("isisfish.message.import.region.zipped"));
+ if (file != null) {
+ FisheryRegion fisheryRegion = inputUI.getContextValue(FisheryRegion.class);
+ TopiaContext tx = fisheryRegion.getTopiaContext();
+ try (InputStream in = new BufferedInputStream(
+ new GZIPInputStream(new FileInputStream(file)))) {
+ RegionImportJson json = new RegionImportJson(new InputStreamReader(in, "UTF-8"),
+ new RegionImportJson.RegionMergeDatabase(tx));
+ Collection<TopiaEntity> entities = json.getEntity();
+ log.info("Entities to importe: " + entities.size());
+ for (TopiaEntity e : entities) {
+ tx.add(e);
+ }
+ tx.commitTransaction();
+ }
+ }
+ } catch (Exception eee) {
+ throw new IsisFishRuntimeException("Can't import region", eee);
+ }
+
+ setStatusMessage(inputUI, t("isisfish.message.import.finished"));
+ }
+
/**
* Remove region.
*
Modified: trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputUI.jaxx
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputUI.jaxx 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/java/fr/ifremer/isisfish/ui/input/InputUI.jaxx 2016-11-04 15:05:55 UTC (rev 4369)
@@ -40,6 +40,8 @@
<JMenuItem id="menuRegionImportRename" text="isisfish.input.menu.importRenameRegion" onActionPerformed="handler.importRegionAndRename()" />
<JMenuItem text="isisfish.input.menu.importRegionSimulation" onActionPerformed="handler.importRegionFromSimulation()" enabled="false"/>
<JMenuItem id="menuRegionExport" text="isisfish.input.menu.exportRegion" enabled='{isRegionLoaded()}' onActionPerformed="handler.exportRegion()" />
+ <JMenuItem id="menuExportJson" text="isisfish.input.menu.exportJson" enabled='{isRegionLoaded()}' onActionPerformed="handler.exportEntityJson()" />
+ <JMenuItem id="menuImportJson" text="isisfish.input.menu.importJson" enabled='{isRegionLoaded()}' onActionPerformed="handler.importEntityJson()" />
<JMenuItem id="menuRegionCopy" text="isisfish.input.menu.copyRegion" enabled='{isRegionLoaded()}' onActionPerformed="handler.copyRegion()" />
<JSeparator/>
<JMenuItem text="isisfish.input.menu.removeLocaly" enabled='{isRegionLoaded()}' onActionPerformed="handler.removeRegion(false)" />
Added: trunk/src/main/java/fr/ifremer/isisfish/util/EntitySemanticsDecorator.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/util/EntitySemanticsDecorator.java (rev 0)
+++ trunk/src/main/java/fr/ifremer/isisfish/util/EntitySemanticsDecorator.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -0,0 +1,151 @@
+package fr.ifremer.isisfish.util;
+
+
+import fr.ifremer.isisfish.IsisFishRuntimeException;
+import fr.ifremer.isisfish.types.Month;
+import fr.ifremer.isisfish.types.TimeStep;
+import java.util.Collection;
+import java.util.Map;
+import org.apache.commons.collections4.BidiMap;
+import org.apache.commons.collections4.bidimap.DualHashBidiMap;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.SemanticsDecorator;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.persistence.TopiaEntity;
+
+/**
+ * Convertie une entite, month, timestep en string et inversement.
+ * Entity = "TopiaId:Entity.toString"
+ */
+public class EntitySemanticsDecorator implements SemanticsDecorator<Object, String> {
+
+ static private Log log = LogFactory.getLog(EntitySemanticsDecorator.class);
+
+ public static interface EntityProvider {
+
+ public Object findById(String id);
+ }
+
+ public static class EntityTxProvider implements EntityProvider {
+
+ protected TopiaContext tx;
+
+ public EntityTxProvider(TopiaContext tx) {
+ this.tx = tx;
+ }
+
+ @Override
+ public Object findById(String id) {
+ Object result = tx.findByTopiaId(id);
+ return result;
+ }
+ }
+
+ public static class EntityMapProvider implements EntityProvider {
+
+ protected Map<String, TopiaEntity> map;
+
+ public EntityMapProvider(Map<String, TopiaEntity> map) {
+ this.map = map;
+ }
+
+ @Override
+ public Object findById(String id) {
+ Object result = map.get(id);
+ if (result == null) {
+ throw new IsisFishRuntimeException("Can't find entity in map: " + id);
+ }
+ return result;
+ }
+ }
+
+
+ private static final String SEP = ":";
+ protected EntityProvider provider;
+ /** en cle les representation interne (get) en valeur les valeurs decoree (getKey) */
+ protected BidiMap<String, Object> cache = new DualHashBidiMap<>();
+
+ public EntitySemanticsDecorator() {
+ }
+
+ public EntitySemanticsDecorator(EntityProvider provider) {
+ this.provider = provider;
+ }
+
+ /**
+ * return all currently cached object decorated. Can be used to transforme
+ * matrix and work on object found in semantics.
+ * If returned collection is cleared, all object in cache are removed too
+ * @return
+ */
+ public Collection<Object> getDecoratedObject() {
+ Collection<Object> result = cache.values();
+ return result;
+ }
+
+ @Override
+ public Object decorate(String internalValue) {
+ Object result = cache.get(internalValue);
+ if (result == null && internalValue != null) {
+ // on retrouve souvent les memes semantiques dans les matrices
+ // pour minimiser les chaines en memoire, on prend la representation
+ // interne avant de l'utiliser comme cle.
+ internalValue = internalValue.intern();
+ result = internalValue;
+ if (StringUtils.startsWith(internalValue, "Month")) {
+ String val = StringUtils.substringAfter(internalValue, SEP);
+ int monthNumber = Integer.parseInt(val);
+ result = Month.MONTH[monthNumber];
+ } else if (StringUtils.startsWith(internalValue, "TimeStep")) {
+ String val = StringUtils.substringAfter(internalValue, SEP);
+ int stepNumber = Integer.parseInt(val);
+ result = new TimeStep(stepNumber);
+ } else if (StringUtils.startsWith(internalValue, "fr.ifremer.isisfish.entities.")) {
+ if (provider == null) {
+ result = StringUtils.substringAfter(internalValue, SEP);
+ } else {
+ try {
+ String id = StringUtils.substringBefore(internalValue, SEP);
+ result = provider.findById(id);
+ } catch (Exception eee) {
+ log.info("Fallback use string representation because" + " i can't decorate (String->Entity): " + internalValue, eee);
+ // si on arrive pas a convertir cette fois-ci, on
+ // renvoi internalValue pour que le undecorate est toutes les infos
+ // et donc que la prochaine fois on y arrive peut etre
+ }
+ }
+ }
+ cache.put(internalValue, result);
+ }
+ return result;
+ }
+
+ @Override
+ public String undecorate(Object decoratedValue) {
+ if (decoratedValue instanceof String) {
+ return (String)decoratedValue;
+ }
+
+ String result = cache.getKey(decoratedValue);
+ if (result == null && decoratedValue != null) {
+ if (decoratedValue instanceof Month) {
+ result = "Month" + SEP + ((Month) decoratedValue).getMonthNumber();
+ } else if (decoratedValue instanceof TimeStep) {
+ result = "TimeStep" + SEP + ((TimeStep) decoratedValue).getStep();
+ } else if (decoratedValue instanceof TopiaEntity) {
+ result = ((TopiaEntity) decoratedValue).getTopiaId() + SEP + decoratedValue;
+ } else {
+ result = String.valueOf(decoratedValue);
+ }
+ // on retrouve souvent les memes semantiques dans les matrices
+ // pour minimiser les chaines en memoire, on prend la representation
+ // interne avant de l'utiliser comme cle.
+ result = result.intern();
+ cache.put(result, decoratedValue);
+ }
+ return result;
+ }
+
+}
Property changes on: trunk/src/main/java/fr/ifremer/isisfish/util/EntitySemanticsDecorator.java
___________________________________________________________________
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision HeadURL
\ No newline at end of property
Added: trunk/src/main/java/fr/ifremer/isisfish/util/MatrixCSVHelper.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/util/MatrixCSVHelper.java (rev 0)
+++ trunk/src/main/java/fr/ifremer/isisfish/util/MatrixCSVHelper.java 2016-11-04 15:05:55 UTC (rev 4369)
@@ -0,0 +1,197 @@
+package fr.ifremer.isisfish.util;
+
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.LineNumberReader;
+import java.io.PrintWriter;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.math.matrix.MatrixFactory;
+import org.nuiton.math.matrix.MatrixIterator;
+import org.nuiton.math.matrix.MatrixND;
+
+/**
+ * Classe permettant de convertir une matrice en String et inversement en
+ * prenant en compte la conversion des semantiques via l'utilisation
+ * d'un decorator ({@link EntitySemanticsDecorator}).
+ *
+ * Ce format est utilise comme format de sauvegarde des resultats dans les
+ * simulation. Il remplace le stockage en base et les fichiers mapper.
+ *
+ * Format d'une matrice:
+ * <pre>
+ * # commentaire
+ * [nom]
+ * [nom dimension1]:[semantique1];[semantique2];...
+ * [nom dimension2]:[semantique1];[semantique2];...
+ * ...
+ * [ligne blanche]
+ * [coordonnee1];[coordonnee2];...;[valeur]
+ * [coordonnee1];[coordonnee2];...;[valeur]
+ * [coordonnee1];[coordonnee2];...;[valeur]
+ * ...
+ * </pre>
+ *
+ * Exemple
+ * <pre>
+ * MaMatrice
+ * Mois:Janvier;Fevrier;Mars
+ * Ville:Nantes;Paris;Nice
+ *
+ * 1;1;2;13.5
+ * 0;2;1;4.2
+ * </pre>
+ *
+ * @author poussin
+ * @version $Revision$
+ *
+ * Last update: $Date$
+ * by : $Author$
+ *
+ * @since 4.4.1.0
+ */
+public class MatrixCSVHelper {
+
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private Log log = LogFactory.getLog(MatrixCSVHelper.class);
+
+ protected EntitySemanticsDecorator decorator;
+
+ public MatrixCSVHelper() {
+ this(new EntitySemanticsDecorator());
+ }
+
+ public MatrixCSVHelper(EntitySemanticsDecorator decorator) {
+ this.decorator = decorator;
+ }
+
+ protected MatrixFactory getMatrixFactory() {
+ return MatrixFactory.getInstance();
+ }
+
+ /**
+ * return new list with undecorate item
+ * @param l
+ * @return new list
+ */
+ protected List<String> undecorate(List l) {
+ ArrayList<String> result = new ArrayList<String>(l.size());
+ for (Object o : l) {
+ result.add(undecorate(o));
+ }
+ return result;
+ }
+
+ protected String undecorate(Object o) {
+ return decorator.undecorate(o);
+ }
+
+ public MatrixND readMatrix(String mat) throws IOException {
+ try (Reader in = new StringReader(mat)) {
+ MatrixND result = this.readMatrix(in);
+ return result;
+ }
+ }
+
+ public String writeMatrix(String name, MatrixND mat) throws IOException {
+ try (StringWriter out = new StringWriter()) {
+ writeMatrix(out, name, mat);
+ String result = out.toString();
+ return result;
+ }
+ }
+
+ public MatrixND readMatrix(Reader reader) throws IOException {
+ LineNumberReader in = new LineNumberReader(reader);
+
+ SimpleParser sp = new SimpleParser(in, true);
+
+ // lecture du nom de la matrice
+ String name = sp.readString('\n');
+
+
+ // lecture du nom des dimensions et des semantics
+ List<String> dimNames = new ArrayList<String>();
+ List<List<String>> semantics = new ArrayList<List<String>>();
+
+ String dimName = sp.readString(':');
+ while (!sp.isEOL() || StringUtils.isNotBlank(dimName)) {
+ dimNames.add(dimName);
+ List<String> sems = new ArrayList<String>();
+ semantics.add(sems);
+ while (!sp.isEOL()) {
+ String sem = sp.readString(';');
+ sems.add(sem);
+ }
+ dimName = sp.readString(':');
+ }
+
+ // creation de la matrice resultat avec les infos collectes
+ MatrixND result = getMatrixFactory().create(name,
+ semantics.toArray(new List[semantics.size()]),
+ dimNames.toArray(new String[dimNames.size()]));
+
+
+ // lecture des data
+ int nbDim = dimNames.size();
+ int[] coord = new int[nbDim];
+
+ while (!sp.isEOF()) {
+ for (int i=0; i<nbDim; i++) {
+ coord[i] = sp.readInt(';');
+ }
+ double v = sp.readDouble(';');
+ result.setValue(coord, v);
+ }
+
+ return result;
+ }
+
+ public void writeMatrix(Writer writer, String name, MatrixND mat) {
+ PrintWriter out = new PrintWriter(new BufferedWriter(writer));
+
+ out.print(name);
+ out.println();
+
+ List[] sems = mat.getSemantics();
+ for (int i=0, maxi=sems.length; i<maxi; i++) {
+ String dimName = mat.getDimensionName(i);
+ out.print(dimName);
+
+ List l = undecorate(sems[i]);
+ char sep = ':';
+ for (Object o : l) {
+ out.print(sep);
+ out.print(o);
+ sep = ';';
+ }
+ out.println();
+ }
+
+ // blank line to separate header and data
+ out.println();
+
+ for (MatrixIterator i = mat.iteratorNotZero(); i.hasNext();) {
+ i.next();
+ int[] pos = i.getCoordinates();
+ double value = i.getValue();
+ for (int p : pos) {
+ out.print(p);
+ out.print(';');
+ }
+ out.print(value);
+ out.println();
+ }
+
+ out.flush();
+ }
+
+}
Property changes on: trunk/src/main/java/fr/ifremer/isisfish/util/MatrixCSVHelper.java
___________________________________________________________________
Added: svn:keywords
## -0,0 +1 ##
+Author Date Id Revision HeadURL
\ No newline at end of property
Modified: trunk/src/main/resources/i18n/isis-fish_en_GB.properties
===================================================================
--- trunk/src/main/resources/i18n/isis-fish_en_GB.properties 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/resources/i18n/isis-fish_en_GB.properties 2016-11-04 15:05:55 UTC (rev 4369)
@@ -458,7 +458,9 @@
isisfish.input.menu.addRegion=Add region
isisfish.input.menu.commit=Commit change
isisfish.input.menu.copyRegion=Copy region
+isisfish.input.menu.exportJson=Export current object in JSON
isisfish.input.menu.exportRegion=Export region
+isisfish.input.menu.importJson=Import objets from JSON
isisfish.input.menu.importRegion=Import region
isisfish.input.menu.importRegionSimulation=Import region from simulation
isisfish.input.menu.importRenameRegion=Import region and rename
Modified: trunk/src/main/resources/i18n/isis-fish_fr_FR.properties
===================================================================
--- trunk/src/main/resources/i18n/isis-fish_fr_FR.properties 2016-11-04 14:16:08 UTC (rev 4368)
+++ trunk/src/main/resources/i18n/isis-fish_fr_FR.properties 2016-11-04 15:05:55 UTC (rev 4369)
@@ -458,7 +458,9 @@
isisfish.input.menu.addRegion=Ajouter une région
isisfish.input.menu.commit=Sauvegarder les changements
isisfish.input.menu.copyRegion=Copier région
+isisfish.input.menu.exportJson=Exporter l'object courant en JSON
isisfish.input.menu.exportRegion=Exporter la région
+isisfish.input.menu.importJson=Importer des objets JSON
isisfish.input.menu.importRegion=Importer une région
isisfish.input.menu.importRegionSimulation=Importer la région d'une simulation
isisfish.input.menu.importRenameRegion=Importer une région et la renommer
1
0
Author: bpoussin
Date: 2016-11-04 15:16:08 +0100 (Fri, 04 Nov 2016)
New Revision: 4368
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4368
Log:
change mime-type
Modified:
trunk/src/main/resources/log4j2.xml
Modified: trunk/src/main/resources/log4j2.xml
===================================================================
(Binary files differ)
Index: trunk/src/main/resources/log4j2.xml
===================================================================
--- trunk/src/main/resources/log4j2.xml 2016-11-04 14:14:46 UTC (rev 4367)
+++ trunk/src/main/resources/log4j2.xml 2016-11-04 14:16:08 UTC (rev 4368)
Property changes on: trunk/src/main/resources/log4j2.xml
___________________________________________________________________
Modified: svn:mime-type
## -1 +1 ##
-application/xml
\ No newline at end of property
+text/xml
\ No newline at end of property
1
0
Author: bpoussin
Date: 2016-11-04 15:14:46 +0100 (Fri, 04 Nov 2016)
New Revision: 4367
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4367
Log:
add date in output
Modified:
trunk/src/main/assembly/isisfish-log4j2.xml
Modified: trunk/src/main/assembly/isisfish-log4j2.xml
===================================================================
--- trunk/src/main/assembly/isisfish-log4j2.xml 2016-10-23 16:43:56 UTC (rev 4366)
+++ trunk/src/main/assembly/isisfish-log4j2.xml 2016-11-04 14:14:46 UTC (rev 4367)
@@ -31,7 +31,7 @@
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
- <PatternLayout pattern="%5p [%t] (%F:%L) %M - %m%n" />
+ <PatternLayout pattern="%d{HH:mm:ss.SSS} %5p [%t] (%F:%L) %M - %m%n" />
</Console>
<Routing name="SimulationSpecificAppender">
1
0
Author: echatellier
Date: 2016-10-23 18:43:56 +0200 (Sun, 23 Oct 2016)
New Revision: 4366
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4366
Log:
Mise ?\195?\160 jour des libs
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2016-09-01 09:42:02 UTC (rev 4365)
+++ trunk/pom.xml 2016-10-23 16:43:56 UTC (rev 4366)
@@ -20,7 +20,7 @@
<dependency>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils</artifactId>
- <version>3.0-rc-13</version>
+ <version>3.0-rc-16</version>
<scope>compile</scope>
</dependency>
@@ -27,7 +27,7 @@
<dependency>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-config</artifactId>
- <version>3.0-rc-4</version>
+ <version>3.1</version>
<scope>compile</scope>
</dependency>
@@ -111,31 +111,31 @@
<dependency>
<groupId>com.fifesoft</groupId>
<artifactId>rsyntaxtextarea</artifactId>
- <version>2.5.8</version>
+ <version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.fifesoft</groupId>
<artifactId>rstaui</artifactId>
- <version>2.5.7</version>
+ <version>2.6.0</version>
</dependency>
<!-- <dependency>
<groupId>com.fifesoft</groupId>
<artifactId>autocomplete</artifactId>
- <version>2.5.7</version>
+ <version>2.6.0</version>
</dependency>
<dependency>
<groupId>com.fifesoft</groupId>
<artifactId>languagesupport</artifactId>
- <version>2.5.7</version>
+ <version>2.6.0</version>
</dependency> -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
- <version>1.5.5</version>
+ <version>1.5.6</version>
<scope>compile</scope>
</dependency>
@@ -192,7 +192,7 @@
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
- <version>3.4</version>
+ <version>3.5</version>
</dependency>
<dependency>
@@ -204,7 +204,7 @@
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
- <version>1.9.2</version>
+ <version>1.9.3</version>
</dependency>
<dependency>
@@ -242,7 +242,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
- <version>2.6.2</version>
+ <version>2.7</version>
<scope>compile</scope>
</dependency>
@@ -249,7 +249,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
- <version>2.6.2</version>
+ <version>2.7</version>
<scope>compile</scope>
</dependency>
@@ -256,7 +256,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
- <version>2.6.2</version>
+ <version>2.7</version>
<scope>runtime</scope>
</dependency>
@@ -263,7 +263,7 @@
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
- <version>2.6.2</version>
+ <version>2.7</version>
<scope>runtime</scope>
</dependency>
@@ -297,7 +297,7 @@
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
- <version>0.1.53</version>
+ <version>0.1.54</version>
<scope>compile</scope>
</dependency>
@@ -384,7 +384,7 @@
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
- <version>4.5.1</version>
+ <version>4.6.1</version>
</dependency>
<dependency>
@@ -552,11 +552,11 @@
<signatureVersion>1.0</signatureVersion>
<!-- Dependencies version -->
- <jaxxVersion>2.30.1</jaxxVersion>
+ <jaxxVersion>2.33.1</jaxxVersion>
<eugeneVersion>2.14</eugeneVersion>
<topiaVersion>2.12-SNAPSHOT</topiaVersion>
- <hibernateVersion>5.1.0.Final</hibernateVersion>
- <nuitonI18nVersion>3.5</nuitonI18nVersion>
+ <hibernateVersion>5.1.2.Final</hibernateVersion>
+ <nuitonI18nVersion>3.6.2</nuitonI18nVersion>
<nuitonWidgetsVersion>1.1.1</nuitonWidgetsVersion>
<redmine.releaseFiles>target/isis-fish-${project.version}-bin.zip</redmine.releaseFiles>
1
0
r4365 - trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher
by bpoussin@users.forge.codelutin.com 01 Sep '16
by bpoussin@users.forge.codelutin.com 01 Sep '16
01 Sep '16
Author: bpoussin
Date: 2016-09-01 11:42:02 +0200 (Thu, 01 Sep 2016)
New Revision: 4365
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4365
Log:
fixes #8484: Am?\195?\169liorer l'affichage du temps de progression des simulations
Modified:
trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java
Modified: trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java 2016-09-01 09:35:53 UTC (rev 4364)
+++ trunk/src/main/java/fr/ifremer/isisfish/simulator/launcher/SimulationServiceTableModel.java 2016-09-01 09:42:02 UTC (rev 4365)
@@ -27,24 +27,23 @@
import static org.nuiton.i18n.I18n.t;
+import fr.ifremer.isisfish.datastore.SimulationInformation;
+import fr.ifremer.isisfish.simulator.SimulationControl;
+import fr.ifremer.isisfish.simulator.SimulationParameter;
+import fr.ifremer.isisfish.types.TimeStep;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
+import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
-
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
-
+import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
-import fr.ifremer.isisfish.simulator.SimulationControl;
-import fr.ifremer.isisfish.simulator.SimulationParameter;
-import fr.ifremer.isisfish.types.TimeStep;
-import org.apache.commons.lang3.time.DurationFormatUtils;
import org.nuiton.profiling.Unit;
/**
@@ -67,11 +66,11 @@
private static final long serialVersionUID = 2414926794815727974L;
/** to use log facility, just put in your code: log.info(\"...\"); */
- private static Log log = LogFactory
+ private final static Log log = LogFactory
.getLog(SimulationServiceTableModel.class);
/** Columns names. */
- protected final static String[] columnHeader = new String[] {
+ protected final static String[] COLUMN_HEADER = new String[] {
t("isisfish.queue.id"),
t("isisfish.queue.plan"),
t("isisfish.queue.launcher"),
@@ -116,6 +115,7 @@
jobs.add(job);
jobIds.put(id, job);
SwingUtilities.invokeLater(new Runnable() {
+ @Override
public void run() {
fireTableRowsInserted(jobs.size() - 1, jobs.size() - 1);
}
@@ -132,6 +132,7 @@
jobs.remove(index);
jobIds.remove(id);
SwingUtilities.invokeLater(new Runnable() {
+ @Override
public void run() {
fireTableRowsDeleted(index, index);
}
@@ -143,6 +144,7 @@
public void clearJob() {
jobs.clear();
SwingUtilities.invokeLater(new Runnable() {
+ @Override
public void run() {
fireTableDataChanged();
}
@@ -190,6 +192,7 @@
/*
* @see javax.swing.table.TableModel#getRowCount()
*/
+ @Override
public int getRowCount() {
int result = jobs.size();
return result;
@@ -198,8 +201,9 @@
/*
* @see javax.swing.table.TableModel#getColumnCount()
*/
+ @Override
public int getColumnCount() {
- int result = columnHeader.length;
+ int result = COLUMN_HEADER.length;
return result;
}
@@ -216,12 +220,13 @@
*/
@Override
public String getColumnName(int column) {
- return columnHeader[column];
+ return COLUMN_HEADER[column];
}
/*
* @see javax.swing.table.TableModel#getValueAt(int, int)
*/
+ @Override
public Object getValueAt(int rowIndex, int columnIndex) {
// FIXME echatellier : hack ArrayIndexOutOfBoundException for unknown
@@ -284,15 +289,21 @@
int value = (int) control.getProgress();
int max = (int) control.getProgressMax();
+ double meanTime = control.getTimeStepMeanTime();
- String restTime = "";
int rest = max - value;
- double time = rest * control.getTimeStepMeanTime();
- if (time > 0) {
- long milli = (long)Unit.Time.s.convertTo(Unit.Time.milli, time);
- restTime = DurationFormatUtils.formatDurationHMS(milli);
+ double time = rest * meanTime;
+ if (time <= 0) {
+ // fin de simulation, on met le temps de simulation
+ SimulationInformation info = control.getSimulation().getInformation();
+ Date start = info.getSimulationStart();
+ Date end = info.getSimulationEnd();
+ time = (end.getTime() - start.getTime()) / 1000;
}
+ long milli = (long)Unit.Time.s.convertTo(Unit.Time.milli, time);
+ String restTime = DurationFormatUtils.formatDurationHMS(milli);
+
pb.setMaximum(max);
pb.setValue(value);
@@ -324,11 +335,13 @@
setData();
}
+ @Override
public void setData() {
model.setJobs(new ArrayList<SimulationJob>(simulationService
.getJobDones()));
}
+ @Override
public void simulationStart(SimulationService simService,
SimulationJob job) {
// this happens when job is restarted
@@ -336,11 +349,13 @@
model.removeJob(job);
}
+ @Override
public void simulationStop(SimulationService simService,
SimulationJob job) {
model.addJob(job);
}
+ @Override
public void clearJobDone(SimulationService simService) {
model.clearJob();
}
@@ -397,6 +412,7 @@
this.model = model;
}
+ @Override
public void propertyChange(PropertyChangeEvent evt) {
SimulationControl control = (SimulationControl) evt.getSource();
String id = control.getId();
@@ -405,6 +421,7 @@
final int index = model.getJobs().indexOf(job);
if (index >= 0) {
SwingUtilities.invokeLater(new Runnable() {
+ @Override
public void run() {
fireTableRowsUpdated(index, index);
}
1
0
r4364 - trunk/src/main/java/fr/ifremer/isisfish/util
by bpoussin@users.forge.codelutin.com 01 Sep '16
by bpoussin@users.forge.codelutin.com 01 Sep '16
01 Sep '16
Author: bpoussin
Date: 2016-09-01 11:35:53 +0200 (Thu, 01 Sep 2016)
New Revision: 4364
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4364
Log:
change log message to have better information on class
Modified:
trunk/src/main/java/fr/ifremer/isisfish/util/IsisCacheBackendOnGuava.java
Modified: trunk/src/main/java/fr/ifremer/isisfish/util/IsisCacheBackendOnGuava.java
===================================================================
--- trunk/src/main/java/fr/ifremer/isisfish/util/IsisCacheBackendOnGuava.java 2016-08-29 15:22:58 UTC (rev 4363)
+++ trunk/src/main/java/fr/ifremer/isisfish/util/IsisCacheBackendOnGuava.java 2016-09-01 09:35:53 UTC (rev 4364)
@@ -29,7 +29,6 @@
import com.google.common.cache.Weigher;
import fr.ifremer.isisfish.types.TimeStep;
import java.util.Collection;
-import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.math.matrix.MatrixND;
@@ -102,7 +101,7 @@
} else {
// a priori, il n'y a pas d'autre type de donnee
if (value != null) {
- log.info("Cache can't compute value size of " + ClassUtils.getPackageCanonicalName(value, "null"));
+ log.info("Cache can't compute value size of " + ((Object)value).getClass());
}
}
1
0
Author: bpoussin
Date: 2016-08-29 17:22:58 +0200 (Mon, 29 Aug 2016)
New Revision: 4363
Url: http://forge.codelutin.com/projects/isis-fish/repository/revisions/4363
Log:
add properties to generate javadoc (needed for isis site)
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2016-08-04 12:28:35 UTC (rev 4362)
+++ trunk/pom.xml 2016-08-29 15:22:58 UTC (rev 4363)
@@ -566,6 +566,7 @@
<!-- Correction des bugs du super pom -->
<javadocPluginVersion>2.10.3</javadocPluginVersion>
+ <maven.javadoc.skip>false</maven.javadoc.skip>
<animalSnifferPluginVersion>1.14</animalSnifferPluginVersion>
<redmine.url>https://forge.${platform}</redmine.url>
<maven.javadoc.skip>false</maven.javadoc.skip>
1
0