Tony CHEMIT pushed to branch develop at ultreiaio / ird-t3 Commits: 121988c6 by Tony CHEMIT at 2018-03-07T12:15:41Z Improve test API - - - - - 69e4068c by Tony CHEMIT at 2018-03-07T12:16:19Z clean and improve code - - - - - 8ac03c14 by Tony CHEMIT at 2018-03-07T13:28:28Z [N2][N3] Les calées de type banc indéterminé ne sont pas traitées au N2 et N3 (See #261) - - - - - 11 changed files: - t3-actions/src/main/java/fr/ird/t3/actions/io/input/test/FakeT3AvdthServiceContext.java - t3-actions/src/test/java/fr/ird/t3/models/LengthCompositionModelHelperTest.java - t3-actions/src/test/java/fr/ird/t3/models/WeightCompositionModelHelperTest.java - + t3-domain/src/main/java/fr/ird/t3/actions/stratum/SchoolTypeIndeterminate.java - t3-domain/src/main/java/fr/ird/t3/entities/T3TopiaApplicationContext.java - t3-domain/src/main/java/fr/ird/t3/models/LengthCompositionModelHelper.java - t3-domain/src/main/java/fr/ird/t3/services/DecoratorService.java - t3-domain/src/main/java/fr/ird/t3/services/T3ServiceSupport.java - t3-domain/src/main/java/fr/ird/t3/services/UserService.java - t3-domain/src/test/java/fr/ird/t3/entities/reference/WeightCategoryTreatmentImplTest.java - t3-test/src/main/java/fr/ird/t3/FakeT3ServiceContext.java Changes: ===================================== t3-actions/src/main/java/fr/ird/t3/actions/io/input/test/FakeT3AvdthServiceContext.java ===================================== --- a/t3-actions/src/main/java/fr/ird/t3/actions/io/input/test/FakeT3AvdthServiceContext.java +++ b/t3-actions/src/main/java/fr/ird/t3/actions/io/input/test/FakeT3AvdthServiceContext.java @@ -24,7 +24,6 @@ import fr.ird.t3.T3Config; import fr.ird.t3.T3ConfigOption; import fr.ird.t3.T3IOUtil; import fr.ird.t3.entities.T3EntityHelper; -import fr.ird.t3.entities.T3JdbcHelper; import fr.ird.t3.entities.T3TopiaApplicationContext; import fr.ird.t3.entities.T3TopiaPersistenceContext; import fr.ird.t3.entities.user.T3Users; @@ -33,7 +32,6 @@ import fr.ird.t3.services.T3ServiceContext; import fr.ird.t3.services.T3ServiceFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Assume; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.mockito.Mockito; @@ -43,7 +41,6 @@ import org.nuiton.version.Version; import java.io.Closeable; import java.io.File; -import java.nio.file.Path; import java.util.Date; import java.util.Locale; import java.util.Properties; @@ -63,7 +60,6 @@ public class FakeT3AvdthServiceContext extends TestWatcher implements T3ServiceC private final boolean injectReferential; protected T3TopiaPersistenceContext transaction; private T3TopiaApplicationContext rootContext; - private T3Users t3Users; private File testDir; private T3Config applicationConfiguration; private Locale locale; @@ -71,26 +67,15 @@ public class FakeT3AvdthServiceContext extends TestWatcher implements T3ServiceC private boolean initOk; private MSAccessTestConfiguration msConfig; - public FakeT3AvdthServiceContext() { - this(false); - } - - public FakeT3AvdthServiceContext(boolean injectReferential) { - this.injectReferential = injectReferential; - } - public FakeT3AvdthServiceContext(boolean injectReferential, MSAccessTestConfiguration msConfig) { this.injectReferential = injectReferential; this.msConfig = msConfig; + setLocale(Locale.FRANCE); } @Override public T3Users getT3Users() { - return t3Users; - } - - public void setT3Users(T3Users t3Users) { - this.t3Users = t3Users; + return null; } public boolean isInitOk() { @@ -116,7 +101,7 @@ public class FakeT3AvdthServiceContext extends TestWatcher implements T3ServiceC return rootContext; } - public T3TopiaPersistenceContext newTransaction() throws TopiaException { + private T3TopiaPersistenceContext newTransaction() throws TopiaException { return rootContext.newPersistenceContext(); } @@ -167,14 +152,12 @@ public class FakeT3AvdthServiceContext extends TestWatcher implements T3ServiceC protected void starting(Description description) { super.starting(description); testName = description.getMethodName(); - testDir = T3IOUtil.getTestSpecificDirectory(description.getTestClass(), description.getMethodName()); log.info(String.format("Test dir = %s", testDir)); Properties defaultProps = new Properties(); defaultProps.put(T3ConfigOption.DATA_DIRECTORY.getKey(), testDir); File treatmentDirectory = new File(testDir, "treatment"); FileUtil.createDirectoryIfNecessary(treatmentDirectory); - T3Config realConfiguration = new T3Config(defaultProps) { @Override public void init() { @@ -183,14 +166,12 @@ public class FakeT3AvdthServiceContext extends TestWatcher implements T3ServiceC }; realConfiguration.init(); Version t3DataVersion = realConfiguration.getT3DataVersion(); - applicationConfiguration = Mockito.mock(T3Config.class); Mockito.when(applicationConfiguration.getDataDirectory()).thenReturn(testDir); Mockito.when(applicationConfiguration.getTreatmentWorkingDirectory()).thenReturn(treatmentDirectory); Mockito.when(applicationConfiguration.getT3DataVersion()).thenReturn(t3DataVersion); Mockito.when(applicationConfiguration.getTreatmentWorkingDirectory(Mockito.anyString(), Mockito.anyBoolean())).thenCallRealMethod(); Mockito.when(applicationConfiguration.getApplicationVersion()).thenReturn(realConfiguration.getApplicationVersion()); - if (msConfig != null) { boolean b = msConfig.beforeClass() && msConfig.setup(testName); if (!b) { @@ -199,19 +180,7 @@ public class FakeT3AvdthServiceContext extends TestWatcher implements T3ServiceC } } try { - // where to put h2 database - File dbDirectory = new File(testDir, "h2-database"); - if (injectReferential) { - Path scriptPath = new File(new File("").getAbsolutePath()).getParentFile().toPath().resolve(".mvn").resolve("cache").resolve("test"); - File scriptsDirectory = T3JdbcHelper.getScriptsDirectory(scriptPath.toFile(), "h2", t3DataVersion); - String[] list = scriptsDirectory.list((dir, name) -> name.endsWith(".sql") && name.contains("-referential")); - if (list == null || list.length != 1) { - throw new IllegalStateException(String.format("Can't find h2 referential db from %s", scriptsDirectory)); - } - rootContext = T3TopiaApplicationContext.newEmbeddedBackupDb(dbDirectory, scriptsDirectory.toPath().resolve(list[0]).toFile()); - } else { - rootContext = T3TopiaApplicationContext.newEmbeddedDb(dbDirectory); - } + rootContext = T3TopiaApplicationContext.newTestTopiaApplicationContext(testDir, t3DataVersion, injectReferential); initOk = true; } catch (Exception e) { initOk = false; ===================================== t3-actions/src/test/java/fr/ird/t3/models/LengthCompositionModelHelperTest.java ===================================== --- a/t3-actions/src/test/java/fr/ird/t3/models/LengthCompositionModelHelperTest.java +++ b/t3-actions/src/test/java/fr/ird/t3/models/LengthCompositionModelHelperTest.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% @@ -102,10 +102,9 @@ public class LengthCompositionModelHelperTest { models.put(species2, model); + DecoratorService decoratorService = serviceContext.newService(DecoratorService.class); - String s = LengthCompositionModelHelper.decorateModel( - serviceContext.newService(DecoratorService.class), - "Mon titre", "Value titre", models); + String s = LengthCompositionModelHelper.decorateModel(decoratorService, "Mon titre", "Value titre", models); if (log.isInfoEnabled()) { log.info("Result :\n" + s); } ===================================== t3-actions/src/test/java/fr/ird/t3/models/WeightCompositionModelHelperTest.java ===================================== --- a/t3-actions/src/test/java/fr/ird/t3/models/WeightCompositionModelHelperTest.java +++ b/t3-actions/src/test/java/fr/ird/t3/models/WeightCompositionModelHelperTest.java @@ -20,7 +20,6 @@ */ package fr.ird.t3.models; -import com.google.common.collect.Sets; import fr.ird.t3.FakeT3ServiceContext; import fr.ird.t3.T3ActionFixtures; import fr.ird.t3.entities.reference.Species; @@ -32,7 +31,6 @@ import org.junit.Test; import java.util.HashMap; import java.util.Map; -import java.util.Set; /** * To test {@link WeightCompositionModelHelper}. @@ -54,9 +52,6 @@ public class WeightCompositionModelHelperTest { Species species1 = fixtures.species1(); Species species2 = fixtures.species2(); - Species species3 = fixtures.species3(); - - Set<Species> species = Sets.newHashSet(species1, species2, species3); WeightCompositionAggregateModel model = new WeightCompositionAggregateModel(); WeightCompositionModel model1 = new WeightCompositionModel(fixtures.weightCategoryTreatment1()); @@ -80,9 +75,7 @@ public class WeightCompositionModelHelperTest { model3.addWeights(weights); model.addModel(model3); - String s = WeightCompositionModelHelper.decorateModel( - serviceContext.newService(DecoratorService.class), - "Mon titre", model); + String s = WeightCompositionModelHelper.decorateModel(serviceContext.newService(DecoratorService.class), "Mon titre", model); log.info("Result :\n" + s); } } ===================================== t3-domain/src/main/java/fr/ird/t3/actions/stratum/SchoolTypeIndeterminate.java ===================================== --- /dev/null +++ b/t3-domain/src/main/java/fr/ird/t3/actions/stratum/SchoolTypeIndeterminate.java @@ -0,0 +1,9 @@ +package fr.ird.t3.actions.stratum; + +/** + * Created by tchemit on 07/03/2018. + * + * @author Tony Chemit - dev@tchemit.fr + */ +public enum SchoolTypeIndeterminate { +} ===================================== t3-domain/src/main/java/fr/ird/t3/entities/T3TopiaApplicationContext.java ===================================== --- a/t3-domain/src/main/java/fr/ird/t3/entities/T3TopiaApplicationContext.java +++ b/t3-domain/src/main/java/fr/ird/t3/entities/T3TopiaApplicationContext.java @@ -10,12 +10,12 @@ package fr.ird.t3.entities; * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% @@ -32,12 +32,14 @@ import org.nuiton.topia.persistence.TopiaConfiguration; import org.nuiton.topia.persistence.TopiaConfigurationBuilder; import org.nuiton.topia.persistence.TopiaException; import org.nuiton.util.RecursiveProperties; +import org.nuiton.version.Version; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; +import java.nio.file.Path; import java.util.Objects; import java.util.Properties; @@ -47,6 +49,10 @@ public class T3TopiaApplicationContext extends AbstractT3TopiaApplicationContext private static final String T3_USER_DB_PROPERTIES = "/t3-datadb.properties"; private static final Log log = LogFactory.getLog(T3TopiaApplicationContext.class); + private T3TopiaApplicationContext(TopiaConfiguration topiaConfiguration) { + super(topiaConfiguration); + } + /** * Open a new topia root context from the given jdbc configuration. * @@ -83,7 +89,6 @@ public class T3TopiaApplicationContext extends AbstractT3TopiaApplicationContext return new T3TopiaApplicationContext(topiaConfiguration); } - /** * Open a new topia root context for the user t3 db using a embedded db (this should be a h2 db). * <p/> @@ -110,6 +115,21 @@ public class T3TopiaApplicationContext extends AbstractT3TopiaApplicationContext return new T3TopiaApplicationContext(topiaConfiguration); } + public static T3TopiaApplicationContext newTestTopiaApplicationContext(File testDir, Version t3DataVersion, boolean injectReferential) throws IOException { + File dbDirectory = new File(testDir, "h2-database"); + if (injectReferential) { + Path scriptPath = new File(new File("").getAbsolutePath()).getParentFile().toPath().resolve(".mvn").resolve("cache").resolve("test"); + File scriptsDirectory = T3JdbcHelper.getScriptsDirectory(scriptPath.toFile(), "h2", t3DataVersion); + String[] list = scriptsDirectory.list((dir, name) -> name.endsWith(".sql") && name.contains("-referential")); + if (list == null || list.length != 1) { + throw new IllegalStateException(String.format("Can't find h2 referential db from %s", scriptsDirectory)); + } + return newEmbeddedBackupDb(dbDirectory, scriptsDirectory.toPath().resolve(list[0]).toFile()); + } else { + return newEmbeddedDb(dbDirectory); + } + } + /** * Open a new topia root context for the user t3 db using a embedded db (this should be a h2 db). * <p/> @@ -119,7 +139,7 @@ public class T3TopiaApplicationContext extends AbstractT3TopiaApplicationContext * @param backupFile backup file to load in db * @return the new fresh root context of the db */ - public static T3TopiaApplicationContext newEmbeddedBackupDb(File dbLocation, File backupFile) { + private static T3TopiaApplicationContext newEmbeddedBackupDb(File dbLocation, File backupFile) { Properties configuration = new Properties(); @@ -143,8 +163,4 @@ public class T3TopiaApplicationContext extends AbstractT3TopiaApplicationContext return new T3JdbcHelper(getConfiguration()); } - private T3TopiaApplicationContext(TopiaConfiguration topiaConfiguration) { - super(topiaConfiguration); - } - } ===================================== t3-domain/src/main/java/fr/ird/t3/models/LengthCompositionModelHelper.java ===================================== --- a/t3-domain/src/main/java/fr/ird/t3/models/LengthCompositionModelHelper.java +++ b/t3-domain/src/main/java/fr/ird/t3/models/LengthCompositionModelHelper.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% @@ -21,13 +21,13 @@ package fr.ird.t3.models; import com.google.common.base.Strings; -import com.google.common.collect.Lists; import fr.ird.t3.entities.reference.Species; +import fr.ird.t3.entities.reference.WeightCategories; import fr.ird.t3.entities.reference.WeightCategoryTreatment; -import fr.ird.t3.entities.reference.WeightCategoryTreatmentTopiaDao; import fr.ird.t3.services.DecoratorService; import org.nuiton.decorator.Decorator; +import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; @@ -43,7 +43,7 @@ import static org.nuiton.i18n.I18n.l; * @author Tony Chemit - dev@tchemit.fr * @since 1.3.1 */ -public class LengthCompositionModelHelper { +public final class LengthCompositionModelHelper { private static final Comparator<Species> SPECIES_COMPARATOR = Comparator.comparingInt(Species::getCode); @@ -55,96 +55,64 @@ public class LengthCompositionModelHelper { String title, String valueTitle, Map<Species, LengthCompositionAggregateModel> models) { - StringBuilder inResume = new StringBuilder(); - Locale locale = decoratorService.getLocale(); - String lengthClassLabel = l(locale, "t3.common.lengthClass"); - int lengthClassColumnLength = lengthClassLabel.length(); int valueColumnLength = 15; int rateColumnLength = 15; - - Decorator<Species> decorator = - decoratorService.getDecorator(locale, Species.class, null); - + Decorator<Species> decorator = decoratorService.getDecorator(locale, Species.class, null); Decorator<WeightCategoryTreatment> decorator2 = decoratorService.getDecorator(locale, WeightCategoryTreatment.class, null); - - List<Species> speciesList = Lists.newArrayList(models.keySet()); + List<Species> speciesList = new ArrayList<>(models.keySet()); speciesList.sort(SPECIES_COMPARATOR); int origMaxLength = 10 + (lengthClassColumnLength) + (valueColumnLength + rateColumnLength); int maxLength = origMaxLength; - maxLength = Math.max(maxLength, l(locale, "t3.common.forAllWeightCategories").length() + 4); - for (Species species : speciesList) { int l = decorator.toString(species).length() + 4; maxLength = Math.max(maxLength, l); LengthCompositionAggregateModel model = models.get(species); - Set<WeightCategoryTreatment> weightCategories = model.getWeightCategories(); for (WeightCategoryTreatment weightCategory : weightCategories) { int l2 = l(locale, "t3.common.weightCategory", decorator2.toString(weightCategory)).length() + 4; maxLength = Math.max(maxLength, l2); } } - if (maxLength > origMaxLength) { lengthClassColumnLength += maxLength - origMaxLength; } - CompositionTableModel header = new CompositionTableModel(); String lineFormat = "| %1$-" + lengthClassColumnLength + "s | %2$-" + valueColumnLength + "s - %3$-" + rateColumnLength + "s |\n"; - header.setLineFormat(lineFormat); header.setHeader( String.format("| %1$-" + lengthClassColumnLength + "s | %2$-" + (valueColumnLength + rateColumnLength + 3) + "s |\n", lengthClassLabel, valueTitle)); - header.setSeparatorFormat3( Strings.padEnd("|", lengthClassColumnLength + 3, '-') + Strings.padEnd("|", (valueColumnLength + rateColumnLength + 6), '-') + "|\n"); - header.setCategoryFormat("| %1$-" + (maxLength - 4) + "s |\n"); header.setSeparatorFormat(Strings.padEnd("|", maxLength - 1, '-') + "|\n"); header.setSeparatorFormat2(Strings.padEnd("|", maxLength - 1, '=') + "|\n"); header.setTopSeparatorFormat(Strings.padEnd("=", maxLength, '=') + "\n"); header.setBottomSeparatorFormat(Strings.padEnd("=", maxLength, '=') + "\n"); - inResume.append(title).append('\n'); inResume.append(header.getTopSeparatorFormat()); inResume.append(header.getHeader()); - for (Species species : speciesList) { - inResume.append(header.getSeparatorFormat2()); - inResume.append(String.format(header.getCategoryFormat(), - decorator.toString(species))); - + inResume.append(String.format(header.getCategoryFormat(), decorator.toString(species))); LengthCompositionAggregateModel model = models.get(species); - - List<WeightCategoryTreatment> weightCategories = Lists.newArrayList(model.getWeightCategories()); - weightCategories.sort(WeightCategoryTreatmentTopiaDao.newComparator()); - + List<WeightCategoryTreatment> weightCategories = new ArrayList<>(model.getWeightCategories()); + WeightCategories.sort(weightCategories); for (WeightCategoryTreatment weightCategory : weightCategories) { LengthCompositionModel lengthCompositionModel = model.getModel(weightCategory); if (!lengthCompositionModel.isEmpty()) { inResume.append(header.getSeparatorFormat()); - decorateModel( - header, - decoratorService, - model, - weightCategory, - inResume - ); + decorateModel(header, decoratorService, model, weightCategory, inResume); } - } } - inResume.append(header.getBottomSeparatorFormat()); - return inResume.toString(); } @@ -153,78 +121,43 @@ public class LengthCompositionModelHelper { LengthCompositionAggregateModel model, WeightCategoryTreatment weightCategory, StringBuilder inResume) { - Decorator<WeightCategoryTreatment> decorator2 = decoratorService.getDecorator(decoratorService.getLocale(), WeightCategoryTreatment.class, null); - - LengthCompositionModel m; - - String categoryLibelle; - Locale locale = decoratorService.getLocale(); - - String totalLibelle = l(locale, "t3.common.total"); - String averageLengthLibelle = l(locale, "t3.common.averageLength"); - + String totalLabel = l(locale, "t3.common.total"); + String averageLengthLabel = l(locale, "t3.common.averageLength"); + LengthCompositionModel m; + String categoryLabel; if (weightCategory == null) { - m = model.getTotalModel(); - categoryLibelle = l(locale, "t3.common.forAllWeightCategories"); + categoryLabel = l(locale, "t3.common.forAllWeightCategories"); } else { m = model.getModel(weightCategory); - - categoryLibelle = - l(locale, "t3.common.weightCategory", - decorator2.toString(weightCategory)); + categoryLabel = l(locale, "t3.common.weightCategory", decorator2.toString(weightCategory)); } - if (!m.isEmpty()) { - - inResume.append(String.format(header.getCategoryFormat(), categoryLibelle)); + inResume.append(String.format(header.getCategoryFormat(), categoryLabel)); inResume.append(header.getSeparatorFormat()); - String lineFormat = header.getLineFormat(); - - List<Integer> lengthClasses = Lists.newArrayList(m.getLengthClasses()); + List<Integer> lengthClasses = new ArrayList<>(m.getLengthClasses()); Collections.sort(lengthClasses); - float totalRate = 0; float totalCount = 0; - float totalLength = 0; - for (Integer lengthClass : lengthClasses) { - float weightRate1 = m.getRate(lengthClass); totalRate += weightRate1; float value = m.getValue(lengthClass); - inResume.append(String.format( - lineFormat, - lengthClass, - value, - (100 * weightRate1) + "%")); + inResume.append(String.format(lineFormat, lengthClass, value, (100 * weightRate1) + "%")); totalCount += value; totalLength += lengthClass * value; } - float averageLength = totalLength / totalCount; - inResume.append(header.getSeparatorFormat3()); - - inResume.append(String.format( - lineFormat, - totalLibelle, - totalCount, - (100 * totalRate) + "%")); - + inResume.append(String.format(lineFormat, totalLabel, totalCount, (100 * totalRate) + "%")); if (weightCategory != null) { - inResume.append(String.format( - lineFormat, - averageLengthLibelle, - averageLength, - "-")); + inResume.append(String.format(lineFormat, averageLengthLabel, averageLength, "-")); } - } } } ===================================== t3-domain/src/main/java/fr/ird/t3/services/DecoratorService.java ===================================== --- a/t3-domain/src/main/java/fr/ird/t3/services/DecoratorService.java +++ b/t3-domain/src/main/java/fr/ird/t3/services/DecoratorService.java @@ -8,21 +8,19 @@ * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ package fr.ird.t3.services; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import fr.ird.t3.actions.stratum.SchoolTypeIndeterminate; import fr.ird.t3.entities.data.Activity; import fr.ird.t3.entities.data.CompleteTrip; import fr.ird.t3.entities.data.Route; @@ -58,11 +56,14 @@ import org.nuiton.decorator.JXPathDecorator; import org.nuiton.topia.persistence.TopiaEntity; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Collection; import java.util.Date; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import static org.nuiton.i18n.I18n.l; @@ -75,85 +76,60 @@ import static org.nuiton.i18n.I18n.l; public class DecoratorService extends T3ServiceSupport implements T3ServiceSingleton { public static final String WITH_ID = "withId"; - + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy"); private final DecoratorMulti18nProvider decoratorProvider; - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy"); + public DecoratorService() { + decoratorProvider = new T3DecoratorProvider(); + } public static String formatDate(Date date) { return DATE_FORMAT.format(date); } - public DecoratorService() { - decoratorProvider = new T3DecoratorProvider(); - } - - public <O> Decorator<O> getDecorator(Locale locale, - Class<O> type, - String context) { - Preconditions.checkNotNull(type, "Decorator type can not be null!"); - Decorator<O> decorator = decoratorProvider.getDecoratorByType(locale, type, context); - Preconditions.checkNotNull( - decorator, - "Could not find decorator for type " + type + - " and context " + context - ); - return decorator; + public <O> Decorator<O> getDecorator(Locale locale, Class<O> type, String context) { + Decorator<O> decorator = decoratorProvider.getDecoratorByType(Objects.requireNonNull(locale), Objects.requireNonNull(type), context); + return Objects.requireNonNull(decorator, + String.format("Could not find decorator for type %s and context %s", type, context)); } public String decorate(Locale locale, Object o, String context) { - Decorator<?> decorator = getDecorator(locale, o.getClass(), context); + Decorator<?> decorator = getDecorator(locale, Objects.requireNonNull(o).getClass(), context); return decorator.toString(o); } public <O> List<O> sortToList(Locale locale, Collection<O> beans, String context) { - Preconditions.checkNotNull(beans); - List<O> list = Lists.newArrayList(beans); + List<O> list = new ArrayList<>(Objects.requireNonNull(beans)); getDecoratorAndSort(locale, context, list); return list; } - public <E extends TopiaEntity> Map<String, String> sortAndDecorate(Locale locale, - Collection<E> beans, - String context) { - Preconditions.checkNotNull(beans); - List<E> list = Lists.newArrayList(beans); - + public <E extends TopiaEntity> Map<String, String> sortAndDecorate(Locale locale, Collection<E> beans, String context) { + List<E> list = new ArrayList<>(Objects.requireNonNull(beans)); Decorator<E> decorator = getDecoratorAndSort(locale, context, list); - Map<String, String> result = Maps.newLinkedHashMap(); + Map<String, String> result = new LinkedHashMap<>(); for (E bean : list) { result.put(bean.getTopiaId(), decorator.toString(bean)); } return result; } - public <E extends Idable> Map<String, String> sortAndDecorateIdAbles(Locale locale, - Collection<E> beans, - String context) { - - Preconditions.checkNotNull(beans); - List<E> list = Lists.newArrayList(beans); - + public <E extends Idable> Map<String, String> sortAndDecorateIdAbles(Locale locale, Collection<E> beans, String context) { + List<E> list = new ArrayList<>(Objects.requireNonNull(beans)); Decorator<E> decorator = getDecoratorAndSort(locale, context, list); - Map<String, String> result = Maps.newLinkedHashMap(); + Map<String, String> result = new LinkedHashMap<>(); for (E bean : list) { result.put(bean.getId(), decorator.toString(bean)); } return result; } - protected <O> Decorator<O> getDecoratorAndSort(Locale locale, - String context, - List<O> list) { + private <O> Decorator<O> getDecoratorAndSort(Locale locale, String context, List<O> list) { Decorator<O> decorator = null; if (CollectionUtils.isNotEmpty(list)) { - O object = list.get(0); - Preconditions.checkNotNull(object); - decorator = decoratorProvider.getDecorator(locale, object, context); - Preconditions.checkNotNull( - decorator, - "Could not find decorator for type " + object.getClass() + - " and context " + context + O object = Objects.requireNonNull(list.get(0)); + decorator = Objects.requireNonNull(decoratorProvider.getDecorator(locale, object, context), + String.format("Could not find decorator for type %s and context %s", object.getClass(), context) ); DecoratorUtil.sort((JXPathDecorator<O>) decorator, list, 0); } @@ -171,6 +147,9 @@ public class DecoratorService extends T3ServiceSupport implements T3ServiceSingl // trip type decorator registerJXPathDecorator(locale, TripType.class, "${label}$s"); + // SchoolTypeIndeterminate decorator + registerJXPathDecorator(locale, SchoolTypeIndeterminate.class, "${label}$s"); + // route decorator registerJXPathDecorator(locale, Route.class, "${trip/vesselLabel}$s - ${trip/landingDate}$td/%2$tm/%2$tY - ${date}$td/%3$tm/%3$tY"); @@ -259,20 +238,17 @@ public class DecoratorService extends T3ServiceSupport implements T3ServiceSingl private static class ZoneStratumAwareMetaJXPathDecorator extends JXPathDecorator<ZoneStratumAwareMeta> { private static final long serialVersionUID = 1L; - private final Locale locale; - public ZoneStratumAwareMetaJXPathDecorator(String expression, - Context<ZoneStratumAwareMeta> context, - Locale locale) throws IllegalArgumentException, NullPointerException { + ZoneStratumAwareMetaJXPathDecorator(String expression, Context<ZoneStratumAwareMeta> context, Locale locale) { super(ZoneStratumAwareMeta.class, expression, context); this.locale = locale; } @SuppressWarnings({"RawUseOfParameterizedType", "RedundantCast", "unchecked"}) @Override - protected Comparable<Comparable<?>> getTokenValue(JXPathContext jxcontext, String token) { - Comparable tokenValue = super.getTokenValue(jxcontext, token); + protected Comparable<Comparable<?>> getTokenValue(JXPathContext jxContext, String token) { + Comparable tokenValue = super.getTokenValue(jxContext, token); return (Comparable) l(locale, (String) tokenValue); } } ===================================== t3-domain/src/main/java/fr/ird/t3/services/T3ServiceSupport.java ===================================== --- a/t3-domain/src/main/java/fr/ird/t3/services/T3ServiceSupport.java +++ b/t3-domain/src/main/java/fr/ird/t3/services/T3ServiceSupport.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% @@ -22,14 +22,13 @@ package fr.ird.t3.services; import fr.ird.t3.T3Config; import fr.ird.t3.entities.T3TopiaPersistenceContext; - -import java.util.Locale; -import java.util.function.Supplier; - import fr.ird.t3.entities.user.T3Users; import org.nuiton.topia.persistence.TopiaException; import org.nuiton.util.TimeLog; +import java.util.Locale; +import java.util.function.Supplier; + /** * Service support. * @@ -38,16 +37,15 @@ import org.nuiton.util.TimeLog; */ public class T3ServiceSupport implements T3Service { - protected TimeLog timeLog; - protected T3ServiceContext serviceContext; + private TimeLog timeLog; @Override public void setServiceContext(T3ServiceContext serviceContext) { this.serviceContext = serviceContext; } - public T3Users getT3UserStorage() { + public T3Users getT3Users() { return serviceContext.getT3Users(); } @@ -71,20 +69,10 @@ public class T3ServiceSupport implements T3Service { return serviceContext.newService(clazz); } - protected void flushTransaction(String message) throws TopiaException { + protected void flushTransaction(String classifier) throws TopiaException { long s0 = TimeLog.getTime(); - getT3TopiaPersistenceContext().get().getHibernateSupport().getHibernateSession().flush(); - - getTimeLog().log(s0, message); - } - - protected void flushTransaction(String message, String classifier) throws TopiaException { - long s0 = TimeLog.getTime(); - - getT3TopiaPersistenceContext().get().getHibernateSupport().getHibernateSession().flush(); - - getTimeLog().log(s0, message, classifier); + getTimeLog().log(s0, "Flush transaction for trip", classifier); } protected TimeLog getTimeLog() { ===================================== t3-domain/src/main/java/fr/ird/t3/services/UserService.java ===================================== --- a/t3-domain/src/main/java/fr/ird/t3/services/UserService.java +++ b/t3-domain/src/main/java/fr/ird/t3/services/UserService.java @@ -41,15 +41,15 @@ import java.util.UUID; public class UserService extends T3ServiceSupport implements T3ServiceInjectable { public Optional<T3User> getUserByLogin(String login) { - return getT3UserStorage().usersStream().whereLogin().isEquals(login).filter().findFirst(); + return getT3Users().usersStream().whereLogin().isEquals(login).filter().findFirst(); } public T3User getUserById(String userId) throws TopiaNotFoundException { - return getT3UserStorage().usersStream().whereId().isEquals(userId).filter().findFirst().orElseThrow(() -> new TopiaNotFoundException(userId)); + return getT3Users().usersStream().whereId().isEquals(userId).filter().findFirst().orElseThrow(() -> new TopiaNotFoundException(userId)); } public List<T3User> getUsers() { - return getT3UserStorage().getUsers(); + return getT3Users().getUsers(); } public void createUser(T3User user) { @@ -61,7 +61,7 @@ public class UserService extends T3ServiceSupport implements T3ServiceInjectable .login(user.getLogin()) .password(newPassword) .build(); - getT3UserStorage().getUsers().add(userToSave); + getT3Users().getUsers().add(userToSave); user.setId(userToSave.getId()); commit(); } @@ -82,7 +82,7 @@ public class UserService extends T3ServiceSupport implements T3ServiceInjectable public void deleteUser(String userId) { T3User user = getUserById(userId); - getT3UserStorage().getUsers().remove(user); + getT3Users().getUsers().remove(user); commit(); } @@ -139,11 +139,11 @@ public class UserService extends T3ServiceSupport implements T3ServiceInjectable } public UserDatabase getUserInputDatabase(String dbConfigurationId) { - return getT3UserStorage().getInput(dbConfigurationId); + return getT3Users().getInput(dbConfigurationId); } public UserDatabase getUserOutputDatabase(String dbConfigurationId) { - return getT3UserStorage().getOutput(dbConfigurationId); + return getT3Users().getOutput(dbConfigurationId); } public boolean checkPassword(T3User user, String password) { @@ -162,7 +162,7 @@ public class UserService extends T3ServiceSupport implements T3ServiceInjectable } private void commit() { - getT3UserStorage().save(); + getT3Users().save(); } } ===================================== t3-domain/src/test/java/fr/ird/t3/entities/reference/WeightCategoryTreatmentImplTest.java ===================================== --- a/t3-domain/src/test/java/fr/ird/t3/entities/reference/WeightCategoryTreatmentImplTest.java +++ b/t3-domain/src/test/java/fr/ird/t3/entities/reference/WeightCategoryTreatmentImplTest.java @@ -76,7 +76,7 @@ public class WeightCategoryTreatmentImplTest extends AbstractDatabaseTest { list.add(catInconnu); list.add(catBound); - WeightCategoryTreatmentTopiaDao.sortWeightCategoryTreatments(list); + WeightCategories.sort(list); Assert.assertEquals(list.get(0), catBound); Assert.assertEquals(list.get(1), catUnbound); @@ -113,8 +113,7 @@ public class WeightCategoryTreatmentImplTest extends AbstractDatabaseTest { list.add(catInconnu); list.add(catBound); - Comparator<WeightCategoryTreatment> comparator = - WeightCategoryTreatmentTopiaDao.newComparator(); + Comparator<WeightCategory> comparator =WeightCategories.newComparator(); int compare; @@ -127,7 +126,7 @@ public class WeightCategoryTreatmentImplTest extends AbstractDatabaseTest { compare = comparator.compare(catBound2, catUnbound); Assert.assertTrue(compare < 0); - WeightCategoryTreatmentTopiaDao.sortWeightCategoryTreatments(list); + WeightCategories.sort(list); Assert.assertEquals(list.get(0), catBound); Assert.assertEquals(list.get(1), catBound2); ===================================== t3-test/src/main/java/fr/ird/t3/FakeT3ServiceContext.java ===================================== --- a/t3-test/src/main/java/fr/ird/t3/FakeT3ServiceContext.java +++ b/t3-test/src/main/java/fr/ird/t3/FakeT3ServiceContext.java @@ -8,12 +8,12 @@ * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. - * + * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. - * + * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% @@ -21,7 +21,6 @@ package fr.ird.t3; import fr.ird.t3.entities.T3EntityHelper; -import fr.ird.t3.entities.T3JdbcHelper; import fr.ird.t3.entities.T3TopiaApplicationContext; import fr.ird.t3.entities.T3TopiaPersistenceContext; import fr.ird.t3.entities.user.T3Users; @@ -39,7 +38,6 @@ import org.nuiton.version.Version; import java.io.Closeable; import java.io.File; -import java.nio.file.Path; import java.util.Date; import java.util.Locale; import java.util.Properties; @@ -59,11 +57,9 @@ public class FakeT3ServiceContext extends TestWatcher implements T3ServiceContex private final boolean injectReferential; protected T3TopiaPersistenceContext transaction; private T3TopiaApplicationContext rootContext; - private T3Users t3Users; private File testDir; private T3Config applicationConfiguration; private Locale locale; - private String testName; private boolean initOk; public FakeT3ServiceContext() { @@ -72,15 +68,12 @@ public class FakeT3ServiceContext extends TestWatcher implements T3ServiceContex public FakeT3ServiceContext(boolean injectReferential) { this.injectReferential = injectReferential; + setLocale(Locale.FRANCE); } @Override public T3Users getT3Users() { - return t3Users; - } - - public void setT3Users(T3Users t3Users) { - this.t3Users = t3Users; + return null; } public boolean isInitOk() { @@ -148,25 +141,15 @@ public class FakeT3ServiceContext extends TestWatcher implements T3ServiceContex return testDir; } - public String getTestName() { - return testName; - } - @Override protected void starting(Description description) { super.starting(description); - testName = description.getMethodName(); - testDir = T3IOUtil.getTestSpecificDirectory(description.getTestClass(), description.getMethodName()); - if (log.isInfoEnabled()) { - log.info("Test dir = " + testDir); - } - + log.info(String.format("Test dir = %s", testDir)); Properties defaultProps = new Properties(); defaultProps.put(T3ConfigOption.DATA_DIRECTORY.getKey(), testDir); File treatmentDirectory = new File(testDir, "treatment"); FileUtil.createDirectoryIfNecessary(treatmentDirectory); - T3Config realConfiguration = new T3Config(defaultProps) { @Override public void init() { @@ -175,37 +158,15 @@ public class FakeT3ServiceContext extends TestWatcher implements T3ServiceContex }; realConfiguration.init(); Version t3DataVersion = realConfiguration.getT3DataVersion(); - applicationConfiguration = Mockito.mock(T3Config.class); Mockito.when(applicationConfiguration.getDataDirectory()).thenReturn(testDir); Mockito.when(applicationConfiguration.getTreatmentWorkingDirectory()).thenReturn(treatmentDirectory); Mockito.when(applicationConfiguration.getT3DataVersion()).thenReturn(t3DataVersion); Mockito.when(applicationConfiguration.getTreatmentWorkingDirectory(Mockito.anyString(), Mockito.anyBoolean())).thenCallRealMethod(); Mockito.when(applicationConfiguration.getApplicationVersion()).thenReturn(realConfiguration.getApplicationVersion()); - try { - - // where to put h2 database - File dbDirectory = new File(testDir, "h2-database"); - - if (injectReferential) { - Path scriptPath = new File(new File("").getAbsolutePath()).getParentFile().toPath().resolve(".mvn").resolve("cache").resolve("test"); - File scriptsDirectory = T3JdbcHelper.getScriptsDirectory(scriptPath.toFile(), "h2", t3DataVersion); - - String[] list = scriptsDirectory.list((dir, name) -> name.endsWith(".sql") && name.contains("-referential")); - if (list == null || list.length != 1) { - throw new IllegalStateException(String.format("Can't find h2 referential db from %s", scriptsDirectory)); - } - rootContext = T3TopiaApplicationContext.newEmbeddedBackupDb(dbDirectory, scriptsDirectory.toPath().resolve(list[0]).toFile()); - } else { - rootContext = T3TopiaApplicationContext.newEmbeddedDb(dbDirectory); - } -// if (injectReferential) { -// // inject in db the referentiel -// T3SqlScriptsImporter.importReferential(new File(""), this, T3SqlScriptsImporter.SKIP_SPECIES_LENGTH_STEP_FILE); -// } + rootContext = T3TopiaApplicationContext.newTestTopiaApplicationContext(testDir, t3DataVersion, injectReferential); initOk = true; - } catch (Exception e) { initOk = false; throw new IllegalStateException("Could not start db", e); View it on GitLab: https://gitlab.com/ultreiaio/ird-t3/compare/f6fbda7f307045941f679ac7b5cc91dd... --- View it on GitLab: https://gitlab.com/ultreiaio/ird-t3/compare/f6fbda7f307045941f679ac7b5cc91dd... You're receiving this email because of your account on gitlab.com.