r264 - in trunk/tutti-persistence-adagio: . src/main/java/fr/ifremer/tutti/persistence/service src/main/resources src/test/java/fr/ifremer/tutti/persistence/service
Author: blavenier Date: 2013-01-30 11:39:43 +0100 (Wed, 30 Jan 2013) New Revision: 264 Url: http://forge.codelutin.com/projects/tutti/repository/revisions/264 Log: ref refs #1920: [Persistence] Adagio Donnees thematiques - Change some PSFM ID in enumerations - Cruise : Add storage of managers and sort room managers (in FishingTrip.comments) - FishingOperation : Add storage of recorder persons (in Operation.comments) - FishingOperation : change 'name' content, to only use '<gearLabel><fishingOperationNumber>' as usual in Harmonie - FishingOperation : implements getAllFishingOperation to only retrieve mandatory properties (for combo) - Queries : speed up query on vessels, add fetch profile (for speciesBatchs) Modified: trunk/tutti-persistence-adagio/ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceImpl.java trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceImpl.java trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/ProgramPersistenceServiceImpl.java trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java trunk/tutti-persistence-adagio/src/main/resources/queries-override.hbm.xml trunk/tutti-persistence-adagio/src/main/resources/tutti-db-conf.properties trunk/tutti-persistence-adagio/src/main/resources/tutti-db-enumerations.properties trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceTest.java trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceTest.java trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceTest.java Property changes on: trunk/tutti-persistence-adagio ___________________________________________________________________ Modified: svn:ignore - target *.ipr *.iml *.iws .idea .classpath .project + target *.ipr *.iml *.iws .idea .classpath .project .settings Modified: trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java =================================================================== --- trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/AbstractPersistenceService.java 2013-01-30 10:39:43 UTC (rev 264) @@ -78,7 +78,14 @@ Object result = query.uniqueResult(); return (Object[]) result; } + + protected <T> T queryUniqueTyped(String queryName, Object... params) { + Query query = createQuery(queryName, params); + Object result = query.uniqueResult(); + return (T) result; + } + protected Iterator<Object[]> queryList(String queryName, Object... params) { Query query = createQuery(queryName, params); @@ -122,4 +129,13 @@ T load = (T) getCurrentSession().load(clazz, id); return load; } + + protected int queryUpdate(String queryName, Object... params) { + + Query query = createQuery(queryName, params); + + int result = query.executeUpdate(); + return result; + } + } Modified: trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceImpl.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceImpl.java 2013-01-30 10:39:43 UTC (rev 264) @@ -25,6 +25,7 @@ */ import java.sql.Timestamp; +import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; @@ -86,12 +87,12 @@ protected static String CRUISE_MISC_DATA_VESSELS_TAG = "#VESSELS="; - protected static String CRUISE_MISC_DATA_GEARS_TAG = "#GEARS="; - - protected static String CRUISE_MISC_DATA_TRAWL_NET_TAG = "#TRAWL_NET="; + protected static String CRUISE_MISC_DATA_MANAGERS_TAG = "#MANAGERS="; + protected static String CRUISE_MISC_DATA_SORT_MANAGERS_TAG = "#SORT_MANAGERS="; + @Autowired(required = true) - protected ReferentialPersistenceService referentielService; + protected ReferentialPersistenceService referentialService; @Autowired(required = true) protected ProgramPersistenceService programService; @@ -186,53 +187,21 @@ result.setEndDate((Date) source[7]); String vesselCode = (String) source[8]; - Vessel vessel = referentielService.getVessel(vesselCode); + Vessel vessel = referentialService.getVessel(vesselCode); result.setVessel(Lists.newArrayList(vessel)); Integer managerId = (Integer) source[9]; if (managerId != null && managerId.equals(enumeration.PERSON_ID_UNKNOWN_RECORDER_PERSON)) { result.setHeadOfMission(null); } else { - Person manager = referentielService.getPerson(managerId); + Person manager = referentialService.getPerson(managerId); result.setHeadOfMission(Lists.newArrayList(manager)); } - - + result.setComment((String) source[10]); String miscData = (String) source[11]; if (miscData != null && miscData.length() > 0) { - - // Retrieve trawl net - int trawlNetIndex = miscData.indexOf(CRUISE_MISC_DATA_TRAWL_NET_TAG); - if (trawlNetIndex != -1) { - String trawlNetStr = miscData.substring(trawlNetIndex + CRUISE_MISC_DATA_TRAWL_NET_TAG.length()).trim(); - miscData = miscData.substring(0, trawlNetIndex); - if (!trawlNetStr.isEmpty()) { - result.setTrawlNet(Integer.valueOf(trawlNetStr)); - } - } - - // Retrieve gears : - int gearTagIndex = miscData.indexOf(CRUISE_MISC_DATA_GEARS_TAG); - if (gearTagIndex == -1) { - result.setGear(null); - } else { - String gearIdsStr = miscData.substring(gearTagIndex + CRUISE_MISC_DATA_GEARS_TAG.length()).trim(); - miscData = miscData.substring(0, gearTagIndex); - if (gearIdsStr.isEmpty()) { - result.setGear(null); - } else { - List<Gear> gears = Lists.newArrayList(); - String[] gearIds = gearIdsStr.split(","); - for (int i = 0; i < gearIds.length; i++) { - Integer gearId = Integer.valueOf(gearIds[i]); - gears.add(referentielService.getGear(gearId)); - } - result.setGear(gears); - } - } - // Retrieve secondary vessels : int vesselTagIndex = miscData.indexOf(CRUISE_MISC_DATA_VESSELS_TAG); if (vesselTagIndex != -1) { @@ -242,25 +211,56 @@ String[] vesselCodes = vesselCodesStr.split(","); for (int i = 0; i < vesselCodes.length; i++) { vesselCode = vesselCodes[i]; - result.addVessel(referentielService.getVessel(vesselCode)); + result.addVessel(referentialService.getVessel(vesselCode)); } } } - } - + // Retrieve cruise managers + int managersIndex = miscData.indexOf(CRUISE_MISC_DATA_MANAGERS_TAG); + if (managersIndex != -1) { + String managersStr = miscData.substring(managersIndex + CRUISE_MISC_DATA_MANAGERS_TAG.length()).trim(); + miscData = miscData.substring(0, managersIndex); + if (!managersStr.isEmpty()) { + String[] managersArray = managersStr.split(","); + for (int i = 0; i < managersArray.length; i++) { + String personId = managersArray[i]; + Person person = referentialService.getPerson(Integer.valueOf(personId)); + result.getHeadOfMission().add(person); + } + } + } + + // Retrieve sort room managers + int sortManagersIndex = miscData.indexOf(CRUISE_MISC_DATA_SORT_MANAGERS_TAG); + if (sortManagersIndex != -1) { + String sortManagersStr = miscData.substring(sortManagersIndex + CRUISE_MISC_DATA_SORT_MANAGERS_TAG.length()).trim(); + miscData = miscData.substring(0, sortManagersIndex); + if (!sortManagersStr.isEmpty()) { + String[] managersArray = sortManagersStr.split(","); + List<Person> persons = new ArrayList<Person>(); + for (int i = 0; i < managersArray.length; i++) { + String personId = managersArray[i]; + Person person = referentialService.getPerson(Integer.valueOf(personId)); + persons.add(person); + } + result.setHeadOfSortRoom(persons); + } + } + } + // get secondary gears from fishingOperation (first load from Allegro DB only) if (result.getGear() == null) { Iterator<Object[]> list = queryList( "allCruiseGears", "cruiseId", IntegerType.INSTANCE, Integer.valueOf(id), - "pmfmIdTrawlNet", IntegerType.INSTANCE, enumeration.PMFM_ID_TRAWL_NET); + "pmfmIdTrawlNet", IntegerType.INSTANCE, enumeration.PMFM_ID_MULTIRIG_NUMBER); List<Gear> gears = Lists.newArrayList(); int maxTrawlNetFound = 0; while (list.hasNext()) { Object[] gearRow = list.next(); - Gear target = referentielService.getGear((Integer) gearRow[0]); + Gear target = referentialService.getGear((Integer) gearRow[0]); Float trawlNet = (Float) gearRow[1]; if (trawlNet != null && trawlNet.intValue() > maxTrawlNetFound) { maxTrawlNetFound = trawlNet.intValue(); @@ -269,7 +269,7 @@ } result.setGear(gears); if (maxTrawlNetFound > 0) { - result.setTrawlNet(maxTrawlNetFound); + result.setTrawlNet(maxTrawlNetFound); } } return result; @@ -316,10 +316,8 @@ } } else { fishingTrip = (ObservedFishingTrip)target.getFishingTrips().iterator().next(); - } + } - - // Name if (copyIfNull && source.getName() == null) { target.setName(null); @@ -333,7 +331,36 @@ } else if (source.getName() != null && source.getProgram().getId() != null) { target.setProgram(programDao.load(source.getProgram().getId())); } + + // Sort Room Managers + if (copyIfNull && (source.getHeadOfSortRoom() == null || source.getHeadOfSortRoom().size() == 0)) { + target.setManagerPerson(null); + } else if (source.getHeadOfSortRoom() != null && source.getHeadOfSortRoom().size() > 0) { + List<Person> persons = source.getHeadOfSortRoom(); + miscDataBuffer.append(CRUISE_MISC_DATA_SORT_MANAGERS_TAG); + for (int i = 0; i < persons.size(); i++) { + if (i > 0) miscDataBuffer.append(','); + miscDataBuffer.append(persons.get(i).getId()); + } + } + + // Managers + if (copyIfNull && (source.getHeadOfMission() == null || source.getHeadOfMission().size() == 0)) { + target.setManagerPerson(null); + } else if (source.getHeadOfMission() != null && source.getHeadOfMission().size() > 0) { + List<Person> persons = source.getHeadOfMission(); + target.setManagerPerson(personDao.load(Integer.valueOf(persons.get(0).getId()))); + if (persons.size() > 1) { + //throw new UnsupportedOperationException("Cruise could not yet support more than one vessel."); + miscDataBuffer.append(CRUISE_MISC_DATA_MANAGERS_TAG); + for (int i = 1; i < persons.size(); i++) { + if (i > 1) miscDataBuffer.append(','); + miscDataBuffer.append(persons.get(i).getId()); + } + } + } + // Vessel if (copyIfNull && (source.getVessel() == null || source.getVessel().size() == 0)) { target.setProgram(null); @@ -394,14 +421,11 @@ if (copyIfNull && (source.getHeadOfMission() == null || source.getHeadOfMission().size() == 0)) { target.setComments(null); } else if (source.getHeadOfMission() != null && source.getHeadOfMission().size() > 0) { - if (source.getHeadOfMission().size() == 1) { + if (source.getHeadOfMission().size() > 0) { Person managerPerson = source.getHeadOfMission().get(0); if (managerPerson.getId() != null) { target.setManagerPerson(personDao.load(Integer.valueOf(managerPerson.getId()))); } - } else { - // TODO : comment gérer dans le modèle Adagio plus d'un manager ? - throw new UnsupportedOperationException("Cruise could not yet support more than one manager person."); } } @@ -453,11 +477,9 @@ } // Gear - if (copyIfNull && source.isGearEmpty()) { - miscDataBuffer.append(CRUISE_MISC_DATA_GEARS_TAG); + if (copyIfNull && source.isGearEmpty() && fishingTrip.getGearPhysicalFeatures() != null) { + fishingTrip.getGearPhysicalFeatures().clear(); } else if (!source.isGearEmpty()) { - //throw new UnsupportedOperationException("Cruise could not yet support gears storage."); - miscDataBuffer.append(CRUISE_MISC_DATA_GEARS_TAG); for (int i = 0; i < source.getGear().size(); i++) { Gear gear = source.getGear().get(i); GearPhysicalFeatures guf = getGearPhysicalfeatures(fishingTrip, Integer.valueOf(gear.getId()), true); @@ -471,27 +493,14 @@ // Trawl net (store in Gear Physical features) if (copyIfNull && source.getTrawlNet() == null) { - removeGearPhysicalMeasurement(guf, enumeration.PMFM_ID_TRAWL_NET); + removeGearPhysicalMeasurement(guf, enumeration.PMFM_ID_MULTIRIG_NUMBER); } else { - setGearPhysicalMeasurement(target, guf, enumeration.PMFM_ID_TRAWL_NET, Float.valueOf(source.getTrawlNet()), null, null); + setGearPhysicalMeasurement(target, guf, enumeration.PMFM_ID_MULTIRIG_NUMBER, Float.valueOf(source.getTrawlNet()), null, null); } - - // TODO BLA : à supprimer : - if (i > 0) miscDataBuffer.append(','); - miscDataBuffer.append(source.getGear().get(i).getId()); } - } + } - // Trawl net (store in misc data) - if (copyIfNull && source.getTrawlNet() == null) { - miscDataBuffer.append(CRUISE_MISC_DATA_TRAWL_NET_TAG); - } else if (source.getTrawlNet() != null) { - //throw new UnsupportedOperationException("Cruise could not yet support gears storage."); - miscDataBuffer.append(CRUISE_MISC_DATA_TRAWL_NET_TAG); - miscDataBuffer.append(source.getTrawlNet()); - } - // Save miscDataBuffer into fishing trip comments, because it's not used in Allegro fishingTrip.setComments(miscDataBuffer.toString()); } @@ -518,11 +527,7 @@ GearPhysicalFeatures gearPhysicalFeature = GearPhysicalFeatures.Factory.newInstance(); gearPhysicalFeature.setFishingTrip(fishingTrip); - fr.ifremer.adagio.core.dao.referential.gear.Gear gear = (fr.ifremer.adagio.core.dao.referential.gear.Gear)getCurrentSession().load(GearImpl.class, gearId); - //fr.ifremer.adagio.core.dao.referential.gear.Gear gear = gearDao.load(gearId); - //if (gear == null) { - // throw new DataRetrievalFailureException("Gear not found with id=" + gearId); - //} + fr.ifremer.adagio.core.dao.referential.gear.Gear gear = (fr.ifremer.adagio.core.dao.referential.gear.Gear)getCurrentSession().load(GearImpl.class, gearId); gearPhysicalFeature.setGear(gear); if (fishingTrip.getGearPhysicalFeatures() == null) { fishingTrip.setGearPhysicalFeatures(Lists.newArrayList(gearPhysicalFeature)); @@ -603,4 +608,22 @@ return gearPhysicalMeasurement; } + + protected List<Person> getCruisePersonsByRole(String cruiseId, Integer vesselPersonRole) { + Iterator<Object[]> list = queryList( + "allCruiseManagers", + "cruiseId", IntegerType.INSTANCE, Integer.valueOf(cruiseId), + "vesselPersonRoleId", IntegerType.INSTANCE, vesselPersonRole); + + List<Person> persons = Lists.newArrayList(); + int maxTrawlNetFound = 0; + while (list.hasNext()) { + Object[] source = list.next(); + Person target = new Person(); + + persons.add(target); + } + + return persons; + } } Modified: trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceImpl.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceImpl.java 2013-01-30 10:39:43 UTC (rev 264) @@ -46,9 +46,12 @@ import org.springframework.dao.DataRetrievalFailureException; import org.springframework.stereotype.Service; +import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import fr.ifremer.adagio.core.dao.data.batch.CatchBatch; +import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatch; import fr.ifremer.adagio.core.dao.data.fishingArea.FishingArea; import fr.ifremer.adagio.core.dao.data.fishingArea.FishingArea2RegulationLocation; import fr.ifremer.adagio.core.dao.data.fishingArea.FishingArea2RegulationLocationPK; @@ -83,6 +86,7 @@ import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType; import fr.ifremer.tutti.persistence.entities.referential.FishingOperationLocation; +import fr.ifremer.tutti.persistence.entities.referential.Person; /** * @author tchemit <chemit@codelutin.com> @@ -117,24 +121,75 @@ protected static Float DEFAULT_EMPTY_LONGITUDE = 0.0001f; - protected static String FISHING_OPERATION_NAME_SEPARATOR = " - "; + protected static String MISC_DATA_RECORDER_PERSONS_TAG = "#REC_PERSONS="; protected Calendar calendar = new GregorianCalendar(); @Override public List<FishingOperation> getAllFishingOperation(String cruiseId) { - return null; + Preconditions.checkNotNull(cruiseId); + + Iterator<Object[]> list = queryList( + "allFishingOperations", + "cruiseId", IntegerType.INSTANCE, Integer.valueOf(cruiseId) + ); + + List<FishingOperation> fishingOperations = new ArrayList<FishingOperation>(); + int fishingOperationRankOrder = 0; + while (list.hasNext()) { + Object[] source = list.next(); + fishingOperationRankOrder++; + + FishingOperation fishingOperation = new FishingOperation(); + int colIndex =0; + + // Id + fishingOperation.setId(((Integer)source[colIndex++]).toString()); + + // Fishing operation number : trying to retrieve from name + String name = (String)source[colIndex++]; + String gearLabel = (String)source[colIndex++]; + String fishingOperationNumberStr = null; + if (name != null && !name.isEmpty()) { + if (gearLabel != null && !gearLabel.isEmpty() + && name.startsWith(gearLabel)) { + fishingOperationNumberStr = name.substring(gearLabel.length()); + } + else { + fishingOperationNumberStr = name; + } + if (fishingOperationNumberStr.matches("\\d+")) { + fishingOperation.setFishingOperationNumber(Integer.valueOf(fishingOperationNumberStr)); + } + else { + // TODO BL : invalid op.name format : log ? + } + } + + // If not found, compute it using a counter (see "order by startDateTime" in HQL query) + if (fishingOperation.getFishingOperationNumber() == null) { + fishingOperation.setFishingOperationNumber(fishingOperationRankOrder); + } + + // Station number + String stationNumber = (String)source[colIndex++]; + fishingOperation.setStationNumber(stationNumber); + + // Trawl number net + Float trawlNetNumber = (Float)source[colIndex++]; + fishingOperation.setTrawlNetNumber(trawlNetNumber.intValue()); + + fishingOperations.add(fishingOperation); + } + return fishingOperations; } @Override public FishingOperation getFishingOperation(String id) { + Preconditions.checkNotNull(id); Object[] source = queryUnique( "fishingOperation", "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(id), - "pmfmIdTrawlDistance", IntegerType.INSTANCE, enumeration.PMFM_ID_TRAWL_DISTANCE, - "pmfmIdRectilinearOperation", IntegerType.INSTANCE, enumeration.PMFM_ID_RECTILINEAR_OPERATION, - "pmfmIdHaulValid", IntegerType.INSTANCE, enumeration.PMFM_ID_HAUL_VALID, - "pmfmIdTrawlNetNumber", IntegerType.INSTANCE, enumeration.PMFM_ID_TRAWL_NET_NUMBER, "locationLevelIdStrata", IntegerType.INSTANCE, enumeration.LOCATION_LEVEL_ID_STRATA, "locationLevelIdSubStrata", IntegerType.INSTANCE, enumeration.LOCATION_LEVEL_ID_SUB_STRATA, "locationLevelIdLocalite", IntegerType.INSTANCE, enumeration.LOCATION_LEVEL_ID_LOCALITE @@ -151,39 +206,63 @@ int colIndex=0; - // Name = StationNumber - FishingOperationNumber - TrawlNetNumber + // Name = <GearLabel><FishingOperationNumber> String name = (String)source[colIndex++]; - if (name != null) { - String[] nameInfos = name.split(FISHING_OPERATION_NAME_SEPARATOR); - if (nameInfos.length == 3) { - // Station number - result.setStationNumber(nameInfos[0]); - - // Fishing operation number - if (nameInfos[1].length() == 0) { - result.setFishingOperationNumber(null); - } - else { - result.setFishingOperationNumber(Integer.valueOf(nameInfos[1])); - } - // Trawl net number - if (nameInfos[2].length() == 0) { - result.setTrawlNetNumber(null); - } - else { - result.setTrawlNetNumber(Integer.valueOf(nameInfos[2])); - } + String gearLabel = (String)source[colIndex++]; + + String fishingOperationNumberStr = null; + if (name != null && !name.isEmpty()) { + if (gearLabel != null && !gearLabel.isEmpty() + && name.startsWith(gearLabel)) { + fishingOperationNumberStr = name.substring(gearLabel.length()); } + else { + fishingOperationNumberStr = name; + } + if (fishingOperationNumberStr.matches("\\d+")) { + result.setFishingOperationNumber(Integer.valueOf(fishingOperationNumberStr)); + } } + // If not found, compute it using a counter (see "order by startDateTime" in HQL query) + if (result.getFishingOperationNumber() == null) { + Integer fishingOperationRankOrder = queryUniqueTyped( + "fishingOperationRankOrder", + "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(id) + ); + result.setFishingOperationNumber(fishingOperationRankOrder); + } + // Start date result.setGearShootingStartDate(convertDatabase2UI((Timestamp) source[colIndex++])); // End date result.setGearShootingEndDate(convertDatabase2UI((Timestamp) source[colIndex++])); + // Misc data + String miscData = (String)source[colIndex++]; + + // Retrieve recorder persons + int recorderPersonsIndex = miscData.indexOf(MISC_DATA_RECORDER_PERSONS_TAG); + if (recorderPersonsIndex != -1) { + String recorderPersonsStr = miscData.substring(recorderPersonsIndex + MISC_DATA_RECORDER_PERSONS_TAG.length()).trim(); + miscData = miscData.substring(0, recorderPersonsIndex); + if (!recorderPersonsStr.isEmpty()) { + String[] recorderPersonsArray = recorderPersonsStr.split(","); + List<Person> persons = new ArrayList<Person>(); + for (int i = 0; i < recorderPersonsArray.length; i++) { + String personId = recorderPersonsArray[i]; + Person person = referentialService.getPerson(Integer.valueOf(personId)); + persons.add(person); + } + result.setSaisisseur(persons); + } + } + // Comment : - result.setComment((String) source[colIndex++]); + if (miscData != null && !miscData.isEmpty()) { + result.setComment(miscData); + } // Gear : Integer gearId = (Integer)source[colIndex++]; @@ -215,24 +294,6 @@ result.setGearShootingEndLongitude(DEFAULT_EMPTY_LONGITUDE.equals(endVesselPosition.getLongitude())?null:endVesselPosition.getLongitude()); } - // Trawl distance - result.setTrawlDistance((Float)source[colIndex++]); - - // Rectilinear operation ? - result.setFishingOperationRectiligne(enumeration.QUALITATIVE_RECTILINEAR_OPERATION_YES.equals((Integer)source[colIndex++])); - - // Haul valid ? - Integer haulValidQualitativeId = (Integer)source[colIndex++]; - //if (haulValidQualitativeId != null) { - // result.setFishingOperationValid((enumeration.QUALITATIVE_HAUL_VALID_YES.equals(haulValidQualitativeId))); - //} - - // Trawl net number (override the value found in the OP name) - Float trawlNetNumber = (Float)source[colIndex++]; - if (trawlNetNumber != null) { - result.setTrawlNetNumber(trawlNetNumber.intValue()); - } - // Strata : Integer strataId = (Integer)source[colIndex++]; if (strataId != null) { @@ -270,12 +331,10 @@ @Override public FishingOperation createFishingOperation(FishingOperation bean) { - if (bean == null) { - throw new IllegalArgumentException("fishingOperation could not be null"); - } - if (bean.getCruise() == null || bean.getCruise().getId() == null) { - throw new IllegalArgumentException("fishingOperation.getCruise() could not be null"); - } + Preconditions.checkNotNull(bean); + Preconditions.checkNotNull(bean.getCruise()); + Preconditions.checkNotNull(bean.getCruise().getId()); + getCurrentSession().setFlushMode(FlushMode.COMMIT); fr.ifremer.adagio.core.dao.data.operation.FishingOperation fishingOperation = fr.ifremer.adagio.core.dao.data.operation.FishingOperation.Factory.newInstance(); beanToEntity(bean, fishingOperation, true); @@ -287,15 +346,11 @@ @Override public FishingOperation saveFishingOperation(FishingOperation bean) { - if (bean == null) { - throw new IllegalArgumentException("fishingOperation could not be null"); - } - if (bean.getId() == null || bean.getId().isEmpty()) { - throw new IllegalArgumentException("fishingOperation.id could not be null"); - } - if (bean.getCruise() == null || bean.getCruise().getId() == null) { - throw new IllegalArgumentException("fishingOperation.getCruise() could not be null"); - } + Preconditions.checkNotNull(bean); + Preconditions.checkNotNull(bean.getId()); + Preconditions.checkNotNull(bean.getCruise()); + Preconditions.checkNotNull(bean.getCruise().getId()); + getCurrentSession().clear(); getCurrentSession().setFlushMode(FlushMode.COMMIT); fr.ifremer.adagio.core.dao.data.operation.FishingOperation fishingOperation = fishingOperationDao.load(Integer.valueOf(bean.getId())); @@ -383,9 +438,10 @@ String alphanumericalValue = (String)source[colIndex++]; Integer qualitativeValueId = (Integer)source[colIndex++]; - // Trawl distance - if (enumeration.PMFM_ID_TRAWL_NET_NUMBER.equals(pmfmId)) { - result.setTrawlNetNumber(numericalValue.intValue()); + // Trawl net number + if (enumeration.PMFM_ID_MULTIRIG_AGGREGATION.equals(pmfmId)) { + // TODO TC : passer la propriété trawlNetNumber en String + result.setTrawlNetNumber(Integer.valueOf(alphanumericalValue)); } // Gear Shooting Caracteristics @@ -411,6 +467,8 @@ } protected void beanToEntity(FishingOperation source, fr.ifremer.adagio.core.dao.data.operation.FishingOperation target, boolean copyIfNull) { + StringBuffer nameBuffer = new StringBuffer(); + // Retrieve entities : FishingTrip and ScientificCruise ScientificCruise scientificCruise = null; FishingTrip fishingTrip = target.getFishingTrip(); @@ -494,6 +552,7 @@ } else { gearPhysicalFeatures.getOperations().add(target); } + nameBuffer.append(source.getGear().getLabel()); } // Retrieve entities : Fishing Area @@ -510,63 +569,53 @@ } else { fishingArea = gearUseFeatures.getFishingAreas().iterator().next(); // Reset all other fishing areas - } + } + // Retrieve entities : CatchBatch + /*CatchBatch catchBatch = target.getCatchBatch(); + if (catchBatch == null) { + catchBatch = CatchBatch.Factory.newInstance(); + catchBatch.setFishingOperation(target); + target.setCatchBatch(catchBatch); + }*/ + // Retrieve trawl net, from Gear physical features int trawlNet = 1; // default value - GearPhysicalMeasurement gpmTrawlNet = measurementService.getGearPhysicalMeasurement(gearPhysicalFeatures, enumeration.PMFM_ID_TRAWL_NET); + GearPhysicalMeasurement gpmTrawlNet = measurementService.getGearPhysicalMeasurement(gearPhysicalFeatures, enumeration.PMFM_ID_MULTIRIG_NUMBER); if (gpmTrawlNet != null && gpmTrawlNet.getNumericalValue() != null) { trawlNet = gpmTrawlNet.getNumericalValue().intValue(); - } + } - StringBuffer nameBuffer = new StringBuffer(); - // StationNumber if (copyIfNull && source.getStationNumber() == null) { - //setVesselUseMeasurement(scientificCruise, vesselUseFeatures, enumeration.PMFM_ID_STATION_NUMBER, null, "", null); + // Nothing to do : will be removed using the list notChangedVesselUseMeasurements } else if (source.getStationNumber() != null) { VesselUseMeasurement vum = setVesselUseMeasurement(scientificCruise, vesselUseFeatures, enumeration.PMFM_ID_STATION_NUMBER, null, source.getStationNumber(), null); notChangedVesselUseMeasurements.remove(vum); - - nameBuffer.append(source.getStationNumber()); } // OP N° if (copyIfNull && source.getFishingOperationNumber() == null) { // Leave empty in the name buffer - if (nameBuffer.length() > 0) { - nameBuffer.append(FISHING_OPERATION_NAME_SEPARATOR); - } } else if (source.getFishingOperationNumber() != null) { - if (nameBuffer.length() > 0) { - nameBuffer.append(FISHING_OPERATION_NAME_SEPARATOR); - } nameBuffer.append(source.getFishingOperationNumber()); - } - + } + target.setName(nameBuffer.toString()); + // Trawl net number if (copyIfNull && source.getTrawlNetNumber() == null) { // Nothing to do : will be removed later, using notChangedGearUseMeasurements - if (nameBuffer.length() > 0) { - nameBuffer.append(FISHING_OPERATION_NAME_SEPARATOR); - } } else if (source.getTrawlNetNumber() != null) { + // TODO TC : change the property into String + // TODO BLA : Then parse the String and validate content if (source.getTrawlNetNumber().intValue() > trawlNet) { throw new DataIntegrityViolationException("An operation could not have a 'trawl net number' greater than 'trawl net' defined in the cruise."); } // Store into Gear Use Features - GearUseMeasurement gum = setGearUseMeasurement(scientificCruise, gearUseFeatures, enumeration.PMFM_ID_TRAWL_NET_NUMBER, Float.valueOf(source.getTrawlNetNumber()), null, null); - notChangedGearUseMeasurements.remove(gum); - - // Store into the name attribute : - if (nameBuffer.length() > 0) { - nameBuffer.append(FISHING_OPERATION_NAME_SEPARATOR); - } - nameBuffer.append(source.getTrawlNetNumber()); + GearUseMeasurement gum = setGearUseMeasurement(scientificCruise, gearUseFeatures, enumeration.PMFM_ID_MULTIRIG_AGGREGATION, null, source.getTrawlNetNumber().toString(), null); + notChangedGearUseMeasurements.remove(gum); } - target.setName(nameBuffer.toString()); - // Start date : if (copyIfNull && source.getGearShootingStartDate() == null) { target.setStartDateTime(null); @@ -607,18 +656,11 @@ // Operation is valid ? if (copyIfNull && source.getFishingOperationValid() == null) { - removeVesselUseMeasurement(vesselUseFeatures, enumeration.PMFM_ID_HAUL_VALID); + // Nothing to do : will be removed later, using notChangedVesselUseMeasurements } else if (source.getFishingOperationValid() != null) { VesselUseMeasurement vum = setVesselUseMeasurement(scientificCruise, vesselUseFeatures, enumeration.PMFM_ID_HAUL_VALID, null, null, source.getFishingOperationValid().booleanValue()?enumeration.QUALITATIVE_HAUL_VALID_YES:enumeration.QUALITATIVE_HAUL_VALID_NO); notChangedVesselUseMeasurements.remove(vum); } - - // Comment - if (copyIfNull && source.getComment() == null) { - target.setComments(null); - } else if (source.getComment() != null) { - target.setComments(source.getComment()); - } // Vessel target.setVessel(fishingTrip.getVessel()); @@ -757,8 +799,32 @@ } } - // Removed unecessary Vessel Use Measurement + // Recorder persons + StringBuffer miscDataBuffer = new StringBuffer(); + if (copyIfNull && (source.getSaisisseur() == null || source.getSaisisseur().size() == 0)) { + miscDataBuffer.append(MISC_DATA_RECORDER_PERSONS_TAG); + } else if (source.getSaisisseur() != null && source.getSaisisseur().size() > 0) { + List<Person> persons = source.getSaisisseur(); + miscDataBuffer.append(MISC_DATA_RECORDER_PERSONS_TAG); + for (int i = 0; i < persons.size(); i++) { + if (i > 0) miscDataBuffer.append(','); + miscDataBuffer.append(persons.get(i).getId()); + } + } + // Store misc data into comments + if (copyIfNull && source.getComment() == null) { + // Store only misc data : + target.setComments(miscDataBuffer.toString()); + } else if (source.getComment() != null) { + // Store comment + misc data + target.setComments(source.getComment() + miscDataBuffer.toString()); + } + + // ---------------------------------------------------------------- + // Removed unecessary *UseMeasurement : --- + // ---------------------------------------------------------------- + // Gear shooting Caracteristics CaracteristicMap gearShootingCaracteristics = source.getGearShootingCaracteristics(); if (copyIfNull && gearShootingCaracteristics == null || gearShootingCaracteristics.size() == 0) { @@ -783,6 +849,10 @@ } } + // ---------------------------------------------------------------- + // Fishing Area : Strata, substrata, localite --- + // ---------------------------------------------------------------- + // Fishing Area : Integer statisticalLocationId = null; if (source.getGearShootingStartLatitude() != null && source.getGearShootingStartLongitude() != null) { @@ -980,16 +1050,6 @@ return vesselUseMeasurement; } - protected void removeVesselUseMeasurement(VesselUseFeatures vesselUseFeatures, - Integer pmfmId) { - VesselUseMeasurement vesselUseMeasurement = getVesselUseMeasurement(null, vesselUseFeatures, pmfmId, false); - if (vesselUseMeasurement == null) { - return; - } - vesselUseFeatures.getVesselUseMeasurements().remove(vesselUseMeasurement); - // TOBO BLa : vérifier qu'il ne faut pas dao.delete() en plus - } - protected VesselUseMeasurement setVesselUseMeasurement(ScientificCruise scientificCruise, VesselUseFeatures vesselUseFeatures, Integer pmfmId, Float numericalValue, @@ -1043,7 +1103,14 @@ measurement.setNumericalValue((Float)value); } else if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { - QualitativeValue qv = (QualitativeValue)getCurrentSession().load(QualitativeValueImpl.class, Integer.valueOf((String)value)); + Integer qvId = null; + if (value instanceof Integer) { + qvId = (Integer)value; + } + else { + qvId = Integer.valueOf(value.toString()); + } + QualitativeValue qv = load(QualitativeValueImpl.class, qvId); measurement.setQualitativeValue(qv); } } @@ -1109,13 +1176,17 @@ return gearUseMeasurement; } - protected void removeGearUseMeasurement(GearUseFeatures gearUseFeatures, - Integer pmfmId) { - GearUseMeasurement gearUseMeasurement = getGearUseMeasurement(null, gearUseFeatures, pmfmId, false); - if (gearUseMeasurement == null) { - return; - } - gearUseFeatures.getGearUseMeasurements().remove(gearUseMeasurement); - // TOBO BLa : vérifier qu'il ne faut pas dao.delete() en plus + protected DenormalizedBatch getDenormalizedBatch(Integer fishingOperationId) { + Iterator<DenormalizedBatch> list = queryListTyped( + "fishingOperationBatchs", + "fishingOperationId", IntegerType.INSTANCE, Integer.valueOf(fishingOperationId) + ); + + CaracteristicMap environmentCaracteristics = new CaracteristicMap(); + while (list.hasNext()) { + DenormalizedBatch batch = list.next(); + System.out.println(batch.getTreeIndent() + batch.getSortingValuesText()); + } + return null; } } Modified: trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/ProgramPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/ProgramPersistenceServiceImpl.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/ProgramPersistenceServiceImpl.java 2013-01-30 10:39:43 UTC (rev 264) @@ -67,6 +67,8 @@ "program", "programCode", StringType.INSTANCE, id); + if (source == null) return null; + Program result = new Program(); result.setId((String) source[0]); result.setName((String) source[1]); Modified: trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java =================================================================== --- trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceImpl.java 2013-01-30 10:39:43 UTC (rev 264) @@ -24,48 +24,192 @@ * #L% */ -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; -import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.annotation.Resource; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.hibernate.FlushMode; +import org.hibernate.type.IntegerType; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.dao.DataRetrievalFailureException; import org.springframework.stereotype.Service; -import java.util.List; +import com.google.common.base.Preconditions; +import com.google.common.collect.Sets; +import fr.ifremer.adagio.core.dao.administration.user.DepartmentImpl; +import fr.ifremer.adagio.core.dao.data.batch.Batch; +import fr.ifremer.adagio.core.dao.data.batch.BatchImpl; +import fr.ifremer.adagio.core.dao.data.batch.CatchBatch; +import fr.ifremer.adagio.core.dao.data.batch.CatchBatchDao; +import fr.ifremer.adagio.core.dao.data.batch.CatchBatchImpl; +import fr.ifremer.adagio.core.dao.data.batch.SortingBatch; +import fr.ifremer.adagio.core.dao.data.batch.SortingBatchDao; +import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatch; +import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchDao; +import fr.ifremer.adagio.core.dao.data.batch.denormalized.DenormalizedBatchImpl; +import fr.ifremer.adagio.core.dao.data.measure.Measurement; +import fr.ifremer.adagio.core.dao.data.measure.QuantificationMeasurement; +import fr.ifremer.adagio.core.dao.data.measure.SortingMeasurement; +import fr.ifremer.adagio.core.dao.data.measure.VesselUseMeasurement; +import fr.ifremer.adagio.core.dao.data.operation.FishingOperationImpl; +import fr.ifremer.adagio.core.dao.data.survey.scientificCruise.ScientificCruise; +import fr.ifremer.adagio.core.dao.data.vessel.feature.use.VesselUseFeatures; +import fr.ifremer.adagio.core.dao.referential.QualityFlagImpl; +import fr.ifremer.adagio.core.dao.referential.pmfm.PmfmImpl; +import fr.ifremer.adagio.core.dao.referential.pmfm.QualitativeValue; +import fr.ifremer.adagio.core.dao.referential.pmfm.QualitativeValueImpl; +import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxon; +import fr.ifremer.adagio.core.dao.referential.taxon.ReferenceTaxonImpl; +import fr.ifremer.adagio.core.dao.technical.synchronization.SynchronizationStatus; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatchFrequency; +import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; +import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType; +import fr.ifremer.tutti.persistence.entities.referential.Species; + /** * @author tchemit <chemit@codelutin.com> * @since 0.3 */ @Service("speciesBatchPersistenceService") -public class SpeciesBatchPersistenceServiceImpl extends AbstractPersistenceService implements SpeciesBatchPersistenceService { +public class SpeciesBatchPersistenceServiceImpl extends + AbstractPersistenceService implements SpeciesBatchPersistenceService { /** Logger. */ - private static final Log log = - LogFactory.getLog(SpeciesBatchPersistenceServiceImpl.class); + private static final Log log = LogFactory + .getLog(SpeciesBatchPersistenceServiceImpl.class); + @Resource(name = "referentialPersistenceService") + protected ReferentialPersistenceService referentialService; + + @Resource(name = "denormalizedBatchDao") + protected DenormalizedBatchDao denormalizedBatchDao; + + @Resource(name = "sortingBatchDao") + protected SortingBatchDao sortingBatchDao; + + @Resource(name = "catchBatchDao") + protected CatchBatchDao catchBatchDao; + @Override public List<SpeciesBatch> getAllRootSpeciesBatch(String fishingOperationId) { - return null; + return null; } @Override public List<SpeciesBatch> getAllSpeciesBatch(String fishingOperationId) { - return null; + return null; } @Override public SpeciesBatch getSpeciesBatch(String id) { - return null; + Object[] source = queryUnique("speciesBatch", + "batchId", IntegerType.INSTANCE, Integer.valueOf(id)); + + if (source == null) { + throw new DataRetrievalFailureException("Could not retrieve speciesBatch with id=" + id); + } + SpeciesBatch result = new SpeciesBatch(); + result.setId(id); + + int colIndex = 0; + // Individual count + result.setNumber((Integer)source[colIndex++]); + + // Weight & sampleCategory Weight + Float sampleWeight = (Float)source[colIndex++]; + Float samplingRatio = (Float)source[colIndex++]; + String samplingRatioText = (String)source[colIndex++]; + if (samplingRatio == null) { + result.setWeight(sampleWeight); + } + else { + String startStr = sampleWeight.toString().replace(',', '.') + "/"; + if (samplingRatioText != null && samplingRatioText.startsWith(startStr)) { + String weightStr = samplingRatioText.substring(startStr.length()); + if (weightStr != null && !weightStr.isEmpty()) { + result.setSampleCategoryWeight(sampleWeight); + result.setWeight(Float.parseFloat(weightStr)); + } + } + } + + // Comments + result.setComment((String)source[colIndex++]); + + // Sample category type + Integer pmfmId = (Integer)source[colIndex++]; + if (pmfmId != null) { + SampleCategoryEnum sampleCategory = pmfmId2SampleCategory(pmfmId); + result.setSampleCategoryType(sampleCategory); + } + + // Sample category value + Integer qvValue = (Integer)source[colIndex++]; + Float numValue = (Float)source[colIndex++]; + String alphaValue = (String)source[colIndex++]; + Serializable value = (qvValue!=null)?qvValue.toString():((numValue!=null)?numValue:alphaValue); + result.setSampleCategoryValue(value); + + // Species + Integer referenceTaxonId = (Integer)source[colIndex++]; + if (referenceTaxonId !=null) { + Species species = new Species(); + species.setId(referenceTaxonId.toString()); + result.setSpecies(species); + } + + return result; } @Override - public SpeciesBatch createSpeciesBatch(SpeciesBatch bean, String parentBatchId) { - return null; + public SpeciesBatch createSpeciesBatch(SpeciesBatch bean, + String parentBatchId) { + Preconditions.checkNotNull(bean); + Preconditions.checkArgument(bean.getId() == null); + Preconditions.checkNotNull(bean.getSpecies()); + Preconditions.checkNotNull(bean.getSpecies().getId()); + + SortingBatch batch = SortingBatch.Factory.newInstance(); + beanToEntity(bean, batch, parentBatchId, true); + batch = sortingBatchDao.create(batch); + + // DenormalizedBatch denormalizedBatch = + // DenormalizedBatch.Factory.newInstance(); + // denormalizedBatch.setId((long)batch.getId()); + // beanToEntity(bean, denormalizedBatch, parentBatchId, true); + // denormalizedBatchDao.create(denormalizedBatch); + + bean.setId(String.valueOf(batch.getId())); + return bean; } @Override public SpeciesBatch saveSpeciesBatch(SpeciesBatch bean) { - return null; + Preconditions.checkNotNull(bean); + Preconditions.checkNotNull(bean.getId()); + + getCurrentSession().clear(); + getCurrentSession().enableFetchProfile("batch-with-measurements"); + getCurrentSession().setFlushMode(FlushMode.COMMIT); + SortingBatch batch = sortingBatchDao.load(Integer.valueOf(bean.getId())); + String parentBatchId = null; + if (bean.getParentBatch() != null) { + parentBatchId=bean.getParentBatch().getId(); + } + beanToEntity(bean, batch, parentBatchId, true); + sortingBatchDao.update(batch); + getCurrentSession().flush(); + return bean; } @Override @@ -77,12 +221,450 @@ } @Override - public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency(String speciesBatchId) { - return null; + public List<SpeciesBatchFrequency> getAllSpeciesBatchFrequency( + String speciesBatchId) { + return null; } @Override - public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency(String speciesBatchId, List<SpeciesBatchFrequency> frequencies) { - return null; + public List<SpeciesBatchFrequency> saveSpeciesBatchFrequency( + String speciesBatchId, List<SpeciesBatchFrequency> frequencies) { + return null; } + + // ------------------------------------------------------------------------// + // -- Internal methods --// + // ------------------------------------------------------------------------// + protected void beanToEntity(SpeciesBatch source, SortingBatch target, String parentBatchId, boolean copyIfNull) { + Preconditions.checkNotNull(source.getFishingOperation()); + Preconditions.checkNotNull(source.getFishingOperation().getId()); + + // Retrieve recorder department + // TODO BLA : prendre le service du 1er saisisseur ? + Integer recorderDepartmentId = enumeration.DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT; + + // Retrieve entity Root batch + Integer fishingOperationId = Integer.valueOf(source.getFishingOperation().getId()); + Integer rootBatchId = getRootBatchId(fishingOperationId); + if (rootBatchId == null) { + CatchBatch rootBatch = CatchBatch.Factory.newInstance(); + rootBatch.setFishingOperation(load(FishingOperationImpl.class, fishingOperationId)); + rootBatch.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED)); + rootBatch.setRankOrder((short)1); + rootBatch.setSynchronizationStatus(SynchronizationStatus.DIRTY.getValue()); + rootBatch = catchBatchDao.create(rootBatch); + rootBatchId = rootBatch.getId(); + target.setRootBatch(rootBatch); + + //fr.ifremer.adagio.core.dao.data.operation.FishingOperation operation = load(FishingOperationImpl.class, fishingOperationId); + //operation.setCatchBatch(rootBatch); + getCurrentSession().flush(); + int rowUpdated = queryUpdate("updateFishingOperationCatchBatch", + "fishingOperationId", IntegerType.INSTANCE, fishingOperationId, + "catchBatchId", IntegerType.INSTANCE, rootBatchId); + if (rowUpdated == 0) { + throw new DataIntegrityViolationException("Could not attach catch batch to the given operation : operation was not found."); + } + } + else { + target.setRootBatch(load(CatchBatchImpl.class, Integer.valueOf(rootBatchId))); + } + + // Parent batch + Integer targetParentBatchId = null;; + if (parentBatchId == null || parentBatchId.isEmpty()) { + targetParentBatchId = rootBatchId; + } + else { + targetParentBatchId = Integer.valueOf(parentBatchId); + } + if (copyIfNull && targetParentBatchId == null) { + target.setParentBatch(null); + } + else if (targetParentBatchId != null){ + target.setParentBatch(load(BatchImpl.class, targetParentBatchId)); + } + + // RankOrder + if (target.getRankOrder() == null) { + short rankOrder = (short)1; + if (source.getParentBatch() != null && source.getParentBatch().getChildBatchs() != null) { + // TODO BL : vérifier cela (est-ce que l'item est ajouté à son père AVANT d'être passé au service ?) + rankOrder = (short)source.getParentBatch().getChildBatchs().size(); + } + target.setRankOrder(rankOrder); + } + + // Create lists to store all updates, then remove not updated items + Set<QuantificationMeasurement> notChangedQuantificationMeasurements = new HashSet<QuantificationMeasurement>(); + if (target.getQuantificationMeasurements() != null) { + notChangedQuantificationMeasurements.addAll(target.getQuantificationMeasurements()); + } + Set<SortingMeasurement> notChangedSortingMeasurements = new HashSet<SortingMeasurement>(); + if (target.getSortingMeasurements() != null) { + notChangedSortingMeasurements.addAll(target.getSortingMeasurements()); + } + + // Weight or SampleCategoryWeight + if (copyIfNull && source.getWeight() == null) { + // Nothing to do : will be removed later, using notChangedSortingMeasurements + } + else if (source.getSampleCategoryWeight() != null){ + QuantificationMeasurement quantificationMeasurement = setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getSampleCategoryWeight(), true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + else if (source.getWeight() != null){ + QuantificationMeasurement quantificationMeasurement = setQuantificationMeasurement(target, enumeration.PMFM_ID_WEIGHT_MEASURED, recorderDepartmentId, source.getWeight(), true); + notChangedQuantificationMeasurements.remove(quantificationMeasurement); + } + + // Sampling Ratio + if (copyIfNull && (source.getSampleCategoryWeight() == null || source.getWeight() == null)) { + target.setSamplingRatio(null); + target.setSamplingRatioText(null); + } + else if (source.getSampleCategoryWeight() != null && source.getWeight() != null) { + String samplingRatioText = source.getSampleCategoryWeight() + "/" + source.getWeight(); + samplingRatioText = samplingRatioText.replaceAll(",", "."); + target.setSamplingRatioText(samplingRatioText); + target.setSamplingRatio(source.getSampleCategoryWeight().floatValue() / source.getWeight().floatValue()); + } + + // SampleCategoryWeight + if (copyIfNull && (source.getSampleCategoryType() == null || source.getSampleCategoryValue() == null)) { + // Nothing to do : will be removed later, using notChangedSortingMeasurements + } + else if (source.getSampleCategoryType() != null && source.getSampleCategoryValue() != null) { + SortingMeasurement sortingMeasurement = setSortingMeasurement(target, recorderDepartmentId, source.getSampleCategoryType(), source.getSampleCategoryValue()); + notChangedSortingMeasurements.remove(sortingMeasurement); + } + + // Individual count + if (copyIfNull && source.getNumber() == null) { + target.setIndividualCount(null); + } + else if (source.getNumber() != null){ + target.setIndividualCount(source.getNumber()); + } + + // Species + if (copyIfNull && (source.getSpecies() == null || parentBatchId != null)) { + target.setReferenceTaxon(null); + } + else if (source.getSpecies() != null && parentBatchId == null){ + ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, Integer.valueOf(source.getSpecies().getId())); + target.setReferenceTaxon(referenceTaxon); + } + + // QualityFlag + if (source.isSpeciesToConfirm()) { + target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_DOUBTFUL)); + } + else { + target.setQualityFlag(load(QualityFlagImpl.class, enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED)); + } + + // Comments + if (copyIfNull && source.getComment() == null) { + target.setComments(null); + } + else if (source.getComment() != null){ + target.setComments(source.getComment()); + } + + // Removed not changed measurements (in sorting and quantification measurement lists) + if (target.getQuantificationMeasurements() != null && notChangedQuantificationMeasurements.size() > 0) { + for (QuantificationMeasurement qm : notChangedQuantificationMeasurements) { + target.getQuantificationMeasurements().remove(qm); + } + } + if (target.getSortingMeasurements() != null && notChangedSortingMeasurements.size() > 0) { + for (SortingMeasurement sm : notChangedSortingMeasurements) { + target.getSortingMeasurements().remove(sm); + } + } + } + + protected void beanToEntity(SpeciesBatch source, DenormalizedBatch target, + String parentBatchId, boolean copyIfNull) { + + // Parent batch + if (copyIfNull && parentBatchId == null) { + target.setParentBatch(null); + ; + } else if (parentBatchId != null) { + target.setParentBatch(load(DenormalizedBatchImpl.class, + Integer.valueOf(parentBatchId))); + } + + // Weight + if (copyIfNull && source.getWeight() == null) { + target.setWeight(null); + } else if (source.getWeight() != null) { + target.setWeight(source.getWeight()); + } + + // SampleCategoryWeight + if (copyIfNull + && (source.getSampleCategoryWeight() == null || source + .getWeight() == null)) { + target.setSamplingRatio(null); + target.setSamplingRatioText(null); + } else if (source.getSampleCategoryWeight() != null + && source.getWeight() != null) { + String samplingRatioText = source.getSampleCategoryWeight() + "/" + + source.getWeight(); + samplingRatioText = samplingRatioText.replaceAll(",", "."); + target.setSamplingRatioText(samplingRatioText); + target.setSamplingRatio(source.getSampleCategoryWeight() + .floatValue() / source.getWeight().floatValue()); + } + + // Rank order + if (copyIfNull && source.getNumber() == null) { + target.setRankOrder(null); + target.setFlatRankOrder(null); + } else if (source.getNumber() != null) { + target.setRankOrder(Short.valueOf(source.getNumber().toString())); + } + + // Flat rank order + target.setFlatRankOrder(target.getRankOrder()); + + // Tree level + if (parentBatchId == null) { + // TODO BLA : à confirmer une fois l'arbre d'échantillonnage créé + target.setTreeLevel((short) 2); + } else { + short treeLevel = 1; + SpeciesBatch item = source; + do { + treeLevel++; + item = item.getParentBatch(); + } while (item != null); + target.setTreeLevel(treeLevel); + } + + // Species + if (copyIfNull && source.getSpecies() == null) { + target.setReferenceTaxon(null); + target.setInheritedReferenceTaxon(null); + } else if (source.getSpecies() != null) { + ReferenceTaxon referenceTaxon = load(ReferenceTaxonImpl.class, + Integer.valueOf(source.getSpecies().getId())); + if (source.getParentBatch() == null) { + target.setReferenceTaxon(referenceTaxon); + // TODO BLA : vérifier que sous Allegro on affecte aussi + // inherited quand + // une valeur non héritée a été saisie. + target.setInheritedReferenceTaxon(referenceTaxon); + } else { + target.setInheritedReferenceTaxon(referenceTaxon); + target.setReferenceTaxon(null); + } + } + + // QualityFlag (using SpeciesToConfirm) + if (source.isSpeciesToConfirm()) { + target.setQualityFlag(load(QualityFlagImpl.class, + enumeration.QUALITY_FLAG_CODE_DOUBTFUL)); + } else { + target.setQualityFlag(load(QualityFlagImpl.class, + enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED)); + } + + // Comments + if (copyIfNull && source.getComment() == null) { + target.setComments(null); + } else if (source.getComment() != null) { + target.setComments(source.getComment()); + } + + // Other mandatory properties : + target.setIsLanding(false); + target.setIsDiscard(false); + } + + public Integer getRootBatchId(Integer fishingOperationId) { + Integer catchBatchId = queryUniqueTyped("fishingOperationCatchBatch", + "fishingOperationId", IntegerType.INSTANCE, fishingOperationId); + return catchBatchId; + } + + protected QuantificationMeasurement setQuantificationMeasurement( + Batch batch, Integer pmfmId, Integer recorderDepartmentId, + Float weightValue, boolean isReferenceSorting) { + QuantificationMeasurement quantificationMeasurement = getQuantificationMeasurement( + batch, pmfmId, recorderDepartmentId, true); + + quantificationMeasurement.setNumericalValue(weightValue); + quantificationMeasurement + .setIsReferenceQuantification(isReferenceSorting); + return quantificationMeasurement; + } + + protected QuantificationMeasurement getQuantificationMeasurement( + Batch batch, Integer pmfmId, Integer recorderDepartmentId, + boolean createIfNotExists) { + QuantificationMeasurement quantificationMeasurement = null; + if (batch.getQuantificationMeasurements() != null) { + for (Iterator iterator = batch + .getQuantificationMeasurements().iterator(); iterator + .hasNext();) { + QuantificationMeasurement qm = (QuantificationMeasurement) iterator + .next(); + if (pmfmId.equals(qm.getPmfm().getId())) { + quantificationMeasurement = qm; + break; + } + } + } + if (quantificationMeasurement == null) { + if (!createIfNotExists) { + return null; + } + quantificationMeasurement = QuantificationMeasurement.Factory + .newInstance(); + quantificationMeasurement.setBatch(batch); + if (batch.getQuantificationMeasurements() == null) { + batch.setQuantificationMeasurements(Sets + .newHashSet(quantificationMeasurement)); + } else { + batch.getQuantificationMeasurements().add( + quantificationMeasurement); + } + quantificationMeasurement.setQualityFlag(load( + QualityFlagImpl.class, + enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED)); + quantificationMeasurement.setDepartment(load(DepartmentImpl.class, + recorderDepartmentId)); + quantificationMeasurement.setPmfm(load(PmfmImpl.class, pmfmId)); + } + + return quantificationMeasurement; + } + + protected void setMeasurement(Measurement measurement, Caracteristic caracteristic, Serializable value) { + if (caracteristic.getCaracteristicType() == CaracteristicType.TEXT) { + measurement.setAlphanumericalValue((String)value); + } + else if (caracteristic.getCaracteristicType() == CaracteristicType.NUMBER) { + measurement.setNumericalValue((Float)value); + } + else if (caracteristic.getCaracteristicType() == CaracteristicType.QUALITATIVE) { + Integer qvId = null; + if (value instanceof Integer) { + qvId = (Integer)value; + } + else { + qvId = Integer.valueOf(value.toString()); + } + QualitativeValue qv = load(QualitativeValueImpl.class, qvId); + measurement.setQualitativeValue(qv); + } + } + + protected SortingMeasurement setSortingMeasurement( + SortingBatch sortingBatch, Integer recorderDepartmentId, + SampleCategoryEnum sampleCategory, Serializable value) { + Preconditions.checkNotNull(sampleCategory); + Preconditions.checkNotNull(value); + + Integer pmfmId = sampleCategory2PmfmId(sampleCategory); + + Caracteristic caracteristic = referentialService.getCaracteristic(pmfmId); + SortingMeasurement sortingMeasurement = getSortingMeasurement( + sortingBatch, pmfmId, recorderDepartmentId, true); + setMeasurement(sortingMeasurement, caracteristic, value); + return sortingMeasurement; + } + + protected SortingMeasurement getSortingMeasurement( + SortingBatch sortingBatch, Integer pmfmId, Integer recorderDepartmentId, + boolean createIfNotExists) { + SortingMeasurement sortingMeasurement = null; + if (sortingBatch.getSortingMeasurements() != null) { + for (Iterator iterator = sortingBatch + .getSortingMeasurements().iterator(); iterator + .hasNext();) { + SortingMeasurement qm = (SortingMeasurement) iterator + .next(); + if (pmfmId.equals(qm.getPmfm().getId())) { + sortingMeasurement = qm; + break; + } + } + } + if (sortingMeasurement == null) { + if (!createIfNotExists) { + return null; + } + sortingMeasurement = SortingMeasurement.Factory + .newInstance(); + sortingMeasurement.setSortingBatch(sortingBatch); + if (sortingBatch.getSortingMeasurements() == null) { + sortingBatch.setSortingMeasurements(Sets + .newHashSet(sortingMeasurement)); + sortingMeasurement.setRankOrder(1); + } else { + sortingBatch.getSortingMeasurements().add( + sortingMeasurement); + sortingMeasurement.setRankOrder(sortingBatch.getSortingMeasurements().size()); + } + sortingMeasurement.setQualityFlag(load( + QualityFlagImpl.class, + enumeration.QUALITY_FLAG_CODE_NOT_QUALIFIED)); + sortingMeasurement.setDepartment(load(DepartmentImpl.class, + recorderDepartmentId)); + sortingMeasurement.setPmfm(load(PmfmImpl.class, pmfmId)); + } + + return sortingMeasurement; + } + + protected Integer sampleCategory2PmfmId(SampleCategoryEnum sampleCategory) { + Integer pmfmId = null; + if (sampleCategory == SampleCategoryEnum.sortedUnsorted) { + pmfmId = enumeration.PMFM_ID_SORTED_UNSORTED; + } + else if (sampleCategory == SampleCategoryEnum.size) { + pmfmId = enumeration.PMFM_ID_SIZE_CATEGORY; + } + else if (sampleCategory == SampleCategoryEnum.maturity) { + pmfmId = enumeration.PMFM_ID_MATURITY; + } + else if (sampleCategory == SampleCategoryEnum.sex) { + pmfmId = enumeration.PMFM_ID_SEX; + } + else if (sampleCategory == SampleCategoryEnum.age) { + pmfmId = enumeration.PMFM_ID_AGE; + } + if (pmfmId == null) { + throw new IllegalArgumentException("Unable to find corresponding PMFM.ID for sampleCategory : " + sampleCategory.name()); + } + return pmfmId; + } + + protected SampleCategoryEnum pmfmId2SampleCategory(Integer pmfmId) { + SampleCategoryEnum sampleCategory = null; + if (pmfmId.intValue() == enumeration.PMFM_ID_SORTED_UNSORTED.intValue()) { + sampleCategory = SampleCategoryEnum.sortedUnsorted; + } + else if (enumeration.PMFM_ID_SIZE_CATEGORY.equals(pmfmId)) { + sampleCategory = SampleCategoryEnum.size; + } + else if (enumeration.PMFM_ID_MATURITY.equals(pmfmId)) { + sampleCategory = SampleCategoryEnum.maturity; + } + else if (enumeration.PMFM_ID_SEX.equals(pmfmId)) { + sampleCategory = SampleCategoryEnum.sex; + } + else if (enumeration.PMFM_ID_AGE.equals(pmfmId)) { + sampleCategory = SampleCategoryEnum.age; + } + if (sampleCategory == null) { + throw new IllegalArgumentException("Unable to find corresponding SampleCategoryEnum for PMFM.ID : " + pmfmId); + } + return sampleCategory; + } } Modified: trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java =================================================================== --- trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/java/fr/ifremer/tutti/persistence/service/TuttiEnumerationFile.java 2013-01-30 10:39:43 UTC (rev 264) @@ -125,6 +125,9 @@ @Value("${QualityFlagCode.NOTQUALIFIED}") public final String QUALITY_FLAG_CODE_NOT_QUALIFIED = null; + @Value("${QualityFlagCode.DOUBTFUL}") + public final String QUALITY_FLAG_CODE_DOUBTFUL = null; + @Value("${PmfmId.STATION_NUMBER}") public final Integer PMFM_ID_STATION_NUMBER = null; @@ -149,12 +152,25 @@ @Value("${QualitativeValueId.HAUL_VALID_NO}") public final Integer QUALITATIVE_HAUL_VALID_NO = null; - @Value("${PmfmId.TRAWL_NET}") - public final Integer PMFM_ID_TRAWL_NET = null; + @Value("${PmfmId.MULTIRIG_NUMBER}") + public final Integer PMFM_ID_MULTIRIG_NUMBER = null; - @Value("${PmfmId.TRAWL_NET_NUMBER}") - public final Integer PMFM_ID_TRAWL_NET_NUMBER = null; + @Value("${PmfmId.MULTIRIG_AGGREGATION}") + public final Integer PMFM_ID_MULTIRIG_AGGREGATION = null; + @Value("${PmfmId.WEIGHT_MEASURED}") + public final Integer PMFM_ID_WEIGHT_MEASURED = null; + + @Value("${DepartmentId.UNKNOWN_RECORDER_DEPARTMENT}") + public final Integer DEPARTMENT_ID_UNKNOWN_RECORDER_DEPARTMENT = null; + + @Value("${VesselPersonRoleId.CRUISE_MANAGER}") + public final Integer VESSEL_PERSON_ROLE_ID_CRUISE_MANAGER = null; + + + @Value("${PmfmId.AGE}") + public final Integer PMFM_ID_AGE = null; + public void init() { Field[] declaredFields = getClass().getDeclaredFields(); Modified: trunk/tutti-persistence-adagio/src/main/resources/queries-override.hbm.xml =================================================================== --- trunk/tutti-persistence-adagio/src/main/resources/queries-override.hbm.xml 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/resources/queries-override.hbm.xml 2013-01-30 10:39:43 UTC (rev 264) @@ -27,10 +27,6 @@ "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> - <!--<fetch-profile name="tutti">--> - <!--TODO Create fetch profile to avoid eager loading --> - <!--</fetch-profile>--> - <!-- ===================================================================== --> <!-- === Requete sur données thématiques [DAT-XXX] === --> <!-- ===================================================================== --> @@ -168,27 +164,44 @@ <query-param name="cruiseId" type="java.lang.Integer"/> </query> + <query cacheable="true" name="allFishingOperations"> + <![CDATA[ + SELECT + o.id AS id, + o.name AS name, + guf.gear.label AS gearLabel, + o.startDateTime AS startDateTime, + (select vum.alphanumericalValue from VesselUseMeasurementImpl vum where vum.vesselUseFeatures.id = vuf.id and vum.pmfm.id=1243) AS stationNumber, + (select gum.numericalValue from GearUseMeasurementImpl gum where gum.gearUseFeatures.id = guf.id and gum.pmfm.id=953) AS trawNetNumber + FROM + FishingOperationImpl o + LEFT OUTER JOIN o.gearUseFeatures guf + LEFT OUTER JOIN o.vesselUseFeatures vuf + WHERE + o.fishingTrip.scientificCruise.id=:cruiseId + ORDER BY + o.startDateTime + ]]> + <query-param name="cruiseId" type="java.lang.Integer"/> + </query> + <query cacheable="true" name="fishingOperation"> <![CDATA[ SELECT - o.name as name, - max(o.startDateTime) as startDateTime, - max(o.endDateTime) as endDateTime, - max(o.comments) as comments, - max(guf.gear.id) as gearId, - (select vp_start from VesselPositionImpl vp_start where vp_start.operation.id = o.id and vp_start.dateTime = o.startDateTime) as startVesselPosition, - (select vp_end from VesselPositionImpl vp_end where vp_end.operation.id = o.id and vp_end.dateTime = o.endDateTime) as endVesselPosition, - (select vum.numericalValue from VesselUseMeasurementImpl vum where vum.vesselUseFeatures.id=vuf.id and vum.pmfm.id=:pmfmIdTrawlDistance) as trawlDistance, - (select vum2.qualitativeValue.id from VesselUseMeasurementImpl vum2 where vum2.vesselUseFeatures.id=vuf.id and vum2.pmfm.id=:pmfmIdRectilinearOperation) as rectilinearQualitativeId, - (select vum3.qualitativeValue.id from VesselUseMeasurementImpl vum3 where vum3.vesselUseFeatures.id=vuf.id and vum3.pmfm.id=:pmfmIdHaulValid) as haulValidQualitativeId, - (select gum.numericalValue from GearUseMeasurementImpl gum where gum.gearUseFeatures.id=guf.id and gum.pmfm.id=:pmfmIdTrawlNetNumber) as trawlNetNumber, + o.name AS name, + max(guf.gear.label) AS gearLabel, + max(o.startDateTime) AS startDateTime, + max(o.endDateTime) AS endDateTime, + max(o.comments) AS comments, + max(guf.gear.id) AS gearId, + (select vp_start from VesselPositionImpl vp_start where vp_start.operation.id = o.id and vp_start.dateTime = o.startDateTime) AS startVesselPosition, + (select vp_end from VesselPositionImpl vp_end where vp_end.operation.id = o.id and vp_end.dateTime = o.endDateTime) AS endVesselPosition, max(case when (rl.locationLevel.id = :locationLevelIdStrata) then rl.id else null end) AS strataId, max(case when (rl.locationLevel.id = :locationLevelIdSubStrata) then rl.id else null end) AS subStrataId, max(case when (rl.locationLevel.id = :locationLevelIdLocalite) then rl.id else null end) AS localiteId FROM FishingOperationImpl o INNER JOIN o.gearUseFeatures guf - INNER JOIN o.vesselUseFeatures vuf LEFT OUTER JOIN guf.fishingAreas fa LEFT OUTER JOIN fa.regulationLocation fa2rl LEFT OUTER JOIN fa2rl.id.location rl @@ -197,12 +210,28 @@ GROUP BY o.name ]]> <query-param name="fishingOperationId" type="java.lang.Integer"/> - <query-param name="pmfmIdTrawlDistance" type="java.lang.Integer"/> - <query-param name="pmfmIdRectilinearOperation" type="java.lang.Integer"/> - <query-param name="pmfmIdHaulValid" type="java.lang.Integer"/> - <query-param name="pmfmIdTrawlNetNumber" type="java.lang.Integer"/> + <query-param name="locationLevelIdStrata" type="java.lang.Integer"/> + <query-param name="locationLevelIdSubStrata" type="java.lang.Integer"/> + <query-param name="locationLevelIdLocalite" type="java.lang.Integer"/> </query> + <query cacheable="true" name="fishingOperationRankOrder"> + <![CDATA[ + SELECT + count(o1.id)+1 as fishingOperationRankOrder + FROM + FishingOperationImpl o1, + FishingOperationImpl o2 + WHERE + o1.fishingTrip.id=o2.fishingTrip.id + and o1.startDateTime < o2.startDateTime + and o2.id = :fishingOperationId + ]]> + <query-param name="fishingOperationId" type="java.lang.Integer"/> + </query> + + + <query cacheable="true" name="fishingOperationEnvironment"> <![CDATA[ SELECT @@ -214,7 +243,7 @@ VesselUseFeaturesImpl vuf join vuf.vesselUseMeasurements vum WHERE - vuf.operation = :fishingOperationId + vuf.operation.id = :fishingOperationId ]]> <query-param name="fishingOperationId" type="java.lang.Integer"/> </query> @@ -230,10 +259,75 @@ GearUseFeaturesImpl guf join guf.gearUseMeasurements gum WHERE - guf.operation = :fishingOperationId + guf.operation.id = :fishingOperationId ]]> <query-param name="fishingOperationId" type="java.lang.Integer"/> </query> + + <query name="updateFishingOperationCatchBatch"> + <![CDATA[ + UPDATE FishingOperationImpl o + SET o.catchBatch.id=:catchBatchId + WHERE + o.id=:fishingOperationId + ]]> + <query-param name="fishingOperationId" type="java.lang.Integer"/> + <query-param name="catchBatchId" type="java.lang.Integer"/> + </query> + + <query cacheable="true" name="fishingOperationCatchBatch"> + <![CDATA[ + SELECT + cb.id + FROM + CatchBatchImpl cb + WHERE + cb.fishingOperation.id = :fishingOperationId + ]]> + <query-param name="fishingOperationId" type="java.lang.Integer"/> + </query> + + <!--query cacheable="true" name="allFishingOperationBatchs"> + <![CDATA[ + select + db.id + from + BatchImpl db + WHERE + db.id = :fishingOperationId + ORDER BY + db.flatRankOrder + ]]> + <query-param name="fishingOperationId" type="java.lang.Integer"/> + </query--> + + <query cacheable="true" name="speciesBatch"> + <![CDATA[ + SELECT + b.individualCount AS individualCount, + qm.numericalValue AS weight, + b.samplingRatio AS samplingRatio, + b.samplingRatioText AS samplingRatioText, + b.comments AS comments, + sm.pmfm.id as pmfmId, + sm.qualitativeValue.id as qvValue, + sm.numericalValue AS numValue, + sm.alphanumericalValue AS alphaValue, + b.referenceTaxon.id as referenceTaxonId + FROM + SortingBatchImpl b + LEFT OUTER JOIN b.sortingMeasurements sm + LEFT OUTER JOIN b.quantificationMeasurements qm + WHERE + b.id = :batchId + AND ( + qm is null + OR qm.isReferenceQuantification=true + ) + ]]> + <query-param name="batchId" type="java.lang.Integer"/> + </query> + <!-- ===================================================================== --> <!-- === Requete techniques sur référentiels [REF-TXXX] === --> @@ -398,22 +492,12 @@ WHERE v.vesselType.id = :vesselTypeId AND v.status.code IN (:statusValidCode, :statusTemporaryCode) - AND vrp.vesselRegistrationPeriodPk.startDateTime = - ( - SELECT MAX(vrp2.vesselRegistrationPeriodPk.startDateTime) - FROM VesselRegistrationPeriodImpl vrp2 WHERE - vrp2.vesselRegistrationPeriodPk.vessel.code = v.code - AND (vrp2.vesselRegistrationPeriodPk.startDateTime <= :refDate OR :refDate IS NULL) - GROUP BY vrp2.vesselRegistrationPeriodPk.vessel.code + AND NOT(coalesce(vrp.endDateTime, '2999-12-31 00:00:00') < coalesce(:refDate,sysdate) + OR vrp.vesselRegistrationPeriodPk.startDateTime > coalesce(:refDate,sysdate) ) - AND vf.startDateTime = - ( - SELECT MAX(vf2.startDateTime) - FROM VesselFeaturesImpl vf2 WHERE - vf2.vessel.code = v.code - AND (vf2.startDateTime <= :refDate OR :refDate IS NULL) - GROUP BY vf2.vessel.code - ) + AND NOT(coalesce(vf.endDateTime, '2999-12-31 00:00:00') < coalesce(:refDate,sysdate) + OR vf.startDateTime > coalesce(:refDate,sysdate) + ) ]]> <query-param name="vesselTypeId" type="java.lang.Integer"/> <query-param name="refDate" type="java.util.Date"/> @@ -596,4 +680,20 @@ <query-param name="statusTemporaryCode" type="java.lang.String"/> </query> + <!-- ===================================================================== --> + <!-- === Fetch profiles === --> + <!-- ===================================================================== --> + + + <!--<fetch-profile name="tutti">--> + <!--TODO Create fetch profile to avoid eager loading --> + <!--</fetch-profile>--> + + <fetch-profile name="batch-with-measurements"> + <fetch entity="CatchBatchImpl" association="quantificationMeasurements" style="join"/> + <fetch entity="SortingBatchImpl" association="sortingMeasurements" style="join"/> + <fetch entity="SortingBatchImpl" association="quantificationMeasurements" style="join"/> + </fetch-profile> + + </hibernate-mapping> Modified: trunk/tutti-persistence-adagio/src/main/resources/tutti-db-conf.properties =================================================================== --- trunk/tutti-persistence-adagio/src/main/resources/tutti-db-conf.properties 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/resources/tutti-db-conf.properties 2013-01-30 10:39:43 UTC (rev 264) @@ -43,4 +43,5 @@ hibernate.use_sql_comments=${tutti.persistence.hibernate.useSqlComment} hibernate.generate_statistics=false hibernate.query.substitutions=true 1, false 0 -hibernate.hbm2ddl.auto=none \ No newline at end of file +hibernate.hbm2ddl.auto=none +hibernate.default_batch_fetch_size=1 \ No newline at end of file Modified: trunk/tutti-persistence-adagio/src/main/resources/tutti-db-enumerations.properties =================================================================== --- trunk/tutti-persistence-adagio/src/main/resources/tutti-db-enumerations.properties 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/main/resources/tutti-db-enumerations.properties 2013-01-30 10:39:43 UTC (rev 264) @@ -318,6 +318,7 @@ PmfmId.SEX=196 PmfmId.SIZE_CATEGORY=198 PmfmId.SORTED_UNSORTED=200 +PmfmId.AGE=1430 # Catégorie maturité PmfmId.MATURITY=174 @@ -342,15 +343,19 @@ # TODO A creer (dans les enumerations Allegro) QualitativeValueId.RECTILINEAR_OPERATION_NO=278 -# TODO A creer (dans les enumerations Allegro) # PSFM "Nombre de poche" d'un chalut (écran campagne) -PmfmId.TRAWL_NET=953 +PmfmId.MULTIRIG_NUMBER=1420 +# PSFM "Liste des poches observées" (écran opération) +PmfmId.MULTIRIG_AGGREGATION=1424 # TODO A creer (dans les enumerations Allegro) -# PSFM "Numero de la poche" (écran opération) -## ATTENTION : à modifier quand Vincent aura créé le PSFM -PmfmId.TRAWL_NET_NUMBER=953 +# PSFM "Poids - observation par une observateur" (écran captures, onglet espèce, benthos, etc) +PmfmId.WEIGHT_MEASURED=220 #TODO A creer (dans les enumerations Allegro) # (20=observateur volant, 95=Administrateur SIH) -> L'avantage du 20 est qu'il est inactif (=20), donc plus facilement detectable PersonId.UNKNOWN_RECORDER_PERSON=20 + +#TODO A creer (dans les enumerations Allegro) +# 181=PDG-RBE (à confirmer par Vincent) +DepartmentId.UNKNOWN_RECORDER_DEPARTMENT=181 Modified: trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceTest.java =================================================================== --- trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceTest.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/CruisePersistenceServiceTest.java 2013-01-30 10:39:43 UTC (rev 264) @@ -128,8 +128,12 @@ cruise.setComment("My comments on cruise"); - Person managerPerson = referentialService.getAllPerson().get(0); - cruise.setHeadOfMission(Lists.newArrayList(managerPerson)); + List<Person> allPersons = referentialService.getAllPerson(); + Person managerPerson1 = allPersons.get(0); + Person managerPerson2 = allPersons.get(1); + cruise.setHeadOfMission(Lists.newArrayList(managerPerson1, managerPerson2)); + + cruise.setHeadOfSortRoom(Lists.newArrayList(managerPerson2)); List<Vessel> vessels = Lists.newArrayList(); vessels.add(referentialService.getAllScientificVessel().get(0)); @@ -162,8 +166,12 @@ calendar.set(Calendar.MILLISECOND, 0); assertEquals(calendar.getTime(), reloadedCruise.getEndDate()); assertEquals(cruise.getTrawlNet(), reloadedCruise.getTrawlNet()); + assertNotNull(reloadedCruise.getHeadOfMission()); + assertEquals(cruise.getHeadOfMission().size(), reloadedCruise.getHeadOfMission().size()); + assertNotNull(reloadedCruise.getHeadOfSortRoom()); + assertEquals(cruise.getHeadOfSortRoom().size(), reloadedCruise.getHeadOfSortRoom().size()); - // ----------------------------------------------------------------------------- + // ----------------------------------------------------------------------------- // 2. Test with only mandatory properties // ----------------------------------------------------------------------------- createdCruise.setId(null); Modified: trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceTest.java =================================================================== --- trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceTest.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/FishingOperationPersistenceServiceTest.java 2013-01-30 10:39:43 UTC (rev 264) @@ -39,6 +39,7 @@ import fr.ifremer.tutti.persistence.entities.referential.CaracteristicType; import fr.ifremer.tutti.persistence.entities.referential.FishingOperationLocation; import fr.ifremer.tutti.persistence.entities.referential.Gear; +import fr.ifremer.tutti.persistence.entities.referential.Person; import org.junit.Before; import org.junit.ClassRule; @@ -83,7 +84,7 @@ @Test @Ignore public void getAllFishingOperation(/*String cruiseId*/) { - + } @Test @@ -94,7 +95,9 @@ @Test public void createFishingOperation(/*FishingOperation bean*/) { - // ----------------------------------------------------------------------------- + List<Person> allPersons = referentialService.getAllPerson(); + + // ----------------------------------------------------------------------------- // Prepare data and other entities // ----------------------------------------------------------------------------- Calendar calendar = new GregorianCalendar(); @@ -232,6 +235,17 @@ localite.setId(dbResource.getFixtures().localite()); fishingOperation.setLocation(localite); + fishingOperation.setSaisisseur(Lists.newArrayList(allPersons.get(0), allPersons.get(1))); + + // Capture + fishingOperation.setCatchTotalWeight(100f); + // note : poids vrac caroussel (thalassa) (init par pupitri) (vrac trie) ou bien "poids trié fournie par la table de tri (Sum(Si) + //fishingOperation.setCatchTotalSortedCarousselWeight(20f); + // note : poids trie par la balance tremis (thalassa) (init par pupitri) + //fishingOperation.setCatchTotalSortedTremisWeight(10f); + //fishingOperation.setCatchTotalUnsortedWeight(15f); + + // Store fishing operation into database : createdFishingOperation = service.createFishingOperation(fishingOperation); assertNotNull("Fishing operation ID must not be null after creation in database", createdFishingOperation); @@ -271,6 +285,12 @@ assertNotNull(reloadedFishingOperation.getLocation()); assertNotNull(reloadedFishingOperation.getLocation().getId()); assertEquals(fishingOperation.getLocation().getId(), reloadedFishingOperation.getLocation().getId()); + + //TODO BL : move into CatchBacth + //assertEquals(fishingOperation.getCatchTotalWeight(), reloadedFishingOperation.getCatchTotalWeight()); + + assertNotNull(reloadedFishingOperation.getSaisisseur()); + assertEquals(fishingOperation.getSaisisseur().size(), reloadedFishingOperation.getSaisisseur().size()); // ----------------------------------------------------------------------------- // 3. Test : Modified: trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceTest.java =================================================================== --- trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceTest.java 2013-01-30 09:56:33 UTC (rev 263) +++ trunk/tutti-persistence-adagio/src/test/java/fr/ifremer/tutti/persistence/service/SpeciesBatchPersistenceServiceTest.java 2013-01-30 10:39:43 UTC (rev 264) @@ -24,32 +24,91 @@ * #L% */ +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; + import fr.ifremer.tutti.persistence.DatabaseResource; +import fr.ifremer.tutti.persistence.entities.data.Cruise; +import fr.ifremer.tutti.persistence.entities.data.FishingOperation; +import fr.ifremer.tutti.persistence.entities.data.SampleCategoryEnum; +import fr.ifremer.tutti.persistence.entities.data.SpeciesBatch; +import fr.ifremer.tutti.persistence.entities.referential.Caracteristic; +import fr.ifremer.tutti.persistence.entities.referential.Species; + import org.junit.Before; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Test; +import static org.junit.Assert.*; /** * @author tchemit <chemit@codelutin.com> * @since 0.3 */ -@Ignore public class SpeciesBatchPersistenceServiceTest { @ClassRule public static final DatabaseResource dbResource = new DatabaseResource(); protected SpeciesBatchPersistenceService service; + + protected CruisePersistenceService cruiseService; + protected FishingOperationPersistenceService fishingOperationService; + protected ReferentialPersistenceService referentialService; + protected Cruise cruise; + protected FishingOperation fishingOperation; + protected List<Species> species; + @Before public void setUp() throws Exception { service = TuttiPersistenceServiceLocator.getSpeciesBatchPersistenceService(); + cruiseService = TuttiPersistenceServiceLocator.getCruisePersistenceService(); + fishingOperationService = TuttiPersistenceServiceLocator.getFishingOperationPersistenceService(); + referentialService = TuttiPersistenceServiceLocator.getReferentialPersistenceService(); + + cruise = cruiseService.getCruise(dbResource.getFixtures().cruiseId()); + cruise.setId(null); + Calendar calendar = new GregorianCalendar(); + cruise.setBeginDate(calendar.getTime()); + cruise.setYear(calendar.get(Calendar.YEAR)); + calendar.add(Calendar.MONTH, 1); // add one month + cruise.setEndDate(calendar.getTime()); + cruise = cruiseService.createCruise(cruise); + + List<FishingOperation> fishingOperations = fishingOperationService.getAllFishingOperation(dbResource.getFixtures().cruiseId()); + assertNotNull(fishingOperations); + assertTrue(fishingOperations.size() > 0); + fishingOperation = fishingOperations.get(0); + fishingOperation = fishingOperationService.getFishingOperation(fishingOperation.getId()); + fishingOperation.setId(null); + fishingOperation.setCruise(cruise); + calendar.setTime(new Date()); + calendar.set(Calendar.HOUR_OF_DAY, 1); + calendar.set(Calendar.MILLISECOND, 0); + fishingOperation.setGearShootingStartDate(calendar.getTime()); + calendar.setTime(new Date()); + calendar.set(Calendar.HOUR_OF_DAY, 10); + calendar.set(Calendar.MILLISECOND, 0); + fishingOperation.setGearShootingEndDate(calendar.getTime()); + + fishingOperation = fishingOperationService.createFishingOperation(fishingOperation); + + species = referentialService.getAllSpecies(); + assertNotNull(species); + assertTrue(species.size() > 2); } @Test + @Ignore public void getAllRootSpeciesBatch(/*String fishingOperationId*/) { + List<SpeciesBatch> speciesBatch = service.getAllRootSpeciesBatch(fishingOperation.getId()); + assertNotNull(speciesBatch); + assertTrue(speciesBatch.size() > 0); + } @Test @@ -64,7 +123,107 @@ @Test public void createSpeciesBatch(/*SpeciesBatch bean, String parentBatchId*/) { + Caracteristic sortedUnsortedPMFM = referentialService.getSortedUnsortedCaracteristic(); + String horsVracQualitativeValueId = sortedUnsortedPMFM.getQualitativeValue(0).getId(); + String vracQualitativeValueId = sortedUnsortedPMFM.getQualitativeValue(1).getId(); + Species taxon1 = species.get(0); + Species taxon2 = species.get(1); + Caracteristic sexPMFM = referentialService.getSexCaracteristic(); + String maleQualitativeValueId = sexPMFM.getQualitativeValue(1).getId(); + String femaleQualitativeValueId = sexPMFM.getQualitativeValue(2).getId(); + SpeciesBatch esp1Batch = null; + SpeciesBatch batch = null; + SpeciesBatch createdBatch = null; + SpeciesBatch reloadedBatch = null; + + // ----------------------------------------------------------------------------- + // 1. Test with only mandatory properties + // ----------------------------------------------------------------------------- + // batch : "ESP1 - Vrac/5" + batch = new SpeciesBatch(); + batch.setFishingOperation(fishingOperation); + batch.setSpecies(taxon1); + batch.setSampleCategoryType(SampleCategoryEnum.sortedUnsorted); + batch.setSampleCategoryValue(vracQualitativeValueId); + batch.setWeight(5f); + + createdBatch = service.createSpeciesBatch(batch, null); + assertNotNull(createdBatch); + assertNotNull(createdBatch.getId()); + reloadedBatch = service.getSpeciesBatch(createdBatch.getId()); + assertNotNull(reloadedBatch); + assertNull(reloadedBatch.getFishingOperation()); + assertEquals(createdBatch.getId(), reloadedBatch.getId()); + assertEquals(batch.getWeight(), reloadedBatch.getWeight()); + assertEquals(batch.getNumber(), reloadedBatch.getNumber()); + assertEquals(batch.getComment(), reloadedBatch.getComment()); + assertEquals(batch.getSampleCategoryType(), reloadedBatch.getSampleCategoryType()); + assertEquals(batch.getSampleCategoryValue(), reloadedBatch.getSampleCategoryValue()); + assertNotNull(reloadedBatch.getSpecies()); + assertEquals(batch.getSpecies().getId(), reloadedBatch.getSpecies().getId()); + // Save ESP1 batch + esp1Batch = reloadedBatch; + + // ----------------------------------------------------------------------------- + // 2. Test child "Male/2" + // ----------------------------------------------------------------------------- + // Batch : ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7 + batch.setId(null); + batch.setParentBatch(esp1Batch); + batch.setSpecies(taxon1); + batch.setComment("ESP1 - Vrac/5 Male/2 ss-ech/1 Nombre/7"); + batch.setWeight(2f); + batch.setSampleCategoryType(SampleCategoryEnum.sex); + batch.setSampleCategoryValue(maleQualitativeValueId); + batch.setSampleCategoryWeight(1f); + batch.setNumber(7); + + createdBatch = service.createSpeciesBatch(batch, batch.getParentBatch().getId()); + assertNotNull(createdBatch); + assertNotNull(createdBatch.getId()); + reloadedBatch = service.getSpeciesBatch(createdBatch.getId()); + assertNotNull(reloadedBatch); + assertNull(reloadedBatch.getParentBatch()); + assertEquals(batch.getNumber(), reloadedBatch.getNumber()); + assertEquals(batch.getSampleCategoryType(), reloadedBatch.getSampleCategoryType()); + assertEquals(batch.getSampleCategoryValue(), reloadedBatch.getSampleCategoryValue()); + assertEquals(batch.getWeight(), reloadedBatch.getWeight()); + assertEquals(batch.getSampleCategoryWeight(), reloadedBatch.getSampleCategoryWeight()); + + // ----------------------------------------------------------------------------- + // 3. Test child "Female/2" + // ----------------------------------------------------------------------------- + // Batch : ESP1 - Vrac/5 Female/3 Nombre/14 + batch.setId(null); + batch.setParentBatch(esp1Batch); + batch.setSpecies(taxon1); + batch.setComment("ESP1 - Vrac/5 Female/3 Nombre/14"); + batch.setWeight(3f); + batch.setSampleCategoryType(SampleCategoryEnum.sex); + batch.setSampleCategoryValue(femaleQualitativeValueId); + batch.setSampleCategoryWeight(null); + batch.setNumber(14); + + createdBatch = service.createSpeciesBatch(batch, batch.getParentBatch().getId()); + assertNotNull(createdBatch); + assertNotNull(createdBatch.getId()); + reloadedBatch = service.getSpeciesBatch(createdBatch.getId()); + assertNotNull(reloadedBatch); + assertNull(reloadedBatch.getParentBatch()); + assertEquals(batch.getNumber(), reloadedBatch.getNumber()); + assertEquals(batch.getSampleCategoryType(), reloadedBatch.getSampleCategoryType()); + assertEquals(batch.getSampleCategoryValue(), reloadedBatch.getSampleCategoryValue()); + assertEquals(batch.getWeight(), reloadedBatch.getWeight()); + assertEquals(batch.getSampleCategoryWeight(), reloadedBatch.getSampleCategoryWeight()); + + + /* + reloadedBatch.setSampleCategoryWeight(1.5f); + reloadedBatch.setParentBatch(createdBatch.getParentBatch()); + reloadedBatch.setFishingOperation(fishingOperation); + service.saveSpeciesBatch(reloadedBatch); + */ } @Test
participants (1)
-
blavenier@users.forge.codelutin.com