From a7458167fb0e01da3b97548aa0ee9afb257ff6af Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Wed, 31 Aug 2022 18:14:42 +0200 Subject: [PATCH] 5.9.2 (#37) * Switch to pom-scijava 32.0.0 * Switch to JUnit5 * Send output from tests to target/logs * Change setup to JDK 8 * Add methods to create a screen and refactor code to import images to screens * Add method addAndReplaceTable (#32) * Add test for addAndReplaceTable * Make Client constructor with arguments public (#34) * Add methods to retrieve well, plate and screen from an image (#35) * Add LibraryChecker utility class to check if required libraries are available (#36) * Make specific tests for LibraryChecker * Add time increment to ImagePlus and set the position to the first slice * Use float coordinates for IJ ROI conversion * Split ImageTest * Simplify key/value tests in ImageTest * Prevent GatewayWrapper from containing null fields * Override toString method in GatewayWrapper and add server information to context * Change disconnect method so that a sudo client does not disconnect the gateway * Replace System.err.println with logger * Add tests * Add serialVersionUID to classes that require it * Fix and improve Javadoc * Rename some variables * Minor code improvements --- .gitignore | 1 + Dockerfile | 2 +- pom.xml | 97 +-- src/main/java/fr/igred/omero/Client.java | 13 +- .../java/fr/igred/omero/GatewayWrapper.java | 52 +- .../fr/igred/omero/GenericObjectWrapper.java | 21 +- .../annotations/FileAnnotationWrapper.java | 5 + .../annotations/MapAnnotationWrapper.java | 2 +- .../igred/omero/annotations/TableWrapper.java | 56 +- .../annotations/TagAnnotationWrapper.java | 4 +- .../omero/exception/AccessException.java | 3 + .../omero/exception/ExceptionHandler.java | 2 +- .../omero/exception/OMEROServerError.java | 3 + .../omero/exception/ServiceException.java | 3 + .../igred/omero/meta/ExperimenterWrapper.java | 8 +- .../fr/igred/omero/meta/GroupWrapper.java | 8 +- .../omero/repository/ChannelWrapper.java | 8 +- .../omero/repository/DatasetWrapper.java | 99 +-- .../igred/omero/repository/FolderWrapper.java | 5 +- .../GenericRepositoryObjectWrapper.java | 203 ++++- .../igred/omero/repository/ImageWrapper.java | 164 +++- .../igred/omero/repository/PixelsWrapper.java | 71 +- .../repository/PlateAcquisitionWrapper.java | 10 +- .../igred/omero/repository/PlateWrapper.java | 33 +- .../omero/repository/ProjectWrapper.java | 11 +- .../igred/omero/repository/ScreenWrapper.java | 105 ++- .../omero/repository/WellSampleWrapper.java | 30 +- .../igred/omero/repository/WellWrapper.java | 9 +- .../fr/igred/omero/roi/EllipseWrapper.java | 6 +- .../igred/omero/roi/GenericShapeWrapper.java | 6 +- .../java/fr/igred/omero/roi/LineWrapper.java | 7 +- .../java/fr/igred/omero/roi/MaskWrapper.java | 4 + .../java/fr/igred/omero/roi/PointWrapper.java | 4 + .../fr/igred/omero/roi/PolygonWrapper.java | 10 +- .../fr/igred/omero/roi/PolylineWrapper.java | 10 +- .../java/fr/igred/omero/roi/ROIWrapper.java | 4 +- .../fr/igred/omero/roi/RectangleWrapper.java | 6 +- .../java/fr/igred/omero/roi/ShapeList.java | 5 +- .../java/fr/igred/omero/roi/TextWrapper.java | 6 +- .../fr/igred/omero/util/LibraryChecker.java | 110 +++ .../fr/igred/omero/util/package-info.java | 20 + .../fr/igred/omero/AccessExceptionTest.java | 173 ++--- src/test/java/fr/igred/omero/BasicTest.java | 80 +- src/test/java/fr/igred/omero/ClientTest.java | 69 +- .../java/fr/igred/omero/ConnectionTest.java | 26 +- .../java/fr/igred/omero/ExceptionTest.java | 137 ++-- .../java/fr/igred/omero/LoggingExtension.java | 203 +++++ src/test/java/fr/igred/omero/RootTest.java | 24 +- src/test/java/fr/igred/omero/SudoTest.java | 32 +- src/test/java/fr/igred/omero/TestObject.java | 6 +- src/test/java/fr/igred/omero/UserTest.java | 22 +- .../fr/igred/omero/annotations/TableTest.java | 180 +++-- .../fr/igred/omero/annotations/TagTest.java | 30 +- .../fr/igred/omero/meta/ExperimenterTest.java | 39 +- .../java/fr/igred/omero/meta/GroupTest.java | 23 +- .../igred/omero/repository/DatasetTest.java | 93 +-- .../fr/igred/omero/repository/FolderTest.java | 24 +- .../omero/repository/ImageImportTest.java | 349 +++++++++ .../fr/igred/omero/repository/ImageTest.java | 714 +++++------------- .../fr/igred/omero/repository/PixelsTest.java | 133 ++++ .../repository/PlateAcquisitionTest.java | 25 +- .../fr/igred/omero/repository/PlateTest.java | 34 +- .../igred/omero/repository/ProjectTest.java | 56 +- .../fr/igred/omero/repository/ScreenTest.java | 111 ++- .../omero/repository/WellSampleTest.java | 26 +- .../fr/igred/omero/repository/WellTest.java | 30 +- .../fr/igred/omero/roi/ROI2ImageJTest.java | 33 +- src/test/java/fr/igred/omero/roi/ROITest.java | 14 +- .../fr/igred/omero/roi/ShapeErrorTest.java | 78 +- .../java/fr/igred/omero/roi/ShapeTest.java | 70 +- .../igred/omero/util/LibraryCheckerTest.java | 88 +++ src/test/resources/logback-test.xml | 12 + 72 files changed, 2575 insertions(+), 1585 deletions(-) create mode 100644 src/main/java/fr/igred/omero/util/LibraryChecker.java create mode 100644 src/main/java/fr/igred/omero/util/package-info.java create mode 100644 src/test/java/fr/igred/omero/LoggingExtension.java create mode 100644 src/test/java/fr/igred/omero/repository/ImageImportTest.java create mode 100644 src/test/java/fr/igred/omero/repository/PixelsTest.java create mode 100644 src/test/java/fr/igred/omero/util/LibraryCheckerTest.java create mode 100644 src/test/resources/logback-test.xml diff --git a/.gitignore b/.gitignore index a16da7b9..7f516c34 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ buildNumber.properties .mvn/timing.properties # https://github.com/takari/maven-wrapper#usage-without-binary-jar .mvn/wrapper/maven-wrapper.jar +*.iml \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 288ea442..02d3c3f1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM maven:3.6.3-jdk-11 +FROM maven:3.8.6-jdk-8 MAINTAINER pierre.pouchin@uca.fr COPY . /src diff --git a/pom.xml b/pom.xml index 270daf57..f2c35000 100644 --- a/pom.xml +++ b/pom.xml @@ -4,12 +4,12 @@ pom-scijava org.scijava - 30.0.0 + 32.0.0 fr.igred simple-omero-client - 5.9.1 + 5.9.2 jar Simple OMERO Client @@ -91,96 +91,37 @@ 8 gpl_v2 GReD + + 3.3.0 + + 3.0.0-M7 - - org.openmicroscopy - omero-gateway - 5.6.7 - org.openmicroscopy omero-model - 5.6.3 + ${omero-model.version} net.jcip jcip-annotations - - org.springframework - * - - - org.hibernate - * - - - - - org.openmicroscopy - omero-blitz - 5.5.8 - - - org.springframework - * - - - org.springframework.security - * - - - org.apache.xmlgraphics - * - - - org.apache.httpcomponents - * - - - org.apache.pdfbox - * - - - org.postgresql - * - - - org.hibernate - * - - - com.codahale.metrics - * - - - - - org.openmicroscopy - ome-common - 6.0.7 - - - xml-apis - xml-apis - - - ome - formats-api - 6.7.0 - - junit - junit + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-params test @@ -218,8 +159,8 @@ - ome.maven - https://artifacts.openmicroscopy.org/artifactory/maven/ + scijava.public + https://maven.scijava.org/content/groups/public @@ -228,7 +169,7 @@ org.apache.maven.plugins maven-assembly-plugin - 2.6 + ${maven-assembly-plugin.version} package @@ -266,7 +207,7 @@ org.jacoco jacoco-maven-plugin - 0.8.6 + ${jacoco-maven-plugin.version} @@ -287,7 +228,6 @@ 8 false - --no-module-directories @@ -308,7 +248,6 @@ 8 false - --no-module-directories diff --git a/src/main/java/fr/igred/omero/Client.java b/src/main/java/fr/igred/omero/Client.java index 779e1fc3..e931f68c 100644 --- a/src/main/java/fr/igred/omero/Client.java +++ b/src/main/java/fr/igred/omero/Client.java @@ -47,7 +47,6 @@ import omero.gateway.model.ScreenData; import omero.gateway.model.TagAnnotationData; import omero.gateway.model.WellData; -import omero.log.SimpleLogger; import omero.model.IObject; import omero.model.TagAnnotation; @@ -80,7 +79,7 @@ public class Client extends GatewayWrapper { * Constructor of the Client class. Initializes the gateway. */ public Client() { - super(new Gateway(new SimpleLogger())); + super(null); } @@ -91,7 +90,7 @@ public Client() { * @param ctx The security context * @param user The user */ - private Client(Gateway gateway, SecurityContext ctx, ExperimenterWrapper user) { + public Client(Gateway gateway, SecurityContext ctx, ExperimenterWrapper user) { super(gateway, ctx, user); } @@ -769,7 +768,7 @@ public TagAnnotationWrapper getTag(Long id) throws OMEROServerError, ServiceExce * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public void delete(Collection> objects) @@ -793,7 +792,7 @@ public void delete(Collection> objects) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public void delete(GenericObjectWrapper object) @@ -813,8 +812,8 @@ public void delete(GenericObjectWrapper object) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws IllegalArgumentException Id not defined. - * @throws OMEROServerError If the thread was interrupted. + * @throws IllegalArgumentException ID not defined. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public void delete(TableWrapper table) diff --git a/src/main/java/fr/igred/omero/GatewayWrapper.java b/src/main/java/fr/igred/omero/GatewayWrapper.java index efeab9f9..d0e2a3d1 100644 --- a/src/main/java/fr/igred/omero/GatewayWrapper.java +++ b/src/main/java/fr/igred/omero/GatewayWrapper.java @@ -35,6 +35,8 @@ import omero.gateway.facility.MetadataFacility; import omero.gateway.facility.ROIFacility; import omero.gateway.facility.TablesFacility; +import omero.gateway.model.ExperimenterData; +import omero.log.SimpleLogger; import omero.model.FileAnnotationI; import omero.model.IObject; @@ -55,7 +57,7 @@ public abstract class GatewayWrapper { /** Gateway linking the code to OMERO, only linked to one group. */ - private final Gateway gateway; + private Gateway gateway; /** Security context of the user, contains the permissions of the user in this group. */ private SecurityContext ctx; @@ -76,15 +78,16 @@ protected GatewayWrapper(Gateway gateway) { /** * Abstract constructor of the GatewayWrapper class. + *

Null arguments will be replaced with default empty objects. * * @param gateway The Gateway. * @param ctx The Security Context. * @param user The connected user. */ protected GatewayWrapper(Gateway gateway, SecurityContext ctx, ExperimenterWrapper user) { - this.gateway = gateway; - this.ctx = ctx; - this.user = user; + this.gateway = gateway != null ? gateway : new Gateway(new SimpleLogger()); + this.user = user != null ? user : new ExperimenterWrapper(new ExperimenterData()); + this.ctx = ctx != null ? ctx : new SecurityContext(-1); } @@ -162,7 +165,7 @@ public String getSessionId() throws ServiceException { * @return See above. */ public boolean isConnected() { - return gateway.isConnected() && ctx != null; + return gateway.isConnected(); } @@ -237,6 +240,7 @@ public void connect(LoginCredentials cred) throws ServiceException { } this.ctx = new SecurityContext(user.getGroupId()); this.ctx.setExperimenter(this.user.asExperimenterData()); + this.ctx.setServerInformation(cred.getServer()); } @@ -244,13 +248,16 @@ public void connect(LoginCredentials cred) throws ServiceException { * Disconnects the user */ public void disconnect() { - if (gateway.isConnected()) { - if (ctx != null) { - ctx.setExperimenter(null); + if (isConnected()) { + boolean sudo = ctx.isSudo(); + user = new ExperimenterWrapper(new ExperimenterData()); + ctx = new SecurityContext(-1); + ctx.setExperimenter(user.asExperimenterData()); + if (sudo) { + gateway = new Gateway(gateway.getLogger()); + } else { + gateway.disconnect(); } - ctx = null; - user = null; - gateway.disconnect(); } } @@ -410,7 +417,7 @@ public IObject save(IObject object) throws ServiceException, AccessException, Ex * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ void delete(IObject object) @@ -432,7 +439,7 @@ void delete(IObject object) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ void delete(List objects) @@ -454,7 +461,7 @@ void delete(List objects) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public void deleteFile(Long id) @@ -463,5 +470,22 @@ public void deleteFile(Long id) delete(file); } + + /** + * Overridden to return the host name, the group ID, the username and the connection status. + * + * @return See above. + */ + @Override + public String toString() { + String host = ctx.getServerInformation() != null ? ctx.getServerInformation().getHost() : "null"; + return String.format("%s{host=%s, groupID=%d, userID=%d, connected=%b}", + getClass().getSimpleName(), + host, + ctx.getGroupID(), + user.getId(), + gateway.isConnected()); + } + } diff --git a/src/main/java/fr/igred/omero/GenericObjectWrapper.java b/src/main/java/fr/igred/omero/GenericObjectWrapper.java index 2c5286c8..bbcaf510 100644 --- a/src/main/java/fr/igred/omero/GenericObjectWrapper.java +++ b/src/main/java/fr/igred/omero/GenericObjectWrapper.java @@ -28,7 +28,6 @@ import omero.model.IObject; import java.sql.Timestamp; -import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; @@ -46,6 +45,7 @@ */ public abstract class GenericObjectWrapper { + /** Wrapped object */ protected T data; @@ -105,7 +105,7 @@ protected GenericObjectWrapper(T object) { * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ protected static void delete(Client client, IObject object) @@ -123,17 +123,12 @@ protected static void delete(Client client, IObject object) * @return Distinct objects list, sorted by ID. */ public static > List distinct(Collection objects) { - Collection ids = new ArrayList<>(objects.size()); - - List purged = new ArrayList<>(objects.size()); - for (T image : objects) { - if (!ids.contains(image.getId())) { - ids.add(image.getId()); - purged.add(image); - } - } - purged.sort(Comparator.comparing(T::getId)); - return purged; + return objects.stream() + .collect(Collectors.toMap(T::getId, o -> o)) + .values() + .stream() + .sorted(Comparator.comparing(T::getId)) + .collect(Collectors.toList()); } diff --git a/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java b/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java index eee75e10..c9738788 100644 --- a/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java @@ -14,6 +14,7 @@ * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin * Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + package fr.igred.omero.annotations; @@ -33,6 +34,10 @@ import static fr.igred.omero.exception.ExceptionHandler.handleServiceOrServer; +/** + * Class containing a FileAnnotationData object. + *

Wraps function calls to the FileAnnotationData contained. + */ public class FileAnnotationWrapper extends GenericAnnotationWrapper { /** diff --git a/src/main/java/fr/igred/omero/annotations/MapAnnotationWrapper.java b/src/main/java/fr/igred/omero/annotations/MapAnnotationWrapper.java index 46128065..9bb4ce37 100644 --- a/src/main/java/fr/igred/omero/annotations/MapAnnotationWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/MapAnnotationWrapper.java @@ -26,7 +26,7 @@ /** * Class containing a MapAnnotationData, a MapAnnotationData contains a list of NamedValue(Key-Value pair). - *

Implements function using the MapAnnotationData contained + *

Wraps function calls to the MapAnnotationData contained. */ public class MapAnnotationWrapper extends GenericAnnotationWrapper { diff --git a/src/main/java/fr/igred/omero/annotations/TableWrapper.java b/src/main/java/fr/igred/omero/annotations/TableWrapper.java index 43bd257e..175acff3 100644 --- a/src/main/java/fr/igred/omero/annotations/TableWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/TableWrapper.java @@ -130,7 +130,7 @@ public TableWrapper(TableData table) { * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. */ - public TableWrapper(Client client, ResultsTable results, Long imageId, List ijRois) + public TableWrapper(Client client, ResultsTable results, Long imageId, List ijRois) throws ServiceException, AccessException, ExecutionException { this(client, results, imageId, ijRois, ROIWrapper.IJ_PROPERTY); } @@ -150,7 +150,8 @@ public TableWrapper(Client client, ResultsTable results, Long imageId, List * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. */ - public TableWrapper(Client client, ResultsTable results, Long imageId, List ijRois, String roiProperty) + public TableWrapper(Client client, ResultsTable results, Long imageId, List ijRois, + String roiProperty) throws ServiceException, AccessException, ExecutionException { roiProperty = ROIWrapper.checkProperty(roiProperty); @@ -395,7 +396,7 @@ public String toString() { * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. */ - public void addRows(Client client, ResultsTable results, Long imageId, List ijRois) + public void addRows(Client client, ResultsTable results, Long imageId, List ijRois) throws ServiceException, AccessException, ExecutionException { this.addRows(client, results, imageId, ijRois, ROIWrapper.IJ_PROPERTY); } @@ -415,7 +416,7 @@ public void addRows(Client client, ResultsTable results, Long imageId, List * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. */ - public void addRows(Client client, ResultsTable results, Long imageId, List ijRois, + public void addRows(Client client, ResultsTable results, Long imageId, List ijRois, String roiProperty) throws ServiceException, AccessException, ExecutionException { roiProperty = ROIWrapper.checkProperty(roiProperty); @@ -497,7 +498,9 @@ public Object getData(int x, int y) { /** - * @return fileId of the table. + * Returns the fileId of the table. + * + * @return See above. */ public Long getFileId() { return fileId; @@ -515,7 +518,9 @@ public void setFileId(Long fileId) { /** - * @return id of the table. + * Returns the table ID. + * + * @return See above. */ public Long getId() { return id; @@ -533,7 +538,9 @@ public void setId(Long id) { /** - * @return name of the table. + * Returns the name of the table. + * + * @return See above. */ public String getName() { return name; @@ -551,7 +558,9 @@ public void setName(String name) { /** - * @return number of column in the table. + * Returns the number of columns in the table. + * + * @return See above. */ public int getColumnCount() { return columnCount; @@ -559,9 +568,11 @@ public int getColumnCount() { /** + * Returns the name of the column. + * * @param column Column number. * - * @return The name of the column. + * @return See above. */ public String getColumnName(int column) { return columns[column].getName(); @@ -569,9 +580,11 @@ public String getColumnName(int column) { /** + * Returns the type of the column. + * * @param column Column number. * - * @return The type of the column. + * @return See above. */ public Class getColumnType(int column) { return columns[column].getType(); @@ -579,7 +592,9 @@ public Class getColumnType(int column) { /** - * @return number of row in the table. + * Returns the number of rows in the table. + * + * @return See above. */ public int getRowCount() { return rowCount; @@ -644,14 +659,14 @@ public void addRow(Object... os) { data[i][row] = o; } row++; + } else if (row >= rowCount) { + if (rowCount == 0) { + throw new IndexOutOfBoundsException("Row size is 0"); + } else { + throw new IndexOutOfBoundsException("The table is already complete"); + } } else { - if (row >= rowCount) { - if (rowCount == 0) - throw new IndexOutOfBoundsException("Row size is 0"); - else - throw new IndexOutOfBoundsException("The table is already complete"); - } else - throw new IllegalArgumentException("Argument count is different than the column size"); + throw new IllegalArgumentException("Argument count is different than the column size"); } } @@ -664,6 +679,11 @@ public void truncateRow() { } + /** + * Creates the corresponding TableData object. + * + * @return See above. + */ public TableData createTable() { if (!isComplete()) truncateRow(); diff --git a/src/main/java/fr/igred/omero/annotations/TagAnnotationWrapper.java b/src/main/java/fr/igred/omero/annotations/TagAnnotationWrapper.java index e1901702..50157823 100644 --- a/src/main/java/fr/igred/omero/annotations/TagAnnotationWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/TagAnnotationWrapper.java @@ -27,8 +27,8 @@ /** - * Class containing a TagAnnotationData - *

Implements function using the TagAnnotationData contained. + * Class containing a TagAnnotationData object. + *

Wraps function calls to the TagAnnotationData contained. */ public class TagAnnotationWrapper extends GenericAnnotationWrapper { diff --git a/src/main/java/fr/igred/omero/exception/AccessException.java b/src/main/java/fr/igred/omero/exception/AccessException.java index 8f7a737a..75abbf3e 100644 --- a/src/main/java/fr/igred/omero/exception/AccessException.java +++ b/src/main/java/fr/igred/omero/exception/AccessException.java @@ -22,6 +22,9 @@ /** Reports an error occurred while trying to pull out data from the server. */ public class AccessException extends DSAccessException { + private static final long serialVersionUID = 3118406890894909851L; + + /** * Constructs a new exception with the specified detail message and cause. * diff --git a/src/main/java/fr/igred/omero/exception/ExceptionHandler.java b/src/main/java/fr/igred/omero/exception/ExceptionHandler.java index 873ecbf2..ff9c2e5a 100644 --- a/src/main/java/fr/igred/omero/exception/ExceptionHandler.java +++ b/src/main/java/fr/igred/omero/exception/ExceptionHandler.java @@ -26,7 +26,7 @@ /** * Class with methods to handle OMERO exceptions */ -public class ExceptionHandler { +public final class ExceptionHandler { private ExceptionHandler() { } diff --git a/src/main/java/fr/igred/omero/exception/OMEROServerError.java b/src/main/java/fr/igred/omero/exception/OMEROServerError.java index 3f0f1fc7..2cb7f78c 100644 --- a/src/main/java/fr/igred/omero/exception/OMEROServerError.java +++ b/src/main/java/fr/igred/omero/exception/OMEROServerError.java @@ -22,6 +22,9 @@ /** Reports an error occurred on the server. */ public class OMEROServerError extends ServerError { + private static final long serialVersionUID = 3769544644500634998L; + + /** * Constructs a new exception with the specified cause and detailed message. * diff --git a/src/main/java/fr/igred/omero/exception/ServiceException.java b/src/main/java/fr/igred/omero/exception/ServiceException.java index 91a71a07..8d40df68 100644 --- a/src/main/java/fr/igred/omero/exception/ServiceException.java +++ b/src/main/java/fr/igred/omero/exception/ServiceException.java @@ -26,6 +26,9 @@ */ public class ServiceException extends DSOutOfServiceException { + private static final long serialVersionUID = -3953926293960923221L; + + /** * Constructs a new exception with the specified cause and a generic message. * diff --git a/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java b/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java index 30dcd776..36b7fad2 100644 --- a/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java +++ b/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java @@ -24,6 +24,10 @@ import java.util.List; +/** + * Class containing an ExperimenterData object. + *

Wraps function calls to the ExperimenterData contained. + */ public class ExperimenterWrapper extends GenericObjectWrapper { /** @@ -37,7 +41,9 @@ public ExperimenterWrapper(ExperimenterData experimenter) { /** - * @return ExperimenterData contained. + * Returns the ExperimenterData contained. + * + * @return See above. */ public ExperimenterData asExperimenterData() { return data; diff --git a/src/main/java/fr/igred/omero/meta/GroupWrapper.java b/src/main/java/fr/igred/omero/meta/GroupWrapper.java index 050086cd..8a281245 100644 --- a/src/main/java/fr/igred/omero/meta/GroupWrapper.java +++ b/src/main/java/fr/igred/omero/meta/GroupWrapper.java @@ -24,6 +24,10 @@ import java.util.List; +/** + * Class containing a GroupData object. + *

Wraps function calls to the GroupData contained. + */ public class GroupWrapper extends GenericObjectWrapper { /** Indicates that the group is {@code Private} i.e. RW----. */ @@ -78,7 +82,9 @@ public void setName(String name) { /** - * @return GroupData contained. + * Returns the GroupData contained. + * + * @return See above. */ public GroupData asGroupData() { return data; diff --git a/src/main/java/fr/igred/omero/repository/ChannelWrapper.java b/src/main/java/fr/igred/omero/repository/ChannelWrapper.java index 08268dfa..e440dc13 100644 --- a/src/main/java/fr/igred/omero/repository/ChannelWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ChannelWrapper.java @@ -24,6 +24,10 @@ import java.awt.Color; +/** + * Class containing a ChannelData object. + *

Wraps function calls to the ChannelData contained. + */ public class ChannelWrapper extends GenericObjectWrapper { @@ -38,7 +42,9 @@ public ChannelWrapper(ChannelData channel) { /** - * @return ChannelData contained. + * Returns the ChannelData contained. + * + * @return See above. */ public ChannelData asChannelData() { return data; diff --git a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java index c67d3ca9..bb7c76ad 100644 --- a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java +++ b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java @@ -25,18 +25,7 @@ import fr.igred.omero.exception.OMEROServerError; import fr.igred.omero.exception.ServiceException; import fr.igred.omero.roi.ROIWrapper; -import loci.formats.in.DefaultMetadataOptions; -import loci.formats.in.MetadataLevel; -import ome.formats.OMEROMetadataStoreClient; -import ome.formats.importer.ImportCandidates; -import ome.formats.importer.ImportConfig; -import ome.formats.importer.ImportContainer; -import ome.formats.importer.ImportLibrary; -import ome.formats.importer.OMEROWrapper; -import ome.formats.importer.cli.ErrorHandler; -import ome.formats.importer.cli.LoggingImportMonitor; import omero.RLong; -import omero.ServerError; import omero.gateway.exception.DSAccessException; import omero.gateway.exception.DSOutOfServiceException; import omero.gateway.model.DatasetData; @@ -45,7 +34,6 @@ import omero.model.DatasetImageLink; import omero.model.DatasetImageLinkI; import omero.model.IObject; -import omero.model.Pixels; import java.io.IOException; import java.util.ArrayList; @@ -55,19 +43,18 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.stream.Collectors; import static fr.igred.omero.exception.ExceptionHandler.handleServiceOrAccess; /** - * Class containing a DatasetData. - *

Implements function using the DatasetData contained + * Class containing a DatasetData object. + *

Wraps function calls to the DatasetData contained. */ public class DatasetWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "DatasetAnnotationLink"; private static final Long[] LONGS = new Long[0]; @@ -120,7 +107,9 @@ public void setName(String name) { /** - * @return the DatasetData contained. + * Returns the DatasetData contained. + * + * @return See above. */ public DatasetData asDatasetData() { return data; @@ -175,7 +164,7 @@ public List getProjects(Client client) throws OMEROServerError, ServiceException, AccessException, ExecutionException { List os = client.findByQuery("select link.parent from ProjectDatasetLink as link " + "where link.child=" + getId()); - return client.getProjects(os.stream().map(IObject::getId).map(RLong::getValue).toArray(Long[]::new)); + return client.getProjects(os.stream().map(IObject::getId).map(RLong::getValue).distinct().toArray(Long[]::new)); } @@ -238,7 +227,8 @@ public List getImages(Client client, String name) public List getImagesLike(Client client, String motif) throws ServiceException, AccessException, ExecutionException { List images = getImages(client); - final String regexp = ".*" + motif + ".*"; + + String regexp = ".*" + motif + ".*"; images.removeIf(image -> !image.getName().matches(regexp)); return images; } @@ -420,7 +410,7 @@ public void addImage(Client client, ImageWrapper image) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public void removeImage(Client client, ImageWrapper image) @@ -445,31 +435,7 @@ public void removeImage(Client client, ImageWrapper image) */ public boolean importImages(Client client, String... paths) throws ServiceException, OMEROServerError, AccessException, IOException, ExecutionException { - boolean success; - - ImportConfig config = new ImportConfig(); - config.target.set("Dataset:" + data.getId()); - config.username.set(client.getUser().getUserName()); - config.email.set(client.getUser().getEmail()); - - OMEROMetadataStoreClient store = client.getImportStore(); - try (OMEROWrapper reader = new OMEROWrapper(config)) { - store.logVersionInfo(config.getIniVersionNumber()); - reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL)); - - ImportLibrary library = new ImportLibrary(store, reader); - library.addObserver(new LoggingImportMonitor()); - - ErrorHandler handler = new ErrorHandler(config); - - ImportCandidates candidates = new ImportCandidates(reader, paths, handler); - success = library.importCandidates(config, candidates); - } catch (ServerError se) { - throw new OMEROServerError(se); - } finally { - store.logout(); - } - + boolean success = importImages(client, data, paths); refresh(client); return success; } @@ -490,47 +456,9 @@ public boolean importImages(Client client, String... paths) */ public List importImage(Client client, String path) throws ServiceException, AccessException, OMEROServerError, ExecutionException { - ImportConfig config = new ImportConfig(); - config.target.set("Dataset:" + data.getId()); - config.username.set(client.getUser().getUserName()); - config.email.set(client.getUser().getEmail()); - - Collection pixels = new ArrayList<>(1); - - OMEROMetadataStoreClient store = client.getImportStore(); - try (OMEROWrapper reader = new OMEROWrapper(config)) { - store.logVersionInfo(config.getIniVersionNumber()); - reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL)); - - ImportLibrary library = new ImportLibrary(store, reader); - library.addObserver(new LoggingImportMonitor()); - - ErrorHandler handler = new ErrorHandler(config); - - ImportCandidates candidates = new ImportCandidates(reader, new String[]{path}, handler); - - ExecutorService uploadThreadPool = Executors.newFixedThreadPool(config.parallelUpload.get()); - - List containers = candidates.getContainers(); - if (containers != null) { - for (int i = 0; i < containers.size(); i++) { - ImportContainer container = containers.get(i); - container.setTarget(data.asDataset()); - List imported = library.importImage(container, uploadThreadPool, i); - pixels.addAll(imported); - } - } - uploadThreadPool.shutdown(); - } catch (Throwable e) { - throw new OMEROServerError(e); - } finally { - store.logout(); - } + List ids = importImage(client, data, path); refresh(client); - - List ids = new ArrayList<>(pixels.size()); - pixels.forEach(pix -> ids.add(pix.getImage().getId().getValue())); - return ids.stream().distinct().collect(Collectors.toList()); + return ids; } @@ -571,6 +499,7 @@ public List replaceImages(Client client, } } descriptions.removeIf(s -> s == null || s.trim().isEmpty()); + //noinspection HardcodedLineSeparator newImage.setDescription(String.join("\n", descriptions)); newImage.saveAndUpdate(client); return orphaned; diff --git a/src/main/java/fr/igred/omero/repository/FolderWrapper.java b/src/main/java/fr/igred/omero/repository/FolderWrapper.java index cfa434d8..145aecf5 100644 --- a/src/main/java/fr/igred/omero/repository/FolderWrapper.java +++ b/src/main/java/fr/igred/omero/repository/FolderWrapper.java @@ -45,11 +45,12 @@ /** - * Class containing a FolderData. - *

Implements function using the FolderData contained. + * Class containing a FolderData object. + *

Wraps function calls to the FolderData contained. */ public class FolderWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "FolderAnnotationLink"; /** ID of the associated image */ diff --git a/src/main/java/fr/igred/omero/repository/GenericRepositoryObjectWrapper.java b/src/main/java/fr/igred/omero/repository/GenericRepositoryObjectWrapper.java index 18e432f9..5b878b1d 100644 --- a/src/main/java/fr/igred/omero/repository/GenericRepositoryObjectWrapper.java +++ b/src/main/java/fr/igred/omero/repository/GenericRepositoryObjectWrapper.java @@ -17,6 +17,7 @@ import fr.igred.omero.Client; +import fr.igred.omero.GatewayWrapper; import fr.igred.omero.GenericObjectWrapper; import fr.igred.omero.annotations.FileAnnotationWrapper; import fr.igred.omero.annotations.GenericAnnotationWrapper; @@ -26,6 +27,17 @@ import fr.igred.omero.exception.AccessException; import fr.igred.omero.exception.OMEROServerError; import fr.igred.omero.exception.ServiceException; +import loci.formats.in.DefaultMetadataOptions; +import loci.formats.in.MetadataLevel; +import ome.formats.OMEROMetadataStoreClient; +import ome.formats.importer.ImportCandidates; +import ome.formats.importer.ImportConfig; +import ome.formats.importer.ImportContainer; +import ome.formats.importer.ImportLibrary; +import ome.formats.importer.OMEROWrapper; +import ome.formats.importer.cli.ErrorHandler; +import ome.formats.importer.cli.LoggingImportMonitor; +import omero.ServerError; import omero.constants.metadata.NSCLIENTMAPANNOTATION; import omero.gateway.exception.DSAccessException; import omero.gateway.exception.DSOutOfServiceException; @@ -35,11 +47,14 @@ import omero.gateway.model.MapAnnotationData; import omero.gateway.model.TableData; import omero.gateway.model.TagAnnotationData; +import omero.gateway.util.PojoMapper; import omero.model.IObject; import omero.model.NamedValue; +import omero.model.Pixels; import omero.model.TagAnnotationI; import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -49,6 +64,8 @@ import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.stream.Collectors; import static fr.igred.omero.exception.ExceptionHandler.handleServiceOrAccess; @@ -319,7 +336,7 @@ public Map getKeyValuePairs(Client client) /** - * Gets the value from a Key-Value pair associated to the object + * Gets the value from a Key-Value pair associated to the object. * * @param client The client handling the connection. * @param key Key researched. @@ -344,8 +361,8 @@ public String getValue(Client client, String key) /** - * Adds a List of Key-Value pair to the object - *

The list is contained in the MapAnnotationWrapper + * Adds a List of Key-Value pair to the object. + *

The list is contained in the MapAnnotationWrapper. * * @param client The client handling the connection. * @param mapAnnotation MapAnnotationWrapper containing a list of NamedValue. @@ -367,7 +384,7 @@ public void addMapAnnotation(Client client, MapAnnotationWrapper mapAnnotation) /** - * Adds a table to the object in OMERO + * Adds a table to the object in OMERO. * * @param client The client handling the connection. * @param table Table to add to the object. @@ -384,7 +401,7 @@ public void addTable(Client client, TableWrapper table) Collection tables = client.getTablesFacility() .getAvailableTables(client.getCtx(), data); - final long fileId = tableData.getOriginalFileId(); + long fileId = tableData.getOriginalFileId(); long id = tables.stream().filter(v -> v.getFileID() == fileId) .mapToLong(DataObject::getId).max().orElse(-1L); @@ -397,7 +414,63 @@ public void addTable(Client client, TableWrapper table) /** - * Gets a certain table linked to the object in OMERO + * Adds a table to the object in OMERO and unlinks or deletes previous tables with the same name. + * + * @param client The client handling the connection. + * @param table Table to add to the object. + * @param policy Whether older tables should be unlinked, deleted or deleted only if they become orphaned. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + * @throws InterruptedException The thread was interrupted. + * @throws OMEROServerError Server error. + */ + public void addAndReplaceTable(Client client, TableWrapper table, ReplacePolicy policy) + throws ServiceException, AccessException, ExecutionException, OMEROServerError, InterruptedException { + Collection tables = new ArrayList<>(0); + try { + tables = client.getTablesFacility() + .getAvailableTables(client.getCtx(), data) + .stream() + .map(FileAnnotationWrapper::new) + .collect(Collectors.toList()); + } catch (DSOutOfServiceException | DSAccessException e) { + handleServiceOrAccess(e, "Cannot get tables from " + this); + } + addTable(client, table); + tables.removeIf(t -> !t.getDescription().equals(table.getName())); + for (FileAnnotationWrapper f : tables) { + this.unlink(client, f); + if (policy == ReplacePolicy.DELETE || + policy == ReplacePolicy.DELETE_ORPHANED && f.countAnnotationLinks(client) == 0) { + client.deleteFile(f.getId()); + } + } + } + + + /** + * Adds a table to the object in OMERO and unlinks previous tables with the same name, or deletes them if they're + * orphaned. + * + * @param client The client handling the connection. + * @param table Table to add to the object. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + * @throws InterruptedException The thread was interrupted. + * @throws OMEROServerError Server error. + */ + public void addAndReplaceTable(Client client, TableWrapper table) + throws ServiceException, AccessException, ExecutionException, OMEROServerError, InterruptedException { + addAndReplaceTable(client, table, ReplacePolicy.DELETE_ORPHANED); + } + + + /** + * Gets a certain table linked to the object in OMERO. * * @param client The client handling the connection. * @param fileId FileId of the table researched. @@ -481,7 +554,7 @@ public long addFile(Client client, File file) throws ExecutionException, Interru /** - * Uploads a file, links it to the object and unlinks previous files with the same name, or deletes them. + * Uploads a file, links it to the object and unlinks or deletes previous files with the same name. * * @param client The client handling the connection. * @param file File to add. @@ -493,7 +566,7 @@ public long addFile(Client client, File file) throws ExecutionException, Interru * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. * @throws InterruptedException The thread was interrupted. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. */ public long addAndReplaceFile(Client client, File file, ReplacePolicy policy) throws ExecutionException, InterruptedException, AccessException, ServiceException, OMEROServerError { @@ -520,7 +593,8 @@ public long addAndReplaceFile(Client client, File file, ReplacePolicy policy) /** - * Uploads a file, links it to the object and unlinks previous files with the same name, or deletes them. + * Uploads a file, links it to the object and unlinks previous files with the same name, or deletes them if they're + * orphaned. * * @param client The client handling the connection. * @param file File to add. @@ -531,11 +605,11 @@ public long addAndReplaceFile(Client client, File file, ReplacePolicy policy) * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. * @throws InterruptedException The thread was interrupted. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. */ public long addAndReplaceFile(Client client, File file) throws ExecutionException, InterruptedException, AccessException, ServiceException, OMEROServerError { - return addAndReplaceFile(client, file, ReplacePolicy.UNLINK); + return addAndReplaceFile(client, file, ReplacePolicy.DELETE_ORPHANED); } @@ -599,7 +673,7 @@ public List getFileAnnotations(Client client) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public > void unlink(Client client, A annotation) @@ -618,7 +692,7 @@ public > void unlink(Client client, A anno * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ protected void removeLink(Client client, String linkType, long childId) @@ -680,6 +754,109 @@ public void copyAnnotationLinks(Client client, GenericRepositoryObjectWrapper } + /** + * Imports all images candidates in the paths to the target in OMERO. + * + * @param client The client handling the connection. + * @param target The import target. + * @param paths Paths to the image files on the computer. + * + * @return If the import did not exit because of an error. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws OMEROServerError Server error. + * @throws IOException Cannot read file. + */ + protected static boolean importImages(GatewayWrapper client, DataObject target, String... paths) + throws ServiceException, OMEROServerError, IOException { + boolean success; + + ImportConfig config = new ImportConfig(); + String type = PojoMapper.getGraphType(target.getClass()); + config.target.set(type + ":" + target.getId()); + config.username.set(client.getUser().getUserName()); + config.email.set(client.getUser().getEmail()); + + OMEROMetadataStoreClient store = client.getImportStore(); + try (OMEROWrapper reader = new OMEROWrapper(config)) { + store.logVersionInfo(config.getIniVersionNumber()); + reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL)); + + ImportLibrary library = new ImportLibrary(store, reader); + library.addObserver(new LoggingImportMonitor()); + + ErrorHandler handler = new ErrorHandler(config); + + ImportCandidates candidates = new ImportCandidates(reader, paths, handler); + success = library.importCandidates(config, candidates); + } catch (ServerError se) { + throw new OMEROServerError(se); + } finally { + store.logout(); + } + + return success; + } + + + /** + * Imports one image file to the target in OMERO. + * + * @param client The client handling the connection. + * @param target The import target. + * @param path Path to the image file on the computer. + * + * @return The list of IDs of the newly imported images. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws OMEROServerError Server error. + */ + protected static List importImage(GatewayWrapper client, DataObject target, String path) + throws ServiceException, OMEROServerError { + ImportConfig config = new ImportConfig(); + String type = PojoMapper.getGraphType(target.getClass()); + config.target.set(type + ":" + target.getId()); + config.username.set(client.getUser().getUserName()); + config.email.set(client.getUser().getEmail()); + + Collection pixels = new ArrayList<>(1); + + OMEROMetadataStoreClient store = client.getImportStore(); + try (OMEROWrapper reader = new OMEROWrapper(config)) { + store.logVersionInfo(config.getIniVersionNumber()); + reader.setMetadataOptions(new DefaultMetadataOptions(MetadataLevel.ALL)); + + ImportLibrary library = new ImportLibrary(store, reader); + library.addObserver(new LoggingImportMonitor()); + + ErrorHandler handler = new ErrorHandler(config); + + ImportCandidates candidates = new ImportCandidates(reader, new String[]{path}, handler); + + ExecutorService uploadThreadPool = Executors.newFixedThreadPool(config.parallelUpload.get()); + + List containers = candidates.getContainers(); + if (containers != null) { + for (int i = 0; i < containers.size(); i++) { + ImportContainer container = containers.get(i); + container.setTarget(target.asIObject()); + List imported = library.importImage(container, uploadThreadPool, i); + pixels.addAll(imported); + } + } + uploadThreadPool.shutdown(); + } catch (Throwable e) { + throw new OMEROServerError(e); + } finally { + store.logout(); + } + + List ids = new ArrayList<>(pixels.size()); + pixels.forEach(pix -> ids.add(pix.getImage().getId().getValue())); + return ids.stream().distinct().collect(Collectors.toList()); + } + + /** * Policy to specify how to handle objects when they are replaced. */ diff --git a/src/main/java/fr/igred/omero/repository/ImageWrapper.java b/src/main/java/fr/igred/omero/repository/ImageWrapper.java index fc3bdf0d..29884c63 100644 --- a/src/main/java/fr/igred/omero/repository/ImageWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ImageWrapper.java @@ -48,6 +48,8 @@ import omero.model.Folder; import omero.model.IObject; import omero.model.Length; +import omero.model.Time; +import omero.model.WellSample; import javax.imageio.ImageIO; import java.awt.Color; @@ -75,10 +77,11 @@ /** * Class containing an ImageData. - *

Implements function using the ImageData contained + *

Wraps function calls to the ImageData contained. */ public class ImageWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "ImageAnnotationLink"; @@ -116,7 +119,9 @@ public void setName(String name) { /** - * @return ImageData contained. + * Returns the ImageData contained. + * + * @return See above. */ public ImageData asImageData() { return data; @@ -165,6 +170,36 @@ protected String annotationLinkType() { } + /** + * Sets the calibration. + */ + private void setCalibration(Calibration calibration) { + PixelsWrapper pixels = this.getPixels(); + Length spacingX = pixels.getPixelSizeX(); + Length spacingY = pixels.getPixelSizeY(); + Length spacingZ = pixels.getPixelSizeZ(); + Time stepT = pixels.getTimeIncrement(); + + if (spacingX != null) { + calibration.setXUnit(spacingX.getSymbol()); + calibration.pixelWidth = spacingX.getValue(); + } + if (spacingY != null) { + calibration.setYUnit(spacingY.getSymbol()); + calibration.pixelHeight = spacingY.getValue(); + } + if (spacingZ != null) { + calibration.setZUnit(spacingZ.getSymbol()); + calibration.pixelDepth = spacingZ.getValue(); + } + if (stepT != null) { + calibration.setTimeUnit(stepT.getSymbol()); + calibration.frameInterval = stepT.getValue(); + } + + } + + /** * Retrieves the projects containing this image * @@ -179,12 +214,12 @@ protected String annotationLinkType() { */ public List getProjects(Client client) throws OMEROServerError, ServiceException, AccessException, ExecutionException { - List datasets = getDatasets(client); - List projects = new ArrayList<>(datasets.size()); + List datasets = getDatasets(client); + Collection projects = new ArrayList<>(datasets.size()); for (DatasetWrapper dataset : datasets) { projects.addAll(dataset.getProjects(client)); } - return projects; + return distinct(projects); } @@ -204,7 +239,72 @@ public List getDatasets(Client client) throws OMEROServerError, ServiceException, AccessException, ExecutionException { List os = client.findByQuery("select link.parent from DatasetImageLink as link " + "where link.child=" + getId()); - return client.getDatasets(os.stream().map(IObject::getId).map(RLong::getValue).toArray(Long[]::new)); + + return client.getDatasets(os.stream().map(IObject::getId).map(RLong::getValue).distinct().toArray(Long[]::new)); + } + + + /** + * Retrieves the wells containing this image + * + * @param client The client handling the connection. + * + * @return See above + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public List getWells(Client client) throws AccessException, ServiceException, ExecutionException { + Long[] ids = this.asImageData() + .asImage() + .copyWellSamples() + .stream() + .map(WellSample::getWell) + .map(IObject::getId) + .map(RLong::getValue) + .sorted().distinct() + .toArray(Long[]::new); + return client.getWells(ids); + } + + + /** + * Retrieves the plates containing this image + * + * @param client The client handling the connection. + * + * @return See above + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public List getPlates(Client client) throws AccessException, ServiceException, ExecutionException { + return distinct(getWells(client).stream().map(WellWrapper::getPlate).collect(Collectors.toList())); + } + + + /** + * Retrieves the screens containing this image + * + * @param client The client handling the connection. + * + * @return See above + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + * @throws OMEROServerError Server error. + */ + public List getScreens(Client client) + throws AccessException, ServiceException, ExecutionException, OMEROServerError { + List plates = getPlates(client); + Collection screens = new ArrayList<>(plates.size()); + for (PlateWrapper plate : plates) { + screens.addAll(plate.getScreens(client)); + } + return distinct(screens); } @@ -399,14 +499,14 @@ public ImagePlus toImagePlus(Client client) /** - * Gets the imagePlus generated from the image from OMERO corresponding to the bound + * Gets the imagePlus generated from the image from OMERO corresponding to the bound. * - * @param client The client handling the connection. - * @param xBound Array containing the X bound from which the pixels should be retrieved. - * @param yBound Array containing the Y bound from which the pixels should be retrieved. - * @param cBound Array containing the C bound from which the pixels should be retrieved. - * @param zBound Array containing the Z bound from which the pixels should be retrieved. - * @param tBound Array containing the T bound from which the pixels should be retrieved. + * @param client The client handling the connection. + * @param xBounds Array containing the X bounds from which the pixels should be retrieved. + * @param yBounds Array containing the Y bounds from which the pixels should be retrieved. + * @param cBounds Array containing the C bounds from which the pixels should be retrieved. + * @param zBounds Array containing the Z bounds from which the pixels should be retrieved. + * @param tBounds Array containing the T bounds from which the pixels should be retrieved. * * @return an ImagePlus from the ij library. * @@ -414,13 +514,18 @@ public ImagePlus toImagePlus(Client client) * @throws AccessException If an error occurs while retrieving the plane data from the pixels source. * @throws ExecutionException A Facility can't be retrieved or instantiated. */ - public ImagePlus toImagePlus(Client client, int[] xBound, int[] yBound, int[] cBound, int[] zBound, int[] tBound) + public ImagePlus toImagePlus(Client client, + int[] xBounds, + int[] yBounds, + int[] cBounds, + int[] zBounds, + int[] tBounds) throws ServiceException, AccessException, ExecutionException { PixelsWrapper pixels = this.getPixels(); boolean createdRDF = pixels.createRawDataFacility(client); - Bounds bounds = pixels.getBounds(xBound, yBound, cBound, zBound, tBound); + Bounds bounds = pixels.getBounds(xBounds, yBounds, cBounds, zBounds, tBounds); int startX = bounds.getStart().getX(); int startY = bounds.getStart().getY(); @@ -434,31 +539,14 @@ public ImagePlus toImagePlus(Client client, int[] xBound, int[] yBound, int[] cB int sizeZ = bounds.getSize().getZ(); int sizeT = bounds.getSize().getT(); - Length spacingX = pixels.getPixelSizeX(); - Length spacingY = pixels.getPixelSizeY(); - Length spacingZ = pixels.getPixelSizeZ(); - int pixelType = FormatTools.pixelTypeFromString(pixels.getPixelType()); int bpp = FormatTools.getBytesPerPixel(pixelType); ImagePlus imp = IJ.createHyperStack(data.getName(), sizeX, sizeY, sizeC, sizeZ, sizeT, bpp * 8); - Calibration cal = imp.getCalibration(); - - if (spacingX != null) { - cal.setXUnit(spacingX.getUnit().name()); - cal.pixelWidth = spacingX.getValue(); - } - if (spacingY != null) { - cal.setYUnit(spacingY.getUnit().name()); - cal.pixelHeight = spacingY.getValue(); - } - if (spacingZ != null) { - cal.setZUnit(spacingZ.getUnit().name()); - cal.pixelDepth = spacingZ.getValue(); - } - - imp.setCalibration(cal); + Calibration calibration = imp.getCalibration(); + setCalibration(calibration); + imp.setCalibration(calibration); boolean isFloat = FormatTools.isFloatingPoint(pixelType); @@ -512,6 +600,7 @@ public ImagePlus toImagePlus(Client client, int[] xBound, int[] yBound, int[] cB if (createdRDF) { pixels.destroyRawDataFacility(); } + imp.setPosition(1); return imp; } @@ -698,13 +787,14 @@ public BufferedImage getThumbnail(Client client, int size) throws ServiceExcepti */ public List download(Client client, String path) throws OMEROServerError, ServiceException, AccessException { + List files = new ArrayList<>(0); try { TransferFacility transfer = client.getGateway().getFacility(TransferFacility.class); - return transfer.downloadImage(client.getCtx(), path, getId()); + files = transfer.downloadImage(client.getCtx(), path, getId()); } catch (DSAccessException | DSOutOfServiceException | ExecutionException e) { handleException(e, "Could not download image " + getId() + ": " + e.getMessage()); } - return new ArrayList<>(0); + return files; } } diff --git a/src/main/java/fr/igred/omero/repository/PixelsWrapper.java b/src/main/java/fr/igred/omero/repository/PixelsWrapper.java index 2457313b..aab1e8dd 100644 --- a/src/main/java/fr/igred/omero/repository/PixelsWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PixelsWrapper.java @@ -26,13 +26,14 @@ import omero.gateway.model.PixelsData; import omero.gateway.rnd.Plane2D; import omero.model.Length; +import omero.model.Time; import java.util.concurrent.ExecutionException; /** - * Class containing a PixelData - *

Implements function using the PixelData contained + * Class containing a PixelData object. + *

Wraps function calls to the PixelData contained. */ public class PixelsWrapper extends GenericObjectWrapper { @@ -40,7 +41,7 @@ public class PixelsWrapper extends GenericObjectWrapper { public static final int MAX_DIST = 5000; /** Raw Data Facility to retrieve pixels */ - private RawDataFacility rawDataFacility = null; + private RawDataFacility rawDataFacility; /** @@ -150,6 +151,16 @@ public Length getPixelSizeZ() { } + /** + * Gets the time increment between time points. + * + * @return Time increment between time points. + */ + public Time getTimeIncrement() { + return data.asPixels().getTimeIncrement(); + } + + /** * Gets the size of the image on the X axis * @@ -248,11 +259,11 @@ public double[][][][][] getAllPixels(Client client) throws AccessException, Exec * Returns an array containing the value for each voxel corresponding to the bounds * * @param client The client handling the connection. - * @param xBound Array containing the X bound from which the pixels should be retrieved. - * @param yBound Array containing the Y bound from which the pixels should be retrieved. - * @param cBound Array containing the C bound from which the pixels should be retrieved. - * @param zBound Array containing the Z bound from which the pixels should be retrieved. - * @param tBound Array containing the T bound from which the pixels should be retrieved. + * @param xBounds Array containing the X bounds from which the pixels should be retrieved. + * @param yBounds Array containing the Y bounds from which the pixels should be retrieved. + * @param cBounds Array containing the C bounds from which the pixels should be retrieved. + * @param zBounds Array containing the Z bounds from which the pixels should be retrieved. + * @param tBounds Array containing the T bounds from which the pixels should be retrieved. * * @return Array containing the value for each voxel of the image. * @@ -260,14 +271,14 @@ public double[][][][][] getAllPixels(Client client) throws AccessException, Exec * @throws ExecutionException A Facility can't be retrieved or instantiated. */ public double[][][][][] getAllPixels(Client client, - int[] xBound, - int[] yBound, - int[] cBound, - int[] zBound, - int[] tBound) + int[] xBounds, + int[] yBounds, + int[] cBounds, + int[] zBounds, + int[] tBounds) throws AccessException, ExecutionException { boolean rdf = createRawDataFacility(client); - Bounds lim = getBounds(xBound, yBound, cBound, zBound, tBound); + Bounds lim = getBounds(xBounds, yBounds, cBounds, zBounds, tBounds); Coordinates start = lim.getStart(); Coordinates size = lim.getSize(); @@ -350,11 +361,11 @@ public byte[][][][] getRawPixels(Client client, int bpp) throws AccessException, * Returns an array containing the raw values for each voxel for each plane corresponding to the bounds * * @param client The client handling the connection. - * @param xBound Array containing the X bound from which the pixels should be retrieved. - * @param yBound Array containing the Y bound from which the pixels should be retrieved. - * @param cBound Array containing the C bound from which the pixels should be retrieved. - * @param zBound Array containing the Z bound from which the pixels should be retrieved. - * @param tBound Array containing the T bound from which the pixels should be retrieved. + * @param xBounds Array containing the X bounds from which the pixels should be retrieved. + * @param yBounds Array containing the Y bounds from which the pixels should be retrieved. + * @param cBounds Array containing the C bounds from which the pixels should be retrieved. + * @param zBounds Array containing the Z bounds from which the pixels should be retrieved. + * @param tBounds Array containing the T bounds from which the pixels should be retrieved. * @param bpp Bytes per pixels of the image. * * @return a table of bytes containing the pixel values @@ -363,15 +374,15 @@ public byte[][][][] getRawPixels(Client client, int bpp) throws AccessException, * @throws ExecutionException A Facility can't be retrieved or instantiated. */ public byte[][][][] getRawPixels(Client client, - int[] xBound, - int[] yBound, - int[] cBound, - int[] zBound, - int[] tBound, + int[] xBounds, + int[] yBounds, + int[] cBounds, + int[] zBounds, + int[] tBounds, int bpp) throws ExecutionException, AccessException { boolean rdf = createRawDataFacility(client); - Bounds lim = getBounds(xBound, yBound, cBound, zBound, tBound); + Bounds lim = getBounds(xBounds, yBounds, cBounds, zBounds, tBounds); Coordinates start = lim.getStart(); Coordinates size = lim.getSize(); @@ -437,11 +448,11 @@ byte[] getRawTile(Client client, Coordinates start, int width, int height, int b /** * Checks all bounds * - * @param xBounds Array containing the X bound from which the pixels should be retrieved. - * @param yBounds Array containing the Y bound from which the pixels should be retrieved. - * @param cBounds Array containing the C bound from which the pixels should be retrieved. - * @param zBounds Array containing the Z bound from which the pixels should be retrieved. - * @param tBounds Array containing the T bound from which the pixels should be retrieved. + * @param xBounds Array containing the X bounds from which the pixels should be retrieved. + * @param yBounds Array containing the Y bounds from which the pixels should be retrieved. + * @param cBounds Array containing the C bounds from which the pixels should be retrieved. + * @param zBounds Array containing the Z bounds from which the pixels should be retrieved. + * @param tBounds Array containing the T bounds from which the pixels should be retrieved. * * @return 5D bounds. */ diff --git a/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java b/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java index 9330a60d..80e2c7cc 100644 --- a/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java @@ -14,6 +14,7 @@ * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin * Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + package fr.igred.omero.repository; @@ -30,8 +31,13 @@ import java.util.concurrent.ExecutionException; +/** + * Class containing a PlateAcquisitionData object. + *

Wraps function calls to the PlateAcquisitionData contained. + */ public class PlateAcquisitionWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "PlateAcquisitionAnnotationLink"; @@ -80,7 +86,9 @@ public void setName(String name) { /** - * @return the PlateAcquisitionData contained. + * Returns the PlateAcquisitionData contained. + * + * @return See above. */ public PlateAcquisitionData asPlateAcquisitionData() { return data; diff --git a/src/main/java/fr/igred/omero/repository/PlateWrapper.java b/src/main/java/fr/igred/omero/repository/PlateWrapper.java index 8c6c09d7..67946c3a 100644 --- a/src/main/java/fr/igred/omero/repository/PlateWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PlateWrapper.java @@ -14,17 +14,21 @@ * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin * Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + package fr.igred.omero.repository; import fr.igred.omero.Client; import fr.igred.omero.exception.AccessException; +import fr.igred.omero.exception.OMEROServerError; import fr.igred.omero.exception.ServiceException; import ome.model.units.BigResult; +import omero.RLong; import omero.gateway.exception.DSAccessException; import omero.gateway.exception.DSOutOfServiceException; import omero.gateway.model.PlateData; import omero.gateway.model.WellData; +import omero.model.IObject; import omero.model.Length; import omero.model.enums.UnitsLength; @@ -38,8 +42,13 @@ import static fr.igred.omero.exception.ExceptionHandler.handleServiceOrAccess; +/** + * Class containing a PlateData object. + *

Wraps function calls to the PlateData contained. + */ public class PlateWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "PlateAnnotationLink"; @@ -88,7 +97,9 @@ public void setName(String name) { /** - * @return the PlateData contained. + * Returns the PlateData contained. + * + * @return See above. */ public PlateData asPlateData() { return data; @@ -116,6 +127,26 @@ public void setDescription(String description) { } + /** + * Retrieves the screens containing this dataset. + * + * @param client The client handling the connection. + * + * @return See above. + * + * @throws OMEROServerError Server error. + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public List getScreens(Client client) + throws OMEROServerError, ServiceException, AccessException, ExecutionException { + List os = client.findByQuery("select link.parent from ScreenPlateLink as link " + + "where link.child=" + getId()); + return client.getScreens(os.stream().map(IObject::getId).map(RLong::getValue).distinct().toArray(Long[]::new)); + } + + /** * Returns the plate acquisitions related to this plate. * diff --git a/src/main/java/fr/igred/omero/repository/ProjectWrapper.java b/src/main/java/fr/igred/omero/repository/ProjectWrapper.java index 6f6660f9..39cf24b3 100644 --- a/src/main/java/fr/igred/omero/repository/ProjectWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ProjectWrapper.java @@ -42,11 +42,12 @@ /** - * Class containing a ProjectData - *

Implements function using the Project contained + * Class containing a ProjectData object. + *

Wraps function calls to the Project contained */ public class ProjectWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "ProjectAnnotationLink"; @@ -104,7 +105,9 @@ public void setName(String name) { /** - * @return the ProjectData contained. + * Returns the ProjectData contained. + * + * @return See above. */ public ProjectData asProjectData() { return data; @@ -223,7 +226,7 @@ public DatasetWrapper addDataset(Client client, DatasetWrapper dataset) * @throws ServiceException Cannot connect to OMERO. * @throws AccessException Cannot access data. * @throws ExecutionException A Facility can't be retrieved or instantiated. - * @throws OMEROServerError If the thread was interrupted. + * @throws OMEROServerError Server error. * @throws InterruptedException If block(long) does not return. */ public void removeDataset(Client client, DatasetWrapper dataset) diff --git a/src/main/java/fr/igred/omero/repository/ScreenWrapper.java b/src/main/java/fr/igred/omero/repository/ScreenWrapper.java index fd1cf601..fd1513a0 100644 --- a/src/main/java/fr/igred/omero/repository/ScreenWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ScreenWrapper.java @@ -14,19 +14,57 @@ * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin * Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + package fr.igred.omero.repository; +import fr.igred.omero.Client; +import fr.igred.omero.GatewayWrapper; +import fr.igred.omero.exception.AccessException; +import fr.igred.omero.exception.OMEROServerError; +import fr.igred.omero.exception.ServiceException; +import omero.gateway.exception.DSAccessException; +import omero.gateway.exception.DSOutOfServiceException; import omero.gateway.model.ScreenData; +import java.io.IOException; +import java.util.Collections; import java.util.List; +import java.util.concurrent.ExecutionException; + +import static fr.igred.omero.exception.ExceptionHandler.handleServiceOrAccess; +/** + * Class containing a ScreenData object. + *

Wraps function calls to the ScreenData contained. + */ public class ScreenWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "ScreenAnnotationLink"; + /** + * Constructor of the ProjectWrapper class. Creates a new project and saves it to OMERO. + * + * @param client The client handling the connection. + * @param name Project name. + * @param description Project description. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public ScreenWrapper(Client client, String name, String description) + throws ServiceException, AccessException, ExecutionException { + super(new ScreenData()); + data.setName(name); + data.setDescription(description); + super.saveAndUpdate(client); + } + + /** * Constructor of the class ScreenWrapper. * @@ -72,7 +110,9 @@ public void setName(String name) { /** - * @return the ScreenData contained. + * Returns the ScreenData contained. + * + * @return See above. */ public ScreenData asScreenData() { return data; @@ -203,4 +243,67 @@ public void setReagentSetIdentifier(String value) { data.setReagentSetIdentifier(value); } + + /** + * Refreshes the wrapped screen. + * + * @param client The client handling the connection. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public void refresh(GatewayWrapper client) throws ServiceException, AccessException, ExecutionException { + try { + data = client.getBrowseFacility() + .getScreens(client.getCtx(), Collections.singletonList(this.getId())) + .iterator().next(); + } catch (DSOutOfServiceException | DSAccessException e) { + handleServiceOrAccess(e, "Cannot refresh " + this); + } + } + + + /** + * Imports all images candidates in the paths to the screen in OMERO. + * + * @param client The client handling the connection. + * @param paths Paths to the image files on the computer. + * + * @return If the import did not exit because of an error. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws OMEROServerError Server error. + * @throws IOException Cannot read file. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public boolean importImages(GatewayWrapper client, String... paths) + throws ServiceException, OMEROServerError, AccessException, IOException, ExecutionException { + boolean success = importImages(client, data, paths); + refresh(client); + return success; + } + + + /** + * Imports one image file to the screen in OMERO. + * + * @param client The client handling the connection. + * @param path Path to the image file on the computer. + * + * @return The list of IDs of the newly imported images. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws OMEROServerError Server error. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public List importImage(GatewayWrapper client, String path) + throws ServiceException, AccessException, OMEROServerError, ExecutionException { + List ids = importImage(client, data, path); + refresh(client); + return ids; + } + } diff --git a/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java b/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java index bcfb2155..e0078b64 100644 --- a/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java +++ b/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java @@ -14,16 +14,26 @@ * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin * Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + package fr.igred.omero.repository; +import fr.igred.omero.Client; import fr.igred.omero.GenericObjectWrapper; +import fr.igred.omero.exception.AccessException; +import fr.igred.omero.exception.ServiceException; import ome.model.units.BigResult; import omero.gateway.model.WellSampleData; import omero.model.Length; import omero.model.enums.UnitsLength; +import java.util.concurrent.ExecutionException; + +/** + * Class containing a WellSampleData object. + *

Wraps function calls to the WellSampleData contained. + */ public class WellSampleWrapper extends GenericObjectWrapper { @@ -38,13 +48,31 @@ public WellSampleWrapper(WellSampleData wellSample) { /** - * @return the WellSampleData contained. + * Returns the WellSampleData contained. + * + * @return See above. */ public WellSampleData asWellSampleData() { return data; } + /** + * Retrieves the well containing this well sample + * + * @param client The client handling the connection. + * + * @return See above + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + * @throws ExecutionException A Facility can't be retrieved or instantiated. + */ + public WellWrapper getWell(Client client) throws AccessException, ServiceException, ExecutionException { + return client.getWell(asWellSampleData().asWellSample().getWell().getId().getValue()); + } + + /** * Returns the image related to that sample if any. * diff --git a/src/main/java/fr/igred/omero/repository/WellWrapper.java b/src/main/java/fr/igred/omero/repository/WellWrapper.java index 51e81304..c12db03c 100644 --- a/src/main/java/fr/igred/omero/repository/WellWrapper.java +++ b/src/main/java/fr/igred/omero/repository/WellWrapper.java @@ -21,8 +21,13 @@ import java.util.List; +/** + * Class containing a WellData object. + *

Wraps function calls to the WellData contained. + */ public class WellWrapper extends GenericRepositoryObjectWrapper { + /** Annotation link name for this type of object */ public static final String ANNOTATION_LINK = "WellAnnotationLink"; @@ -91,7 +96,9 @@ public String getDescription() { /** - * @return the WellData contained. + * Returns the WellData contained. + * + * @return See above. */ public WellData asWellData() { return data; diff --git a/src/main/java/fr/igred/omero/roi/EllipseWrapper.java b/src/main/java/fr/igred/omero/roi/EllipseWrapper.java index 67e0a56e..cefc4d62 100644 --- a/src/main/java/fr/igred/omero/roi/EllipseWrapper.java +++ b/src/main/java/fr/igred/omero/roi/EllipseWrapper.java @@ -27,6 +27,10 @@ import java.awt.geom.RectangularShape; +/** + * Class containing an EllipseData. + *

Wraps function calls to the EllipseData contained. + */ public class EllipseWrapper extends GenericShapeWrapper { @@ -59,7 +63,7 @@ public EllipseWrapper(ij.gui.Roi ijRoi) { ijRoi.getBounds().getWidth() / 2, ijRoi.getBounds().getHeight() / 2); data.setText(ijRoi.getName()); - copy(ijRoi); + super.copy(ijRoi); } diff --git a/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java b/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java index 5ddc6c30..5cf3452b 100644 --- a/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java +++ b/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java @@ -84,8 +84,8 @@ static ShapeList fromImageJ(ij.gui.Roi ijRoi) { list.add(new EllipseWrapper(ijRoi)); break; case Roi.POINT: - int[] x = ijRoi.getPolygon().xpoints; - int[] y = ijRoi.getPolygon().ypoints; + float[] x = ijRoi.getFloatPolygon().xpoints; + float[] y = ijRoi.getFloatPolygon().ypoints; Collection points = new LinkedList<>(); for (int i = 0; i < x.length; i++) { @@ -119,7 +119,7 @@ static ShapeList fromImageJ(ij.gui.Roi ijRoi) { * * @param ijRoi An ImageJ Roi. */ - protected final void copy(ij.gui.Roi ijRoi) { + protected void copy(ij.gui.Roi ijRoi) { data.setC(Math.max(-1, ijRoi.getCPosition() - 1)); data.setZ(Math.max(-1, ijRoi.getZPosition() - 1)); data.setT(Math.max(-1, ijRoi.getTPosition() - 1)); diff --git a/src/main/java/fr/igred/omero/roi/LineWrapper.java b/src/main/java/fr/igred/omero/roi/LineWrapper.java index fa196edf..6259369b 100644 --- a/src/main/java/fr/igred/omero/roi/LineWrapper.java +++ b/src/main/java/fr/igred/omero/roi/LineWrapper.java @@ -27,8 +27,13 @@ import java.awt.geom.Line2D; +/** + * Class containing an LineData. + *

Wraps function calls to the LineData contained. + */ public class LineWrapper extends GenericShapeWrapper { + /** String to use arrows as markers */ public static final String ARROW = "Arrow"; @@ -65,7 +70,7 @@ public LineWrapper(Line line) { data.getShapeSettings().setMarkerStart(ARROW); } } - copy(line); + super.copy(line); } diff --git a/src/main/java/fr/igred/omero/roi/MaskWrapper.java b/src/main/java/fr/igred/omero/roi/MaskWrapper.java index 29e821a9..8f5db514 100644 --- a/src/main/java/fr/igred/omero/roi/MaskWrapper.java +++ b/src/main/java/fr/igred/omero/roi/MaskWrapper.java @@ -25,6 +25,10 @@ import java.awt.geom.Rectangle2D; +/** + * Class containing an MaskData. + *

Wraps function calls to the MaskData contained. + */ public class MaskWrapper extends GenericShapeWrapper { diff --git a/src/main/java/fr/igred/omero/roi/PointWrapper.java b/src/main/java/fr/igred/omero/roi/PointWrapper.java index be5d6b69..38baeff3 100644 --- a/src/main/java/fr/igred/omero/roi/PointWrapper.java +++ b/src/main/java/fr/igred/omero/roi/PointWrapper.java @@ -24,6 +24,10 @@ import java.awt.geom.Path2D; +/** + * Class containing an PointData. + *

Wraps function calls to the PointData contained. + */ public class PointWrapper extends GenericShapeWrapper { diff --git a/src/main/java/fr/igred/omero/roi/PolygonWrapper.java b/src/main/java/fr/igred/omero/roi/PolygonWrapper.java index cf88af18..c05548a0 100644 --- a/src/main/java/fr/igred/omero/roi/PolygonWrapper.java +++ b/src/main/java/fr/igred/omero/roi/PolygonWrapper.java @@ -29,6 +29,10 @@ import java.util.stream.IntStream; +/** + * Class containing an PolygonData. + *

Wraps function calls to the PolygonData contained. + */ public class PolygonWrapper extends GenericShapeWrapper { @@ -57,15 +61,15 @@ public PolygonWrapper() { */ public PolygonWrapper(Roi ijRoi) { this(); - int[] x = ijRoi.getPolygon().xpoints; - int[] y = ijRoi.getPolygon().ypoints; + float[] x = ijRoi.getFloatPolygon().xpoints; + float[] y = ijRoi.getFloatPolygon().ypoints; List points = new LinkedList<>(); IntStream.range(0, x.length).forEach(i -> points.add(new Point2D.Double(x[i], y[i]))); data.setPoints(points); data.setText(ijRoi.getName()); - copy(ijRoi); + super.copy(ijRoi); } diff --git a/src/main/java/fr/igred/omero/roi/PolylineWrapper.java b/src/main/java/fr/igred/omero/roi/PolylineWrapper.java index be1063c5..cf8fd54e 100644 --- a/src/main/java/fr/igred/omero/roi/PolylineWrapper.java +++ b/src/main/java/fr/igred/omero/roi/PolylineWrapper.java @@ -28,6 +28,10 @@ import java.util.stream.IntStream; +/** + * Class containing an PolylineData. + *

Wraps function calls to the PolylineData contained. + */ public class PolylineWrapper extends GenericShapeWrapper { @@ -56,15 +60,15 @@ public PolylineWrapper() { */ public PolylineWrapper(Roi ijRoi) { this(); - int[] x = ijRoi.getPolygon().xpoints; - int[] y = ijRoi.getPolygon().ypoints; + float[] x = ijRoi.getFloatPolygon().xpoints; + float[] y = ijRoi.getFloatPolygon().ypoints; List points = new LinkedList<>(); IntStream.range(0, x.length).forEach(i -> points.add(new Point2D.Double(x[i], y[i]))); data.setPoints(points); data.setText(ijRoi.getName()); - copy(ijRoi); + super.copy(ijRoi); } diff --git a/src/main/java/fr/igred/omero/roi/ROIWrapper.java b/src/main/java/fr/igred/omero/roi/ROIWrapper.java index 3b9892f3..324a5298 100644 --- a/src/main/java/fr/igred/omero/roi/ROIWrapper.java +++ b/src/main/java/fr/igred/omero/roi/ROIWrapper.java @@ -44,8 +44,8 @@ /** - * Class containing a ROIData - *

Implements function using the ROIData contained + * Class containing a ROIData object. + *

Wraps function calls to the ROIData contained. */ public class ROIWrapper extends GenericObjectWrapper { diff --git a/src/main/java/fr/igred/omero/roi/RectangleWrapper.java b/src/main/java/fr/igred/omero/roi/RectangleWrapper.java index 573470c0..e6f4229e 100644 --- a/src/main/java/fr/igred/omero/roi/RectangleWrapper.java +++ b/src/main/java/fr/igred/omero/roi/RectangleWrapper.java @@ -25,6 +25,10 @@ import java.awt.geom.Rectangle2D; +/** + * Class containing an RectangleData. + *

Wraps function calls to the RectangleData contained. + */ public class RectangleWrapper extends GenericShapeWrapper { @@ -58,7 +62,7 @@ public RectangleWrapper(ij.gui.Roi ijRoi) { ijRoi.getBounds().getHeight()); data.setText(ijRoi.getName()); - copy(ijRoi); + super.copy(ijRoi); } diff --git a/src/main/java/fr/igred/omero/roi/ShapeList.java b/src/main/java/fr/igred/omero/roi/ShapeList.java index 9a43bbb2..67e4dba4 100644 --- a/src/main/java/fr/igred/omero/roi/ShapeList.java +++ b/src/main/java/fr/igred/omero/roi/ShapeList.java @@ -37,13 +37,16 @@ public class ShapeList extends ArrayList> { + private static final long serialVersionUID = 9076633148525603098L; + + /** * Gets a list of elements from this list whose class is specified. * * @param clazz Class of the wanted elements. * @param Subclass of GenericShapeWrapper. * - * @return List of elements of + * @return See above. */ public > List getElementsOf(Class clazz) { return stream().filter(clazz::isInstance).map(clazz::cast).collect(Collectors.toList()); diff --git a/src/main/java/fr/igred/omero/roi/TextWrapper.java b/src/main/java/fr/igred/omero/roi/TextWrapper.java index ac9f10fe..ea5795a7 100644 --- a/src/main/java/fr/igred/omero/roi/TextWrapper.java +++ b/src/main/java/fr/igred/omero/roi/TextWrapper.java @@ -24,6 +24,10 @@ import java.awt.geom.Path2D; +/** + * Class containing an TextData. + *

Wraps function calls to the TextData contained. + */ public class TextWrapper extends GenericShapeWrapper { @@ -52,7 +56,7 @@ public TextWrapper() { */ public TextWrapper(TextRoi text) { this(text.getText(), text.getBounds().getX(), text.getBounds().getY()); - copy(text); + super.copy(text); } diff --git a/src/main/java/fr/igred/omero/util/LibraryChecker.java b/src/main/java/fr/igred/omero/util/LibraryChecker.java new file mode 100644 index 00000000..035f6cbc --- /dev/null +++ b/src/main/java/fr/igred/omero/util/LibraryChecker.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2020-2022 GReD + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 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 General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package fr.igred.omero.util; + + +/** + * Utility methods to check if required libraries/classes are available + */ +public final class LibraryChecker { + + private LibraryChecker() { + } + + + /** + * Checks if the required libraries are available. + * + * @return {@code true} if the libraries are available, {@code false} otherwise. + */ + public static boolean areRequirementsAvailable() { + return isFormatsAPIAvailable() && + isOMEROModelAvailable() && + isOMECommonAvailable() && + isOMEROBlitzAvailable() && + isOMEROGatewayAvailable(); + } + + + /** + * Checks if the omero-gateway is available. + * + * @return {@code true} if Gateway is available, {@code false} otherwise. + */ + public static boolean isOMEROGatewayAvailable() { + return checkClass("omero.gateway.Gateway"); + } + + + /** + * Checks if the omero-model is available. + * + * @return {@code true} if IObject is available, {@code false} otherwise. + */ + public static boolean isOMEROModelAvailable() { + return checkClass("ome.model.IObject"); + } + + + /** + * Checks if OMERO Blitz is available. + * + * @return {@code true} if OMEROMetadataStoreClient is available, {@code false} otherwise. + */ + public static boolean isOMEROBlitzAvailable() { + return checkClass("ome.formats.OMEROMetadataStoreClient"); + } + + + /** + * Checks if ome-common is available. + * + * @return {@code true} if DataTools is available, {@code false} otherwise. + */ + public static boolean isOMECommonAvailable() { + return checkClass("loci.common.DataTools"); + } + + + /** + * Checks if formats-api is available. + * + * @return {@code true} if DefaultMetadataOptions is available, {@code false} otherwise. + */ + public static boolean isFormatsAPIAvailable() { + return checkClass("loci.formats.in.DefaultMetadataOptions"); + } + + + /** + * Checks whether the given class is available. + * + * @param className The name of the class. + * + * @return {@code true} if the class was found, {@code false} otherwise. + */ + public static boolean checkClass(String className) { + try { + Class.forName(className); + } catch (ClassNotFoundException e) { + return false; + } + return true; + } + +} diff --git a/src/main/java/fr/igred/omero/util/package-info.java b/src/main/java/fr/igred/omero/util/package-info.java new file mode 100644 index 00000000..801b97aa --- /dev/null +++ b/src/main/java/fr/igred/omero/util/package-info.java @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2020-2022 GReD + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 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 General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +/** + * This package contains a utility class used to check if the library requirements are available. + */ +package fr.igred.omero.util; \ No newline at end of file diff --git a/src/test/java/fr/igred/omero/AccessExceptionTest.java b/src/test/java/fr/igred/omero/AccessExceptionTest.java index 5f95958e..84234e7a 100644 --- a/src/test/java/fr/igred/omero/AccessExceptionTest.java +++ b/src/test/java/fr/igred/omero/AccessExceptionTest.java @@ -28,78 +28,59 @@ import omero.gateway.model.ProjectData; import omero.model.NamedValue; import omero.model.ProjectI; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import java.io.OutputStream; -import java.io.PrintStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.logging.Level; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeFalse; -public class AccessExceptionTest extends BasicTest { +class AccessExceptionTest extends BasicTest { - private final PrintStream empty = new PrintStream(new OutputStream() { - public void write(int b) { - //DO NOTHING - } - }); - private final PrintStream error = System.err; - protected Client client; - protected Client sudo; - - - void hideErrors() { - System.setErr(empty); - } - - - void showErrors() { - System.setErr(error); - } + protected Client client; + protected Client sudo; - @Before - public void setUp() { + @BeforeEach + void setUp() { boolean failed = false; client = new Client(); try { client.connect(HOST, PORT, "testUser", "password".toCharArray(), GROUP1.id); - assertEquals("Wrong user", USER1.id, client.getId()); - assertEquals("Wrong group", GROUP1.id, client.getCurrentGroupId()); + assertEquals(USER1.id, client.getId(), "Wrong user"); + assertEquals(GROUP1.id, client.getCurrentGroupId(), "Wrong group"); sudo = client.sudoGetUser("testUser2"); } catch (AccessException | ServiceException | ExecutionException | RuntimeException e) { sudo = null; failed = true; logger.log(Level.SEVERE, String.format("%sConnection failed.%s", ANSI_RED, ANSI_RESET), e); } - org.junit.Assume.assumeFalse(failed); - hideErrors(); + assumeFalse(failed, "Connection failed"); } - @After - public void cleanUp() { + @AfterEach + void cleanUp() { try { client.disconnect(); - showErrors(); - } catch (Exception e) { - showErrors(); + } catch (RuntimeException e) { logger.log(Level.WARNING, String.format("%sDisconnection failed.%s", ANSI_YELLOW, ANSI_RESET), e); } } @Test - public void testAddTagToImageWrongUser() throws Exception { + void testAddTagToImageWrongUser() throws Exception { boolean exception = false; client.disconnect(); client.connect(HOST, PORT, "root", "omero".toCharArray(), GROUP1.id); @@ -126,8 +107,8 @@ public void testAddTagToImageWrongUser() throws Exception { } - @Test(expected = AccessException.class) - public void testFolderAddROIWithoutImage() throws Exception { + @Test + void testFolderAddROIWithoutImage() throws Exception { FolderWrapper folder = new FolderWrapper(client, "Test1"); RectangleWrapper rectangle = new RectangleWrapper(0, 0, 10, 10); @@ -137,39 +118,39 @@ public void testFolderAddROIWithoutImage() throws Exception { roi.addShape(rectangle); roi.saveROI(client); - folder.addROI(client, roi); + assertThrows(AccessException.class, () -> folder.addROI(client, roi)); } - @Test(expected = AccessException.class) - public void testSudoFailGetProjects() throws Exception { - sudo.getProjects(); + @Test + void testSudoFailGetProjects() { + assertThrows(AccessException.class, () -> sudo.getProjects()); } - @Test(expected = AccessException.class) - public void testSudoFailGetSingleProject() throws Exception { - sudo.getProject(PROJECT1.id); + @Test + void testSudoFailGetSingleProject() { + assertThrows(AccessException.class, () -> sudo.getProject(PROJECT1.id)); } - @Test(expected = AccessException.class) - public void testSudoFailGetProjectByName() throws Exception { - sudo.getProjects("TestProject"); + @Test + void testSudoFailGetProjectByName() { + assertThrows(AccessException.class, () -> sudo.getProjects("TestProject")); } - @Test(expected = AccessException.class) - public void testSudoFailDeleteProject() throws Exception { + @Test + void testSudoFailDeleteProject() { ProjectI projectI = new ProjectI(PROJECT1.id, false); ProjectData projectData = new ProjectData(projectI); ProjectWrapper project = new ProjectWrapper(projectData); - sudo.delete(project); + assertThrows(AccessException.class, () -> sudo.delete(project)); } - @Test(expected = AccessException.class) - public void testSudoFailDeleteProjects() throws Exception { + @Test + void testSudoFailDeleteProjects() { ProjectI projectI1 = new ProjectI(PROJECT1.id, false); ProjectI projectI2 = new ProjectI(2L, false); ProjectData projectData1 = new ProjectData(projectI1); @@ -178,81 +159,81 @@ public void testSudoFailDeleteProjects() throws Exception { Collection projects = new ArrayList<>(2); projects.add(new ProjectWrapper(projectData1)); projects.add(new ProjectWrapper(projectData2)); - sudo.delete(projects); + assertThrows(AccessException.class, () -> sudo.delete(projects)); } // This test returns a ServiceException for a "security violation". - @Test(expected = ServiceException.class) - public void testSudoFailGetDatasets() throws Exception { - sudo.getDatasets(); + @Test + void testSudoFailGetDatasets() { + assertThrows(ServiceException.class, () -> sudo.getDatasets()); } - @Test(expected = AccessException.class) - public void testSudoFailGetSingleDataset() throws Exception { - sudo.getDataset(DATASET1.id); + @Test + void testSudoFailGetSingleDataset() { + assertThrows(AccessException.class, () -> sudo.getDataset(DATASET1.id)); } - @Test(expected = AccessException.class) - public void testSudoFailGetDatasetByName() throws Exception { - sudo.getDatasets("TestDataset"); + @Test + void testSudoFailGetDatasetByName() { + assertThrows(AccessException.class, () -> sudo.getDatasets("TestDataset")); } - @Test(expected = AccessException.class) - public void testSudoFailGetImages() throws Exception { - sudo.getImages(); + @Test + void testSudoFailGetImages() { + assertThrows(AccessException.class, () -> sudo.getImages()); } - @Test(expected = AccessException.class) - public void testSudoFailGetImage() throws Exception { - sudo.getImage(IMAGE1.id); + @Test + void testSudoFailGetImage() { + assertThrows(AccessException.class, () -> sudo.getImage(IMAGE1.id)); } - @Test(expected = AccessException.class) - public void testSudoFailGetImagesName() throws Exception { - sudo.getImages("image1.fake"); + @Test + void testSudoFailGetImagesName() { + assertThrows(AccessException.class, () -> sudo.getImages("image1.fake")); } - @Test(expected = AccessException.class) - public void testSudoFailGetImagesLike() throws Exception { - sudo.getImagesLike("image1"); + @Test + void testSudoFailGetImagesLike() { + assertThrows(AccessException.class, () -> sudo.getImagesLike("image1")); } - @Test(expected = ServiceException.class) - public void testSudoFailGetAllTags() throws Exception { - sudo.getTags(); + @Test + void testSudoFailGetAllTags() { + assertThrows(ServiceException.class, () -> sudo.getTags()); } - @Test(expected = ServiceException.class) - public void testSudoFailGetTag() throws Exception { - sudo.getTag(TAG1.id); + @Test + void testSudoFailGetTag() { + assertThrows(ServiceException.class, () -> sudo.getTag(TAG1.id)); } - @Test(expected = AccessException.class) - public void testSudoFailGetImageTag() throws Exception { + @Test + void testSudoFailGetImageTag() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); - image.getTags(sudo); + assertThrows(AccessException.class, () -> image.getTags(sudo)); } - @Test(expected = AccessException.class) - public void testSudoFailGetKVPairs() throws Exception { + @Test + void testSudoFailGetKVPairs() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); - image.getKeyValuePairs(sudo); + assertThrows(AccessException.class, () -> image.getKeyValuePairs(sudo)); } - @Test(expected = AccessException.class) - public void testSudoFailAddKVPair() throws Exception { + @Test + void testSudoFailAddKVPair() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List result1 = new ArrayList<>(2); @@ -260,13 +241,13 @@ public void testSudoFailAddKVPair() throws Exception { result1.add(new NamedValue("Test2 result1", "Value Test2")); MapAnnotationWrapper mapAnnotation1 = new MapAnnotationWrapper(result1); - image.addMapAnnotation(sudo, mapAnnotation1); + assertThrows(AccessException.class, () -> image.addMapAnnotation(sudo, mapAnnotation1)); } - @Test(expected = AccessException.class) - public void testSudoFail() throws Exception { - sudo.sudoGetUser("root"); + @Test + void testSudoFail() { + assertThrows(AccessException.class, () -> sudo.sudoGetUser("root")); } diff --git a/src/test/java/fr/igred/omero/BasicTest.java b/src/test/java/fr/igred/omero/BasicTest.java index 17e389d0..7d8daa25 100644 --- a/src/test/java/fr/igred/omero/BasicTest.java +++ b/src/test/java/fr/igred/omero/BasicTest.java @@ -16,13 +16,7 @@ package fr.igred.omero; -import loci.common.DebugTools; -import org.junit.AssumptionViolatedException; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.rules.TestRule; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; +import org.junit.jupiter.api.extension.ExtendWith; import java.io.File; import java.io.IOException; @@ -34,13 +28,14 @@ import java.util.logging.Logger; -@Ignore("Abstract class") +@ExtendWith(LoggingExtension.class) public abstract class BasicTest { public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; public static final String ANSI_YELLOW = "\u001B[33m"; + public static final String ANSI_BLUE = "\u001B[34m"; protected static final Logger logger = Logger.getLogger(MethodHandles.lookup().lookupClass().getName()); @@ -63,79 +58,24 @@ public abstract class BasicTest { protected static final TestObject TAG1 = new TestObject(1L, "tag1", "description"); protected static final TestObject TAG2 = new TestObject(2L, "tag2", ""); - static { - System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] %5$s %n"); - } - - @Rule - public final TestRule watcher = new Stopwatch(); - - private long start = System.currentTimeMillis(); - - - long getStart() { - return start; - } - - - void setStart(long start) { - this.start = start; - } - - - private class Stopwatch extends TestWatcher { - - @Override - protected void starting(Description description) { - DebugTools.enableLogging("OFF"); - setStart(System.currentTimeMillis()); - } - - - @Override - protected void skipped(AssumptionViolatedException e, Description description) { - float time = (float) (System.currentTimeMillis() - getStart()) / 1000; - String status = String.format("%sSKIPPED%s", ANSI_YELLOW, ANSI_RESET); - String testName = description.getMethodName() + ":"; - logger.info(String.format("%-40s\t%s (%.3f s)", testName, status, time)); - } - - - @Override - protected void succeeded(Description description) { - float time = (float) (System.currentTimeMillis() - getStart()) / 1000; - String status = String.format("%sSUCCEEDED%s", ANSI_GREEN, ANSI_RESET); - String testName = description.getMethodName() + ":"; - logger.info(String.format("%-40s\t%s (%.3f s)", testName, status, time)); - } - - - @Override - protected void failed(Throwable e, Description description) { - float time = (float) (System.currentTimeMillis() - getStart()) / 1000; - String testName = description.getMethodName() + ":"; - String status = String.format("%sFAILED%s", ANSI_RED, ANSI_RESET); - logger.info(String.format("%-40s\t%s (%.3f s)", testName, status, time)); - } - - } - protected static File createFile(String filename) throws IOException { - final String tmpdir = System.getProperty("java.io.tmpdir") + File.separator; + @SuppressWarnings("AccessOfSystemProperties") + String tmpdir = System.getProperty("java.io.tmpdir") + File.separator; File file = new File(tmpdir + File.separator + filename); if (!file.createNewFile()) { - System.err.println("\"" + file.getCanonicalPath() + "\" could not be created."); + logger.severe("\"" + file.getCanonicalPath() + "\" could not be created."); } return file; } protected static File createRandomFile(String filename) throws IOException { - File file = createFile(filename); + final int size = 2 * 262144 + 20; - final byte[] array = new byte[2 * 262144 + 20]; + File file = createFile(filename); + byte[] array = new byte[size]; new SecureRandom().nextBytes(array); String generatedString = new String(array, StandardCharsets.UTF_8); try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath()), false, "UTF-8")) { @@ -147,7 +87,7 @@ protected static File createRandomFile(String filename) throws IOException { protected static void removeFile(File file) throws IOException { if (!file.delete()) { - System.err.println("\"" + file.getCanonicalPath() + "\" could not be deleted."); + logger.severe("\"" + file.getCanonicalPath() + "\" could not be deleted."); } } diff --git a/src/test/java/fr/igred/omero/ClientTest.java b/src/test/java/fr/igred/omero/ClientTest.java index 649177cc..c243b327 100644 --- a/src/test/java/fr/igred/omero/ClientTest.java +++ b/src/test/java/fr/igred/omero/ClientTest.java @@ -22,22 +22,23 @@ import fr.igred.omero.repository.ProjectWrapper; import fr.igred.omero.repository.ScreenWrapper; import fr.igred.omero.repository.WellWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class ClientTest extends UserTest { +class ClientTest extends UserTest { @Test - public void testProjectBasic() throws Exception { + void testProjectBasic() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); assertEquals(PROJECT1.id, project.getId()); assertEquals(PROJECT1.name, project.getName()); @@ -48,21 +49,21 @@ public void testProjectBasic() throws Exception { @Test - public void testGetSingleProject() throws Exception { + void testGetSingleProject() throws Exception { String name = client.getProject(PROJECT1.id).getName(); assertEquals(PROJECT1.name, name); } @Test - public void testGetAllProjects() throws Exception { + void testGetAllProjects() throws Exception { Collection projects = client.getProjects(); assertEquals(2, projects.size()); } @Test - public void testGetProjectByName() throws Exception { + void testGetProjectByName() throws Exception { Collection projects = client.getProjects(PROJECT1.name); int differences = 0; @@ -77,41 +78,33 @@ public void testGetProjectByName() throws Exception { @Test - public void testCreateAndDeleteProject() throws Exception { - boolean exception = false; - + void testCreateAndDeleteProject() throws Exception { String name = "Foo project"; ProjectWrapper project = new ProjectWrapper(client, name, ""); long newId = project.getId(); assertEquals(name, client.getProject(newId).getName()); - client.delete(client.getProject(newId)); - try { - client.getProject(newId); - } catch (Exception e) { - exception = true; - } - assertTrue(exception); + assertThrows(NoSuchElementException.class, () -> client.getProject(newId)); } @Test - public void testGetSingleDataset() throws Exception { + void testGetSingleDataset() throws Exception { assertEquals(DATASET1.name, client.getDataset(DATASET1.id).getName()); } @Test - public void testGetAllDatasets() throws Exception { + void testGetAllDatasets() throws Exception { Collection datasets = client.getDatasets(); assertEquals(3, datasets.size()); } @Test - public void testGetDatasetByName() throws Exception { + void testGetDatasetByName() throws Exception { Collection datasets = client.getDatasets(DATASET1.name); int differences = 0; @@ -125,7 +118,7 @@ public void testGetDatasetByName() throws Exception { @Test - public void testGetImages() throws Exception { + void testGetImages() throws Exception { final int nImages = 56; List images = client.getImages(); @@ -134,56 +127,56 @@ public void testGetImages() throws Exception { @Test - public void testGetImage() throws Exception { + void testGetImage() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); assertEquals(IMAGE1.name, image.getName()); } @Test - public void testGetImagesName() throws Exception { + void testGetImagesName() throws Exception { List images = client.getImages(IMAGE1.name); assertEquals(3, images.size()); } @Test - public void testGetImagesLike() throws Exception { + void testGetImagesLike() throws Exception { List images = client.getImagesLike("image1"); assertEquals(3, images.size()); } @Test - public void testGetImagesTagged() throws Exception { + void testGetImagesTagged() throws Exception { List images = client.getImagesTagged(TAG1.id); assertEquals(3, images.size()); } @Test - public void testGetImagesKey() throws Exception { + void testGetImagesKey() throws Exception { List images = client.getImagesKey("testKey1"); assertEquals(3, images.size()); } @Test - public void testGetImagesKeyValue() throws Exception { + void testGetImagesKeyValue() throws Exception { List images = client.getImagesPairKeyValue("testKey1", "testValue1"); assertEquals(2, images.size()); } @Test - public void testGetImagesFromNames() throws Exception { + void testGetImagesFromNames() throws Exception { List images = client.getImages(PROJECT1.name, DATASET1.name, IMAGE1.name); assertEquals(2, images.size()); } @Test - public void testGetImagesCond() throws Exception { + void testGetImagesCond() throws Exception { String key = "testKey2"; /* Load the image with the key */ @@ -206,7 +199,7 @@ public void testGetImagesCond() throws Exception { @Test - public void testSwitchGroup() { + void testSwitchGroup() { final long newGroupId = 4L; client.switchGroup(newGroupId); long actualGroupId = client.getCurrentGroupId(); @@ -215,7 +208,7 @@ public void testSwitchGroup() { @Test - public void testSwitchGroupAndImport() throws Exception { + void testSwitchGroupAndImport() throws Exception { final long newGroupId = 4L; String filename = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=256&sizeY=256.fake"; @@ -239,35 +232,35 @@ public void testSwitchGroupAndImport() throws Exception { @Test - public void testGetAllScreens() throws Exception { + void testGetAllScreens() throws Exception { Collection screens = client.getScreens(); assertEquals(2, screens.size()); } @Test - public void testGetSingleScreen() throws Exception { + void testGetSingleScreen() throws Exception { String name = client.getScreen(SCREEN1.id).getName(); assertEquals(SCREEN1.name, name); } @Test - public void testGetAllPlates() throws Exception { + void testGetAllPlates() throws Exception { Collection screens = client.getPlates(); assertEquals(3, screens.size()); } @Test - public void testGetSinglePlate() throws Exception { + void testGetSinglePlate() throws Exception { String name = client.getPlate(PLATE1.id).getName(); assertEquals(PLATE1.name, name); } @Test - public void testGetAllWells() throws Exception { + void testGetAllWells() throws Exception { final int nWells = 17; Collection screens = client.getWells(); @@ -276,7 +269,7 @@ public void testGetAllWells() throws Exception { @Test - public void testGetSingleWell() throws Exception { + void testGetSingleWell() throws Exception { String plateName = client.getWell(1L).getPlate().getName(); assertEquals(PLATE1.name, plateName); } diff --git a/src/test/java/fr/igred/omero/ConnectionTest.java b/src/test/java/fr/igred/omero/ConnectionTest.java index 3cd4ddd1..24cd3a61 100644 --- a/src/test/java/fr/igred/omero/ConnectionTest.java +++ b/src/test/java/fr/igred/omero/ConnectionTest.java @@ -16,25 +16,27 @@ package fr.igred.omero; -import org.junit.Test; +import fr.igred.omero.exception.ServiceException; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class ConnectionTest extends BasicTest { +class ConnectionTest extends BasicTest { @Test - public void testDisconnect() { + void testDisconnect() { Client testRoot = new Client(); testRoot.disconnect(); assertFalse(testRoot.isConnected()); + assertEquals("Client{host=null, groupID=-1, userID=-1, connected=false}", testRoot.toString()); } @Test - public void testSessionConnect() throws Exception { + void testSessionConnect() throws ServiceException { Client client1 = new Client(); client1.connect(HOST, PORT, USER1.name, "password".toCharArray()); String sessionId = client1.getSessionId(); @@ -47,14 +49,14 @@ public void testSessionConnect() throws Exception { @Test - public void testRootConnection() throws Exception { + void testRootConnection() throws ServiceException { Client testRoot = new Client(); testRoot.connect(HOST, PORT, "root", "omero".toCharArray(), GROUP1.id); long id = testRoot.getId(); long groupId = testRoot.getCurrentGroupId(); try { testRoot.disconnect(); - } catch (Exception ignored) { + } catch (RuntimeException ignored) { } assertEquals(0L, id); assertEquals(GROUP1.id, groupId); @@ -62,15 +64,19 @@ public void testRootConnection() throws Exception { @Test - public void testUserConnection() throws Exception { + void testUserConnection() throws ServiceException { + String toString = String.format("Client{host=%s, groupID=%d, userID=%s, connected=true}", + HOST, GROUP1.id, USER1.id); + Client testUser = new Client(); assertFalse(testUser.isConnected()); testUser.connect(HOST, PORT, USER1.name, "password".toCharArray()); + assertEquals(toString, testUser.toString()); long id = testUser.getId(); long groupId = testUser.getCurrentGroupId(); try { testUser.disconnect(); - } catch (Exception ignored) { + } catch (RuntimeException ignored) { } assertEquals(USER1.id, id); assertEquals(GROUP1.id, groupId); diff --git a/src/test/java/fr/igred/omero/ExceptionTest.java b/src/test/java/fr/igred/omero/ExceptionTest.java index 55c94116..5e08214e 100644 --- a/src/test/java/fr/igred/omero/ExceptionTest.java +++ b/src/test/java/fr/igred/omero/ExceptionTest.java @@ -23,74 +23,54 @@ import omero.ServerError; import omero.gateway.exception.DSAccessException; import omero.gateway.exception.DSOutOfServiceException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ExceptionTest extends BasicTest { +class ExceptionTest extends BasicTest { @Test - public void testConnectionErrorUsername() { - boolean exception = false; - Client client = new Client(); - try { - client.connect(HOST, PORT, "badUser", "omero".toCharArray(), GROUP1.id); - } catch (ServiceException e) { - exception = true; - } - assertTrue(exception); + void testConnectionErrorUsername() { + Client client = new Client(); + assertThrows(ServiceException.class, + () -> client.connect(HOST, PORT, "badUser", "omero".toCharArray(), GROUP1.id)); } @Test - public void testConnectionErrorPassword() { - boolean exception = false; - Client root = new Client(); - try { - root.connect(HOST, PORT, "root", "badPassword".toCharArray(), GROUP1.id); - } catch (ServiceException e) { - exception = true; - } - assertTrue(exception); + void testConnectionErrorPassword() { + Client root = new Client(); + assertThrows(ServiceException.class, + () -> root.connect(HOST, PORT, "root", "badPassword".toCharArray(), GROUP1.id)); } @Test - public void testConnectionErrorHost() { - boolean exception = false; - Client root = new Client(); - try { - root.connect("127.0.0.1", PORT, "root", "omero".toCharArray(), GROUP1.id); - } catch (Exception e) { - exception = true; - } - assertTrue(exception); + void testConnectionErrorHost() { + Client root = new Client(); + assertThrows(ServiceException.class, + () -> root.connect("127.0.0.1", PORT, "root", "omero".toCharArray(), GROUP1.id)); } @Test - public void testConnectionErrorPort() { + void testConnectionErrorPort() { final int badPort = 5000; - - boolean exception = false; - Client root = new Client(); - try { - root.connect(HOST, badPort, "root", "omero".toCharArray(), GROUP1.id); - } catch (Exception e) { - exception = true; - } - assertTrue(exception); + Client root = new Client(); + assertThrows(ServiceException.class, + () -> root.connect(HOST, badPort, "root", "omero".toCharArray(), GROUP1.id)); } @Test - public void testConnectionErrorGroupNotExist() throws Exception { + void testConnectionErrorGroupNotExist() throws ServiceException { final long badGroup = 200L; Client clientNoSuchGroup = new Client(); @@ -101,7 +81,7 @@ public void testConnectionErrorGroupNotExist() throws Exception { @Test - public void testConnectionErrorNotInGroup() throws Exception { + void testConnectionErrorNotInGroup() throws ServiceException { Client clientWrongGroup = new Client(); clientWrongGroup.connect(HOST, PORT, USER1.name, "password".toCharArray(), 0L); assertEquals(USER1.id, clientWrongGroup.getId()); @@ -110,7 +90,7 @@ public void testConnectionErrorNotInGroup() throws Exception { @Test - public void testGetSingleProjectError() throws Exception { + void testGetSingleProjectError() throws Exception { final long badProject = 333L; boolean exception = false; @@ -127,7 +107,7 @@ public void testGetSingleProjectError() throws Exception { @Test - public void testGetImageError() throws Exception { + void testGetImageError() throws Exception { final long badImage = 200L; boolean exception = false; @@ -146,7 +126,7 @@ public void testGetImageError() throws Exception { @Test - public void testGetImageError2() throws Exception { + void testGetImageError2() throws Exception { final long badImage = -5L; boolean exception = false; @@ -165,7 +145,7 @@ public void testGetImageError2() throws Exception { @Test - public void testGetSingleScreenError() throws Exception { + void testGetSingleScreenError() throws Exception { final long badScreen = 333L; boolean exception = false; @@ -182,7 +162,7 @@ public void testGetSingleScreenError() throws Exception { @Test - public void testGetSinglePlateError() throws Exception { + void testGetSinglePlateError() throws Exception { final long badPlate = 333L; boolean exception = false; @@ -199,7 +179,7 @@ public void testGetSinglePlateError() throws Exception { @Test - public void testGetSingleWellError() throws Exception { + void testGetSingleWellError() throws Exception { final long badWell = 333L; boolean exception = false; @@ -215,73 +195,52 @@ public void testGetSingleWellError() throws Exception { } - @Test(expected = AccessException.class) - public void testExceptionHandler1() throws Exception { + @Test + void testExceptionHandler1() { Throwable t = new DSAccessException("Test", null); - ExceptionHandler.handleException(t, "Great"); + assertThrows(AccessException.class, () -> ExceptionHandler.handleException(t, "Great")); } - @Test(expected = OMEROServerError.class) - public void testExceptionHandler2() throws Exception { + @Test + void testExceptionHandler2() { Throwable t = new ServerError(null); - ExceptionHandler.handleException(t, "Great"); + assertThrows(OMEROServerError.class, () -> ExceptionHandler.handleException(t, "Great")); } - @Test(expected = OMEROServerError.class) - public void testExceptionHandler3() throws Exception { + @Test + void testExceptionHandler3() { Throwable t = new ServerError(null); - ExceptionHandler.handleServiceOrServer(t, "Great"); + assertThrows(OMEROServerError.class, () -> ExceptionHandler.handleServiceOrServer(t, "Great")); } - @Test(expected = ServiceException.class) - public void testExceptionHandler4() throws Exception { + @Test + void testExceptionHandler4() { Throwable t = new DSOutOfServiceException(null); - ExceptionHandler.handleException(t, "Great"); + assertThrows(ServiceException.class, () -> ExceptionHandler.handleException(t, "Great")); } @Test - public void testExceptionHandler5() { - boolean exception = false; - + void testExceptionHandler5() { Throwable t = new Exception("Nothing"); - try { - ExceptionHandler.handleException(t, "Great"); - } catch (Throwable t2) { - exception = true; - } - assertFalse(exception); + assertDoesNotThrow(() -> ExceptionHandler.handleException(t, "Great")); } @Test - public void testExceptionHandler6() { - boolean exception = false; - + void testExceptionHandler6() { Throwable t = new ServerError(null); - try { - ExceptionHandler.handleServiceOrAccess(t, "Great"); - } catch (Throwable t2) { - exception = true; - } - assertFalse(exception); + assertDoesNotThrow(() -> ExceptionHandler.handleServiceOrAccess(t, "Great")); } @Test - public void testExceptionHandler7() { - boolean exception = false; - + void testExceptionHandler7() { Throwable t = new DSAccessException("Test", null); - try { - ExceptionHandler.handleServiceOrServer(t, "Great"); - } catch (Throwable t2) { - exception = true; - } - assertFalse(exception); + assertDoesNotThrow(() -> ExceptionHandler.handleServiceOrServer(t, "Great")); } } diff --git a/src/test/java/fr/igred/omero/LoggingExtension.java b/src/test/java/fr/igred/omero/LoggingExtension.java new file mode 100644 index 00000000..5b8ea75b --- /dev/null +++ b/src/test/java/fr/igred/omero/LoggingExtension.java @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2020-2022 GReD + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 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 General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package fr.igred.omero; + + +import org.junit.jupiter.api.extension.AfterAllCallback; +import org.junit.jupiter.api.extension.BeforeAllCallback; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestWatcher; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Optional; +import java.util.logging.Logger; + +import static fr.igred.omero.BasicTest.ANSI_BLUE; +import static fr.igred.omero.BasicTest.ANSI_GREEN; +import static fr.igred.omero.BasicTest.ANSI_RED; +import static fr.igred.omero.BasicTest.ANSI_RESET; +import static fr.igred.omero.BasicTest.ANSI_YELLOW; + + +public class LoggingExtension implements TestWatcher, BeforeTestExecutionCallback, BeforeAllCallback, AfterAllCallback { + + private static final String FORMAT = "[%-43s]\t%s%-9s%s (%.3f s)"; + + @SuppressWarnings("UseOfSystemOutOrSystemErr") + private static final PrintStream error = System.err; + + @SuppressWarnings("UseOfSystemOutOrSystemErr") + private static final PrintStream output = System.out; + + @SuppressWarnings("InstanceVariableMayNotBeInitialized") + private PrintStream logFile; + + @SuppressWarnings("InstanceVariableMayNotBeInitialized") + private Logger logger; + + private long start = System.currentTimeMillis(); + + + /** + * Callback that is invoked once before all tests in the current container. + * + * @param context the current extension context; never {@code null} + */ + @Override + public void beforeAll(ExtensionContext context) throws IOException { + //noinspection AccessOfSystemProperties + System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] [%4$-7s] %5$s %n"); + String klass = context.getRequiredTestClass().getSimpleName(); + logger = Logger.getLogger(klass); + + File file = new File("target" + File.separator + "logs" + File.separator + klass + ".log"); + Files.createDirectories(file.toPath().getParent()); + Files.deleteIfExists(file.toPath()); + logFile = new PrintStream(Files.newOutputStream(file.toPath()), false, StandardCharsets.UTF_8.name()); + } + + + /** + * Callback that is invoked once after all tests in the current container. + * + * @param context the current extension context; never {@code null} + */ + @Override + public void afterAll(ExtensionContext context) { + logFile.close(); + } + + + /** + * Callback that is invoked immediately before an individual test is executed but after any user-defined + * setup methods have been executed for that test. + * + * @param context the current extension context; never {@code null} + */ + @Override + public void beforeTestExecution(ExtensionContext context) { + hideOutputs(); + String methodName = context.getRequiredTestMethod().getName(); + String displayName = context.getDisplayName(); + displayName = displayName.equals(methodName + "()") ? "" : displayName; + logFile.printf("%9s: %s %s%n", "STARTING", methodName, displayName); + start = System.currentTimeMillis(); + } + + + /** + * Invoked after a disabled test has been skipped. + * + *

The default implementation does nothing. Concrete implementations can + * override this method as appropriate. + * + * @param context the current extension context; never {@code null} + * @param reason the reason the test is disabled; never {@code null} but + */ + @Override + public void testDisabled(ExtensionContext context, Optional reason) { + float time = (float) (System.currentTimeMillis() - start) / 1000; + logStatus(context.getRequiredTestMethod().getName(), context.getDisplayName(), "DISABLED", ANSI_BLUE, time); + } + + + /** + * Invoked after a test has completed successfully. + * + *

The default implementation does nothing. Concrete implementations can + * override this method as appropriate. + * + * @param context the current extension context; never {@code null} + */ + @Override + public void testSuccessful(ExtensionContext context) { + float time = (float) (System.currentTimeMillis() - start) / 1000; + logStatus(context.getRequiredTestMethod().getName(), context.getDisplayName(), "SUCCEEDED", ANSI_GREEN, time); + } + + + /** + * Invoked after a test has been aborted. + * + *

The default implementation does nothing. Concrete implementations can + * override this method as appropriate. + * + * @param context the current extension context; never {@code null} + * @param cause the throwable responsible for the test being aborted; may be {@code null} + */ + @Override + public void testAborted(ExtensionContext context, Throwable cause) { + float time = (float) (System.currentTimeMillis() - start) / 1000; + logStatus(context.getRequiredTestMethod().getName(), context.getDisplayName(), "ABORTED", ANSI_YELLOW, time); + } + + + /** + * Invoked after a test has failed. + * + *

The default implementation does nothing. Concrete implementations can + * override this method as appropriate. + * + * @param context the current extension context; never {@code null} + * @param cause the throwable that caused test failure; may be {@code null} + */ + @Override + public void testFailed(ExtensionContext context, Throwable cause) { + float time = (float) (System.currentTimeMillis() - start) / 1000; + logStatus(context.getRequiredTestMethod().getName(), context.getDisplayName(), "FAILED", ANSI_RED, time); + } + + + /** + * Logs test status. + * + * @param methodName The method name. + * @param displayName The test display name. + * @param status The test status. + * @param time The time it took to run. + */ + private void logStatus(String methodName, String displayName, String status, String color, float time) { + showOutputs(); + displayName = displayName.equals(methodName + "()") ? "" : displayName; + String name = String.format("%s %s", methodName, displayName); + logger.info(String.format(FORMAT, name, color, status, ANSI_RESET, time)); + logFile.printf("%9s: %s%n", status, name); + } + + + /** + * Output to console. + */ + private static void showOutputs() { + System.setOut(output); + System.setErr(error); + } + + + /** + * Output to file. + */ + private void hideOutputs() { + System.setOut(logFile); + System.setErr(logFile); + } + +} diff --git a/src/test/java/fr/igred/omero/RootTest.java b/src/test/java/fr/igred/omero/RootTest.java index 4cd76442..edb01e13 100644 --- a/src/test/java/fr/igred/omero/RootTest.java +++ b/src/test/java/fr/igred/omero/RootTest.java @@ -16,41 +16,41 @@ package fr.igred.omero; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; +import fr.igred.omero.exception.ServiceException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import java.util.logging.Level; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; -@Ignore("Abstract class") public abstract class RootTest extends BasicTest { protected final Client client = new Client(); - @Before + @BeforeEach public void setUp() { boolean failed = false; try { client.connect(HOST, PORT, ROOT.name, "omero".toCharArray(), GROUP1.id); - assertEquals("Wrong user", ROOT.id, client.getId()); - assertEquals("Wrong group", GROUP1.id, client.getCurrentGroupId()); - } catch (Exception e) { + assertEquals(ROOT.id, client.getId(), "Wrong user"); + assertEquals(GROUP1.id, client.getCurrentGroupId(), "Wrong group"); + } catch (ServiceException e) { failed = true; logger.log(Level.SEVERE, String.format("%sConnection failed.%s", ANSI_RED, ANSI_RESET), e); } - org.junit.Assume.assumeFalse(failed); + assumeFalse(failed, "Connection failed."); } - @After + @AfterEach public void cleanUp() { try { client.disconnect(); - } catch (Exception e) { + } catch (RuntimeException e) { logger.log(Level.WARNING, String.format("%sDisconnection failed.%s", ANSI_YELLOW, ANSI_RESET), e); } } diff --git a/src/test/java/fr/igred/omero/SudoTest.java b/src/test/java/fr/igred/omero/SudoTest.java index 591522b7..85fc8643 100644 --- a/src/test/java/fr/igred/omero/SudoTest.java +++ b/src/test/java/fr/igred/omero/SudoTest.java @@ -19,21 +19,35 @@ import fr.igred.omero.annotations.TagAnnotationWrapper; import fr.igred.omero.repository.DatasetWrapper; import fr.igred.omero.repository.ImageWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class SudoTest extends BasicTest { +class SudoTest extends BasicTest { @Test - public void testSudoTag() throws Exception { + void testSudoDisconnect() throws Exception { + Client root = new Client(); + root.connect(HOST, PORT, "root", "omero".toCharArray(), GROUP1.id); + + Client test = root.sudoGetUser(USER1.name); + assertEquals(USER1.id, test.getId()); + test.disconnect(); + assertTrue(root.isConnected(), "root has been disconnected by sudo context"); + root.disconnect(); + assertNotEquals(root.getGateway(), test.getGateway(), "Gateways should not be the same"); + } + + + @Test + void testSudoTag() throws Exception { Client root = new Client(); root.connect(HOST, PORT, "root", "omero".toCharArray(), GROUP1.id); @@ -60,7 +74,7 @@ public void testSudoTag() throws Exception { try { test.disconnect(); root.disconnect(); - } catch (Exception ignored) { + } catch (RuntimeException ignored) { } assertNotEquals(0, images.size()); @@ -70,7 +84,7 @@ public void testSudoTag() throws Exception { @Test - public void sudoImport() throws Exception { + void sudoImport() throws Exception { String filename = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=256&sizeY=512.fake"; Client client4 = new Client(); @@ -100,7 +114,7 @@ public void sudoImport() throws Exception { try { client3.disconnect(); client4.disconnect(); - } catch (Exception ignored) { + } catch (RuntimeException ignored) { } } diff --git a/src/test/java/fr/igred/omero/TestObject.java b/src/test/java/fr/igred/omero/TestObject.java index 88a8e503..e52a59ac 100644 --- a/src/test/java/fr/igred/omero/TestObject.java +++ b/src/test/java/fr/igred/omero/TestObject.java @@ -32,11 +32,7 @@ public class TestObject { @Override public String toString() { - return "TestObject{" + - "id=" + id + - ", name='" + name + '\'' + - ", description='" + description + '\'' + - '}'; + return String.format("TestObject{id=%d, name='%s', description='%s'}", id, name, description); } } diff --git a/src/test/java/fr/igred/omero/UserTest.java b/src/test/java/fr/igred/omero/UserTest.java index 5ffe298a..7d7bf7c4 100644 --- a/src/test/java/fr/igred/omero/UserTest.java +++ b/src/test/java/fr/igred/omero/UserTest.java @@ -16,37 +16,37 @@ package fr.igred.omero; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; +import fr.igred.omero.exception.ServiceException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import java.util.logging.Level; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeFalse; -@Ignore("Abstract class") public abstract class UserTest extends BasicTest { protected final Client client = new Client(); - @Before + @BeforeEach public void setUp() { boolean failed = false; try { client.connect(HOST, PORT, USER1.name, "password".toCharArray(), GROUP1.id); - assertEquals("Wrong user", USER1.id, client.getId()); - assertEquals("Wrong group", GROUP1.id, client.getCurrentGroupId()); - } catch (Exception e) { + assertEquals(USER1.id, client.getId(), "Wrong user"); + assertEquals(GROUP1.id, client.getCurrentGroupId(), "Wrong group"); + } catch (ServiceException e) { failed = true; logger.log(Level.SEVERE, String.format("%sConnection failed.%s", ANSI_RED, ANSI_RESET), e); } - org.junit.Assume.assumeFalse(failed); + assumeFalse(failed, "Connection failed."); } - @After + @AfterEach public void cleanUp() { try { client.disconnect(); diff --git a/src/test/java/fr/igred/omero/annotations/TableTest.java b/src/test/java/fr/igred/omero/annotations/TableTest.java index cb6582ad..e98dfa08 100644 --- a/src/test/java/fr/igred/omero/annotations/TableTest.java +++ b/src/test/java/fr/igred/omero/annotations/TableTest.java @@ -25,7 +25,7 @@ import ij.measure.ResultsTable; import omero.gateway.model.DataObject; import omero.gateway.model.ImageData; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.nio.file.Files; @@ -33,21 +33,22 @@ import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class TableTest extends UserTest { +class TableTest extends UserTest { protected static final double volume1 = 25.0d; protected static final double volume2 = 50.0d; @Test - public void testCreateTable() throws Exception { + void testCreateTable() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -86,9 +87,75 @@ public void testCreateTable() throws Exception { @Test - public void testErrorTableFull() throws Exception { - boolean exception = false; - DatasetWrapper dataset = client.getDataset(DATASET1.id); + void testReplaceTable() throws Exception { + DatasetWrapper dataset = client.getDataset(DATASET1.id); + + List images = dataset.getImages(client); + + TableWrapper table1 = new TableWrapper(2, "TableTest"); + + assertEquals(2, table1.getColumnCount()); + + table1.setColumn(0, "Image", ImageData.class); + table1.setColumn(1, "Name", String.class); + assertEquals("Image", table1.getColumnName(0)); + assertEquals("Name", table1.getColumnName(1)); + assertSame(ImageData.class, table1.getColumnType(0)); + + table1.setRowCount(images.size()); + + assertEquals(images.size(), table1.getRowCount()); + + for (ImageWrapper image : images) { + assertNotEquals(true, table1.isComplete()); + table1.addRow(image.asImageData(), image.getName()); + } + + assertEquals(images.get(0).asImageData(), table1.getData(0, 0)); + assertEquals(images.get(1).getName(), table1.getData(0, 1)); + + dataset.addTable(client, table1); + long tableId1 = table1.getId(); + + TableWrapper table2 = new TableWrapper(2, "TableTest 2"); + table2.setColumn(0, "Image", ImageData.class); + table2.setColumn(1, "Name", String.class); + table2.setRowCount(images.size()); + for (ImageWrapper image : images) { + assertNotEquals(true, table2.isComplete()); + table2.addRow(image.asImageData(), image.getDescription()); + } + dataset.addTable(client, table2); + long tableId2 = table2.getId(); + + TableWrapper table3 = new TableWrapper(2, "TableTest"); + table3.setColumn(0, "Image", ImageData.class); + table3.setColumn(1, "Name", String.class); + table3.setRowCount(images.size()); + for (ImageWrapper image : images) { + assertNotEquals(true, table3.isComplete()); + table3.addRow(image.asImageData(), "Test name"); + } + dataset.addAndReplaceTable(client, table3); + long tableId3 = table3.getId(); + + assertNotEquals(tableId1, tableId3); + assertNotEquals(tableId2, tableId3); + + List tables = dataset.getTables(client); + for (TableWrapper table : tables) { + client.delete(table); + } + List noTables = dataset.getTables(client); + + assertEquals(2, tables.size()); + assertEquals(0, noTables.size()); + } + + + @Test + void testErrorTableFull() throws Exception { + DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -102,38 +169,22 @@ public void testErrorTableFull() throws Exception { table.setRowCount(images.size() - 1); - try { - for (ImageWrapper image : images) { - table.addRow(image.asImageData(), image.getName()); - } - } catch (IndexOutOfBoundsException e) { - exception = true; - } - assertTrue(exception); + assertThrows(IndexOutOfBoundsException.class, + () -> images.forEach(i -> table.addRow(i.asImageData(), i.getName()))); } @Test - public void testErrorTableColumn() { - boolean exception = false; - + void testErrorTableColumn() { TableWrapper table = new TableWrapper(2, "TableTest"); table.setColumn(0, "Image", ImageData.class); table.setColumn(1, "Name", String.class); - - try { - table.setColumn(2, "Id", Long.class); - } catch (IndexOutOfBoundsException e) { - exception = true; - } - assertTrue(exception); + assertThrows(IndexOutOfBoundsException.class, () -> table.setColumn(2, "Id", Long.class)); } @Test - public void testErrorTableUninitialized() throws Exception { - boolean exception = false; - + void testErrorTableUninitialized() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -141,22 +192,13 @@ public void testErrorTableUninitialized() throws Exception { TableWrapper table = new TableWrapper(2, "TableTest"); table.setColumn(0, "Image", ImageData.class); table.setColumn(1, "Name", String.class); - - try { - for (ImageWrapper image : images) { - table.addRow(image.asImageData(), image.getName()); - } - } catch (IndexOutOfBoundsException e) { - exception = true; - } - assertTrue(exception); + assertThrows(IndexOutOfBoundsException.class, + () -> images.forEach(i -> table.addRow(i.asImageData(), i.getName()))); } @Test - public void testErrorTableNotEnoughArgs() throws Exception { - boolean exception = false; - + void testErrorTableNotEnoughArgs() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -164,22 +206,14 @@ public void testErrorTableNotEnoughArgs() throws Exception { TableWrapper table = new TableWrapper(2, "TableTest"); table.setColumn(0, "Image", ImageData.class); table.setColumn(1, "Name", String.class); - table.setRowCount(images.size()); - - try { - for (ImageWrapper image : images) { - table.addRow(image.asImageData()); - } - } catch (IllegalArgumentException e) { - exception = true; - } - assertTrue(exception); + assertThrows(IllegalArgumentException.class, + () -> images.forEach(i -> table.addRow(i.asImageData()))); } @Test - public void testCreateTableWithROIsFromIJResults1() throws Exception { + void testCreateTableWithROIsFromIJResults1() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -234,7 +268,7 @@ public void testCreateTableWithROIsFromIJResults1() throws Exception { @Test - public void testCreateTableWithROIsFromIJResults2() throws Exception { + void testCreateTableWithROIsFromIJResults2() throws Exception { String property = "Cell"; ImageWrapper image = client.getImage(IMAGE1.id); @@ -293,7 +327,7 @@ public void testCreateTableWithROIsFromIJResults2() throws Exception { @Test - public void testCreateTableWithROIsFromIJResults3() throws Exception { + void testCreateTableWithROIsFromIJResults3() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -346,7 +380,7 @@ public void testCreateTableWithROIsFromIJResults3() throws Exception { @Test - public void testCreateTableWithROIsFromIJResults4() throws Exception { + void testCreateTableWithROIsFromIJResults4() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -399,7 +433,7 @@ public void testCreateTableWithROIsFromIJResults4() throws Exception { @Test - public void testCreateTableFromIJResults() throws Exception { + void testCreateTableFromIJResults() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List ijRois = new ArrayList<>(0); @@ -433,7 +467,7 @@ public void testCreateTableFromIJResults() throws Exception { @Test - public void testAddRowsFromIJResults() throws Exception { + void testAddRowsFromIJResults() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List ijRois = new ArrayList<>(0); @@ -479,7 +513,7 @@ public void testAddRowsFromIJResults() throws Exception { @Test - public void testAddRowsWithROIsFromIJResults() throws Exception { + void testAddRowsWithROIsFromIJResults() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -545,7 +579,7 @@ public void testAddRowsWithROIsFromIJResults() throws Exception { @Test - public void testCreateTableWithLocalROIFromIJResults1() throws Exception { + void testCreateTableWithLocalROIFromIJResults1() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -611,7 +645,7 @@ public void testCreateTableWithLocalROIFromIJResults1() throws Exception { @Test - public void testCreateTableWithLocalROIFromIJResults2() throws Exception { + void testCreateTableWithLocalROIFromIJResults2() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -675,7 +709,7 @@ public void testCreateTableWithLocalROIFromIJResults2() throws Exception { @Test - public void testCreateTableWithROINamesFromIJResults1() throws Exception { + void testCreateTableWithROINamesFromIJResults1() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi1 = new ROIWrapper(); @@ -746,7 +780,7 @@ public void testCreateTableWithROINamesFromIJResults1() throws Exception { @Test - public void testCreateTableWithROINamesFromIJResults2() throws Exception { + void testCreateTableWithROINamesFromIJResults2() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi1 = new ROIWrapper(); @@ -818,7 +852,7 @@ public void testCreateTableWithROINamesFromIJResults2() throws Exception { @Test - public void testAddRowsFromIJResultsError() throws Exception { + void testAddRowsFromIJResultsError() throws Exception { boolean error = false; ImageWrapper image = client.getImage(IMAGE1.id); @@ -848,7 +882,7 @@ public void testAddRowsFromIJResultsError() throws Exception { @Test - public void testAddRowsFromIJResultsInverted() throws Exception { + void testAddRowsFromIJResultsInverted() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List ijRois = new ArrayList<>(0); @@ -894,7 +928,7 @@ public void testAddRowsFromIJResultsInverted() throws Exception { @Test - public void testSaveTableAs() throws Exception { + void testSaveTableAs() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); ROIWrapper roi = new ROIWrapper(); @@ -933,12 +967,14 @@ public void testSaveTableAs() throws Exception { TableWrapper table = new TableWrapper(client, results1, IMAGE1.id, ijRois); table.addRows(client, results2, IMAGE1.id, ijRois); + @SuppressWarnings("MagicCharacter") + char delimiter = '\t'; String filename = "file.csv"; - table.saveAs(filename, ','); + table.saveAs(filename, delimiter); - String line1 = "\"Image\",\"ROI\",\"Label\",\"Volume\",\"Volume_Unit\""; - String line2 = String.format("\"1\",\"%d\",\"image1.fake\",\"%.1f\",\"µm^3\"", roi.getId(), volume1); - String line3 = String.format("\"1\",\"%d\",\"image1.fake\",\"%.1f\",\"m^3\"", roi.getId(), volume2); + String line1 = "\"Image\"\t\"ROI\"\t\"Label\"\t\"Volume\"\t\"Volume_Unit\""; + String line2 = String.format("\"1\"\t\"%d\"\t\"image1.fake\"\t\"%.1f\"\t\"µm^3\"", roi.getId(), volume1); + String line3 = String.format("\"1\"\t\"%d\"\t\"image1.fake\"\t\"%.1f\"\t\"m^3\"", roi.getId(), volume2); List expected = Arrays.asList(line1, line2, line3); diff --git a/src/test/java/fr/igred/omero/annotations/TagTest.java b/src/test/java/fr/igred/omero/annotations/TagTest.java index f774a1c1..4bfd3cce 100644 --- a/src/test/java/fr/igred/omero/annotations/TagTest.java +++ b/src/test/java/fr/igred/omero/annotations/TagTest.java @@ -23,19 +23,19 @@ import fr.igred.omero.repository.ProjectWrapper; import fr.igred.omero.repository.ScreenWrapper; import fr.igred.omero.repository.WellWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class TagTest extends UserTest { +class TagTest extends UserTest { @Test - public void testGetTagInfo() throws Exception { + void testGetTagInfo() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); assertEquals(TAG1.id, tag.getId()); assertEquals(TAG1.name, tag.getName()); @@ -44,14 +44,14 @@ public void testGetTagInfo() throws Exception { @Test - public void testGetTags() throws Exception { + void testGetTags() throws Exception { List tags = client.getTags(); assertEquals(3, tags.size()); } @Test - public void testGetTagsSorted() throws Exception { + void testGetTagsSorted() throws Exception { List tags = client.getTags(); for (int i = 1; i < tags.size(); i++) { assertTrue(tags.get(i - 1).getId() <= tags.get(i).getId()); @@ -60,7 +60,7 @@ public void testGetTagsSorted() throws Exception { @Test - public void testGetProjects() throws Exception { + void testGetProjects() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); List projects = tag.getProjects(client); assertEquals(1, projects.size()); @@ -69,7 +69,7 @@ public void testGetProjects() throws Exception { @Test - public void testGetDatasets() throws Exception { + void testGetDatasets() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); List datasets = tag.getDatasets(client); assertEquals(1, datasets.size()); @@ -78,7 +78,7 @@ public void testGetDatasets() throws Exception { @Test - public void testGetImages() throws Exception { + void testGetImages() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); List images = tag.getImages(client); assertEquals(3, images.size()); @@ -89,7 +89,7 @@ public void testGetImages() throws Exception { @Test - public void testGetScreens() throws Exception { + void testGetScreens() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); List screens = tag.getScreens(client); assertEquals(1, screens.size()); @@ -98,7 +98,7 @@ public void testGetScreens() throws Exception { @Test - public void testGetPlates() throws Exception { + void testGetPlates() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); List plates = tag.getPlates(client); assertEquals(1, plates.size()); @@ -107,7 +107,7 @@ public void testGetPlates() throws Exception { @Test - public void testGetWells() throws Exception { + void testGetWells() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); List wells = tag.getWells(client); assertEquals(1, wells.size()); @@ -116,7 +116,7 @@ public void testGetWells() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); String name = tag.getName(); @@ -132,7 +132,7 @@ public void testSetName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG1.id); String description = tag.getDescription(); diff --git a/src/test/java/fr/igred/omero/meta/ExperimenterTest.java b/src/test/java/fr/igred/omero/meta/ExperimenterTest.java index 9c39e4b9..8fa3cd3d 100644 --- a/src/test/java/fr/igred/omero/meta/ExperimenterTest.java +++ b/src/test/java/fr/igred/omero/meta/ExperimenterTest.java @@ -17,40 +17,41 @@ import fr.igred.omero.RootTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ExperimenterTest extends RootTest { +class ExperimenterTest extends RootTest { - @Test(expected = NoSuchElementException.class) - public void testGetWrongUser() throws Exception { - client.getUser("nonexistent"); + @Test + void testGetWrongUser() { + assertThrows(NoSuchElementException.class, () -> client.getUser("nonexistent")); } - @Test(expected = NoSuchElementException.class) - public void testSudoWrongUser() throws Exception { - client.sudoGetUser("nonexistent"); + @Test + void testSudoWrongUser() { + assertThrows(NoSuchElementException.class, () -> client.sudoGetUser("nonexistent")); } @Test - public void testGetUsername() throws Exception { + void testGetUsername() throws Exception { ExperimenterWrapper experimenter = client.getUser(USER1.name); assertEquals(USER1.name, experimenter.getUserName()); } @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { final String first = "Test"; final String last = "User"; final String middle = "O."; @@ -67,7 +68,7 @@ public void testSetName() throws Exception { @Test - public void testSetEmail() throws Exception { + void testSetEmail() throws Exception { final String email = "test.user1.name@example.org"; ExperimenterWrapper experimenter = client.getUser(USER1.name); @@ -78,7 +79,7 @@ public void testSetEmail() throws Exception { @Test - public void testSetInstitution() throws Exception { + void testSetInstitution() throws Exception { final String institution = "Example"; ExperimenterWrapper experimenter = client.getUser(USER1.name); @@ -89,21 +90,21 @@ public void testSetInstitution() throws Exception { @Test - public void testIsActive() throws Exception { + void testIsActive() throws Exception { ExperimenterWrapper experimenter = client.getUser(USER1.name); assertTrue(experimenter.isActive()); } @Test - public void testIsLDAP() throws Exception { + void testIsLDAP() throws Exception { ExperimenterWrapper experimenter = client.getUser(USER1.name); assertFalse(experimenter.isLDAP()); } @Test - public void testIsMemberOfGroup() throws Exception { + void testIsMemberOfGroup() throws Exception { ExperimenterWrapper experimenter = client.getUser(USER1.name); assertFalse(experimenter.isMemberOfGroup(0L)); assertTrue(experimenter.isMemberOfGroup(GROUP1.id)); @@ -111,7 +112,7 @@ public void testIsMemberOfGroup() throws Exception { @Test - public void testGetGroups() throws Exception { + void testGetGroups() throws Exception { ExperimenterWrapper experimenter = client.getUser(USER1.name); List groups = experimenter.getGroups(); assertEquals(3, groups.size()); diff --git a/src/test/java/fr/igred/omero/meta/GroupTest.java b/src/test/java/fr/igred/omero/meta/GroupTest.java index c420e15e..26574e0a 100644 --- a/src/test/java/fr/igred/omero/meta/GroupTest.java +++ b/src/test/java/fr/igred/omero/meta/GroupTest.java @@ -17,25 +17,26 @@ import fr.igred.omero.RootTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class GroupTest extends RootTest { +class GroupTest extends RootTest { - @Test(expected = NoSuchElementException.class) - public void testGetWrongGroup() throws Exception { - client.getGroup("nonexistent"); + @Test + void testGetWrongGroup() { + assertThrows(NoSuchElementException.class, () -> client.getGroup("nonexistent")); } @Test - public void testSetGroupName() throws Exception { + void testSetGroupName() throws Exception { GroupWrapper group = client.getGroup("testGroup2"); assertEquals("testGroup2", group.getName()); group.setName("Empty"); @@ -48,7 +49,7 @@ public void testSetGroupName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { GroupWrapper group = client.getGroup("testGroup1"); assertEquals(GroupWrapper.PERMISSIONS_GROUP_READ, group.getPermissionsLevel()); group.setDescription("Test"); @@ -58,7 +59,7 @@ public void testSetDescription() throws Exception { @Test - public void testGetExperimenters() throws Exception { + void testGetExperimenters() throws Exception { GroupWrapper group = client.getGroup("testGroup3"); List experimenters = group.getExperimenters(); @@ -76,7 +77,7 @@ public void testGetExperimenters() throws Exception { @Test - public void testGetMembersOnly() throws Exception { + void testGetMembersOnly() throws Exception { GroupWrapper group = client.getGroup("testGroup3"); List members = group.getMembersOnly(); @@ -86,7 +87,7 @@ public void testGetMembersOnly() throws Exception { @Test - public void testGetLeaders() throws Exception { + void testGetLeaders() throws Exception { GroupWrapper group = client.getGroup("testGroup3"); List leaders = group.getLeaders(); diff --git a/src/test/java/fr/igred/omero/repository/DatasetTest.java b/src/test/java/fr/igred/omero/repository/DatasetTest.java index 00422322..690224c8 100644 --- a/src/test/java/fr/igred/omero/repository/DatasetTest.java +++ b/src/test/java/fr/igred/omero/repository/DatasetTest.java @@ -18,25 +18,25 @@ import fr.igred.omero.UserTest; import fr.igred.omero.annotations.TagAnnotationWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class DatasetTest extends UserTest { +class DatasetTest extends UserTest { @Test - public void testCreateDatasetAndDeleteIt1() throws Exception { - boolean exception = false; - String name = "To delete"; + void testCreateDatasetAndDeleteIt1() throws Exception { + String name = "To delete"; ProjectWrapper project = client.getProject(PROJECT1.id); @@ -54,20 +54,12 @@ public void testCreateDatasetAndDeleteIt1() throws Exception { assertFalse(dataset.canChown()); client.delete(dataset); - - try { - client.getDataset(id); - } catch (NoSuchElementException e) { - exception = true; - } - assertTrue(exception); + assertThrows(NoSuchElementException.class, () -> client.getDataset(id)); } @Test - public void testCreateDatasetAndDeleteIt2() throws Exception { - boolean exception = false; - + void testCreateDatasetAndDeleteIt2() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); String description = "Dataset which will be deleted"; @@ -78,20 +70,13 @@ public void testCreateDatasetAndDeleteIt2() throws Exception { DatasetWrapper checkDataset = client.getDataset(id); client.delete(checkDataset); - - try { - client.getDataset(id); - } catch (NoSuchElementException e) { - exception = true; - } - + assertThrows(NoSuchElementException.class, () -> client.getDataset(id)); assertEquals(description, checkDataset.getDescription()); - assertTrue(exception); } @Test - public void testCopyDataset() throws Exception { + void testCopyDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -123,7 +108,7 @@ public void testCopyDataset() throws Exception { @Test - public void testDatasetBasic() throws Exception { + void testDatasetBasic() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); assertEquals(DATASET1.name, dataset.getName()); @@ -133,7 +118,7 @@ public void testDatasetBasic() throws Exception { @Test - public void testAddTagToDataset() throws Exception { + void testAddTagToDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); @@ -150,7 +135,7 @@ public void testAddTagToDataset() throws Exception { @Test - public void testAddTagToDataset2() throws Exception { + void testAddTagToDataset2() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); dataset.addTag(client, "Dataset tag", "tag attached to a dataset"); @@ -166,30 +151,22 @@ public void testAddTagToDataset2() throws Exception { @Test - public void testAddTagIdToDataset() throws Exception { - boolean exception = false; - + void testAddTagIdToDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - dataset.addTag(client, tag.getId()); - + long tagId = tag.getId(); + dataset.addTag(client, tagId); List tags = dataset.getTags(client); client.delete(tag); - try { - client.getTag(tag.getId()); - } catch (NullPointerException e) { - exception = true; - } - + assertThrows(NullPointerException.class, () -> client.getTag(tagId)); assertEquals(1, tags.size()); - assertTrue(exception); } @Test - public void testAddTagsToDataset() throws Exception { + void testAddTagsToDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); @@ -212,7 +189,7 @@ public void testAddTagsToDataset() throws Exception { @Test - public void testAddTagsToDataset2() throws Exception { + void testAddTagsToDataset2() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); @@ -235,7 +212,7 @@ public void testAddTagsToDataset2() throws Exception { @Test - public void testAddAndRemoveTagFromDataset() throws Exception { + void testAddAndRemoveTagFromDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); @@ -253,13 +230,13 @@ public void testAddAndRemoveTagFromDataset() throws Exception { @Test - public void testGetProjects() throws Exception { + void testGetProjects() throws Exception { assertEquals(PROJECT1.id, client.getImage(DATASET1.id).getProjects(client).get(0).getId()); } @Test - public void testGetImagesInDataset() throws Exception { + void testGetImagesInDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -269,7 +246,7 @@ public void testGetImagesInDataset() throws Exception { @Test - public void testGetImagesByNameInDataset() throws Exception { + void testGetImagesByNameInDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client, "image1.fake"); @@ -279,7 +256,7 @@ public void testGetImagesByNameInDataset() throws Exception { @Test - public void testGetImagesLikeInDataset() throws Exception { + void testGetImagesLikeInDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImagesLike(client, ".fake"); @@ -289,7 +266,7 @@ public void testGetImagesLikeInDataset() throws Exception { @Test - public void testGetImagesTaggedInDataset() throws Exception { + void testGetImagesTaggedInDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImagesTagged(client, TAG1.id); @@ -299,7 +276,7 @@ public void testGetImagesTaggedInDataset() throws Exception { @Test - public void testGetImagesTaggedInDataset2() throws Exception { + void testGetImagesTaggedInDataset2() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG2.id); DatasetWrapper dataset = client.getDataset(DATASET1.id); @@ -310,7 +287,7 @@ public void testGetImagesTaggedInDataset2() throws Exception { @Test - public void testGetImagesKeyInDataset() throws Exception { + void testGetImagesKeyInDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImagesKey(client, "testKey1"); @@ -320,7 +297,7 @@ public void testGetImagesKeyInDataset() throws Exception { @Test - public void testGetImagesPairKeyValueInDataset() throws Exception { + void testGetImagesPairKeyValueInDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImagesPairKeyValue(client, "testKey1", "testValue1"); @@ -330,7 +307,7 @@ public void testGetImagesPairKeyValueInDataset() throws Exception { @Test - public void testGetImagesFromDataset() throws Exception { + void testGetImagesFromDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); List images = dataset.getImages(client); @@ -339,7 +316,7 @@ public void testGetImagesFromDataset() throws Exception { @Test - public void testAddFileDataset() throws Exception { + void testAddFileDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); File file = createRandomFile("test_dataset.txt"); @@ -351,7 +328,7 @@ public void testAddFileDataset() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); String name = dataset.getName(); @@ -367,7 +344,7 @@ public void testSetName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); String description = dataset.getDescription(); diff --git a/src/test/java/fr/igred/omero/repository/FolderTest.java b/src/test/java/fr/igred/omero/repository/FolderTest.java index 771a843c..b5e2a14f 100644 --- a/src/test/java/fr/igred/omero/repository/FolderTest.java +++ b/src/test/java/fr/igred/omero/repository/FolderTest.java @@ -20,31 +20,31 @@ import fr.igred.omero.annotations.TagAnnotationWrapper; import fr.igred.omero.roi.ROIWrapper; import fr.igred.omero.roi.RectangleWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.NoSuchElementException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class FolderTest extends UserTest { +class FolderTest extends UserTest { - @Test(expected = NoSuchElementException.class) - public void testGetDeletedFolder() throws Exception { + @Test + void testGetDeletedFolder() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); FolderWrapper folder = new FolderWrapper(client, "Test"); - folder.setImage(image); - folder = image.getFolder(client, folder.getId()); + long id = folder.getId(); client.delete(folder); - image.getFolder(client, folder.getId()); + assertThrows(NoSuchElementException.class, () -> image.getFolder(client, id)); } @Test - public void testFolder1() throws Exception { + void testFolder1() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); FolderWrapper folder = new FolderWrapper(client, "Test"); @@ -83,7 +83,7 @@ public void testFolder1() throws Exception { @Test - public void testFolder2() throws Exception { + void testFolder2() throws Exception { FolderWrapper folder = new FolderWrapper(client, "Test"); folder.setImage(IMAGE2.id); @@ -118,7 +118,7 @@ public void testFolder2() throws Exception { @Test - public void testFolder3() throws Exception { + void testFolder3() throws Exception { final int nImages = 16; ImageWrapper image = client.getImage(IMAGE2.id); @@ -185,7 +185,7 @@ public void testFolder3() throws Exception { @Test - public void testAddAndRemoveTagFromFolder() throws Exception { + void testAddAndRemoveTagFromFolder() throws Exception { FolderWrapper folder = new FolderWrapper(client, "Test1"); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a folder"); diff --git a/src/test/java/fr/igred/omero/repository/ImageImportTest.java b/src/test/java/fr/igred/omero/repository/ImageImportTest.java new file mode 100644 index 00000000..53b348e5 --- /dev/null +++ b/src/test/java/fr/igred/omero/repository/ImageImportTest.java @@ -0,0 +1,349 @@ +/* + * Copyright (C) 2020-2022 GReD + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 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 General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package fr.igred.omero.repository; + + +import fr.igred.omero.UserTest; +import fr.igred.omero.annotations.TableWrapper; +import fr.igred.omero.annotations.TagAnnotationWrapper; +import fr.igred.omero.roi.ROIWrapper; +import fr.igred.omero.roi.RectangleWrapper; +import org.junit.jupiter.api.Test; + +import java.io.File; +import java.util.List; + +import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE; +import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE_ORPHANED; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class ImageImportTest extends UserTest { + + + @Test + void testImportImage() throws Exception { + String filename1 = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; + String filename2 = "8bit-unsigned&pixelType=uint8&sizeZ=4&sizeC=5&sizeT=6&sizeX=512&sizeY=512.fake"; + + File f1 = createFile(filename1); + File f2 = createFile(filename2); + + DatasetWrapper dataset = client.getDataset(DATASET2.id); + + boolean imported = dataset.importImages(client, f1.getAbsolutePath(), f2.getAbsolutePath()); + + removeFile(f1); + removeFile(f2); + + List images = dataset.getImages(client); + client.delete(images); + List endImages = dataset.getImages(client); + + assertEquals(2, images.size()); + assertTrue(endImages.isEmpty()); + assertTrue(imported); + } + + + @Test + void testReplaceAndDeleteImages() throws Exception { + String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&sizeX=512&sizeY=512.fake"; + + DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); + client.getProject(PROJECT1.id).addDataset(client, dataset); + + File imageFile = createFile(filename); + File file = createRandomFile("test_image.txt"); + + List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); + ImageWrapper image1 = client.getImage(ids1.get(0)); + image1.setDescription("This is"); + image1.saveAndUpdate(client); + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "ReplaceTestTag1", "Copy annotations"); + image1.addTag(client, tag1); + image1.addPairKeyValue(client, "Map", "ReplaceTest"); + + long fileId = image1.addFile(client, file); + removeFile(file); + assertNotEquals(0L, fileId); + + List ids2 = dataset.importImage(client, imageFile.getAbsolutePath()); + ImageWrapper image2 = client.getImage(ids2.get(0)); + image2.setDescription("a test."); + image2.saveAndUpdate(client); + + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "ReplaceTestTag2", "Copy annotations"); + image2.addTag(client, tag2); + image2.addFileAnnotation(client, image1.getFileAnnotations(client).get(0)); + image2.addMapAnnotation(client, image1.getMapAnnotations(client).get(0)); + + final RectangleWrapper rectangle = new RectangleWrapper(30, 30, 20, 20); + ROIWrapper roi = new ROIWrapper(); + roi.setImage(image2); + roi.addShape(rectangle); + image2.saveROI(client, roi); + + FolderWrapper folder = new FolderWrapper(client, "ReplaceTestFolder"); + folder.setImage(image2); + folder.addROI(client, roi); + + TableWrapper table = new TableWrapper(1, "ReplaceTestTable"); + table.setColumn(0, "Name", String.class); + table.setRowCount(1); + table.addRow("Annotation"); + image1.addTable(client, table); + image2.addTable(client, table); + + List ids3 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE); + ImageWrapper image3 = client.getImage(ids3.get(0)); + + assertEquals(2, image3.getTags(client).size()); + assertEquals(2, image3.getTables(client).size()); + assertEquals(3, image3.getFileAnnotations(client).size()); + assertEquals(1, image3.getMapAnnotations(client).size()); + assertEquals(1, image3.getROIs(client).size()); + assertEquals(1, image3.getFolders(client).size()); + assertEquals("ReplaceTestTag1", image3.getTags(client).get(0).getName()); + assertEquals("ReplaceTestTag2", image3.getTags(client).get(1).getName()); + assertEquals("ReplaceTest", image3.getValue(client, "Map")); + assertEquals("ReplaceTestTable", image3.getTables(client).get(0).getName()); + //noinspection HardcodedLineSeparator + assertEquals("This is\na test.", image3.getDescription()); + + client.delete(image3.getMapAnnotations(client).get(0)); + removeFile(imageFile); + + List images = dataset.getImages(client); + + client.delete(images); + List endImages = dataset.getImages(client); + client.delete(dataset); + client.delete(tag1); + client.delete(tag2); + client.delete(table); + client.deleteFile(fileId); + client.delete(roi); + client.delete(folder); + + assertEquals(1, images.size()); + assertTrue(endImages.isEmpty()); + } + + + @Test + void testReplaceAndUnlinkImages() throws Exception { + String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&sizeX=512&sizeY=512.fake"; + + DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); + client.getProject(PROJECT1.id).addDataset(client, dataset); + + File imageFile = createFile(filename); + File file = createRandomFile("test_image.txt"); + + List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); + ImageWrapper image1 = client.getImage(ids1.get(0)); + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "ReplaceTestTag1", "Copy annotations"); + image1.addTag(client, tag1); + image1.addPairKeyValue(client, "Map", "ReplaceTest"); + + long fileId = image1.addFile(client, file); + removeFile(file); + assertNotEquals(0L, fileId); + + List ids2 = dataset.importImage(client, imageFile.getAbsolutePath()); + ImageWrapper image2 = client.getImage(ids2.get(0)); + image2.setDescription("A test."); + image2.saveAndUpdate(client); + + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "ReplaceTestTag2", "Copy annotations"); + image2.addTag(client, tag2); + image2.addFileAnnotation(client, image1.getFileAnnotations(client).get(0)); + image2.addMapAnnotation(client, image1.getMapAnnotations(client).get(0)); + + final RectangleWrapper rectangle = new RectangleWrapper(30, 30, 20, 20); + ROIWrapper roi = new ROIWrapper(); + roi.setImage(image2); + roi.addShape(rectangle); + image2.saveROI(client, roi); + + FolderWrapper folder = new FolderWrapper(client, "ReplaceTestFolder"); + folder.setImage(image2); + folder.addROI(client, roi); + + TableWrapper table = new TableWrapper(1, "ReplaceTestTable"); + table.setColumn(0, "Name", String.class); + table.setRowCount(1); + table.addRow("Annotation"); + image1.addTable(client, table); + image2.addTable(client, table); + + List ids3 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath()); + ImageWrapper image3 = client.getImage(ids3.get(0)); + + assertEquals(2, image3.getTags(client).size()); + assertEquals(2, image3.getTables(client).size()); + assertEquals(3, image3.getFileAnnotations(client).size()); + assertEquals(1, image3.getMapAnnotations(client).size()); + assertEquals(1, image3.getROIs(client).size()); + assertEquals(1, image3.getFolders(client).size()); + assertEquals("ReplaceTestTag1", image3.getTags(client).get(0).getName()); + assertEquals("ReplaceTestTag2", image3.getTags(client).get(1).getName()); + assertEquals("ReplaceTest", image3.getValue(client, "Map")); + assertEquals("ReplaceTestTable", image3.getTables(client).get(0).getName()); + assertEquals("A test.", image3.getDescription()); + + client.delete(image3.getMapAnnotations(client).get(0)); + removeFile(imageFile); + + List images = dataset.getImages(client); + + for (ImageWrapper image : images) { + client.delete(image); + } + List endImages = dataset.getImages(client); + client.delete(dataset); + client.delete(tag1); + client.delete(tag2); + client.delete(table); + client.deleteFile(fileId); + client.delete(roi); + client.delete(folder); + client.delete(image1); + client.delete(image2); + + assertEquals(1, images.size()); + assertTrue(endImages.isEmpty()); + } + + + @Test + void testReplaceImagesFileset1() throws Exception { + String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&series=2&sizeX=512&sizeY=512.fake"; + + DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); + client.getProject(PROJECT1.id).addDataset(client, dataset); + + File imageFile = createFile(filename); + + List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); + List images1 = dataset.getImages(client); + + List ids2 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE); + List images2 = dataset.getImages(client); + + removeFile(imageFile); + + assertEquals(2, ids1.size()); + assertEquals(2, ids2.size()); + assertEquals(ids1.size(), images1.size()); + assertEquals(ids2.size(), images2.size()); + assertTrue(client.getImages(ids1.get(0), ids1.get(1)).isEmpty()); + + client.delete(images2); + List endImages = dataset.getImages(client); + client.delete(dataset); + + assertTrue(endImages.isEmpty()); + } + + + @Test + void testReplaceImagesFileset2() throws Exception { + String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&series=2&sizeX=512&sizeY=512.fake"; + + DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); + client.getProject(PROJECT1.id).addDataset(client, dataset); + + File imageFile = createFile(filename); + + List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); + assertEquals(2, ids1.size()); + List images1 = dataset.getImages(client); + assertEquals(ids1.size(), images1.size()); + dataset.removeImage(client, images1.get(0)); + List fsImages = images1.get(0).getFilesetImages(client); + assertEquals(images1.size(), fsImages.size()); + assertTrue(ids1.contains(fsImages.get(0).getId())); + assertTrue(ids1.contains(fsImages.get(1).getId())); + + List ids2 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE); + assertEquals(2, ids2.size()); + List images2 = dataset.getImages(client); + assertEquals(ids2.size(), images2.size()); + + removeFile(imageFile); + + List images3 = client.getImages(ids1.get(0), ids1.get(1)); + assertEquals(2, images3.size()); + assertFalse(images2.get(0).isOrphaned(client)); + assertTrue(images3.get(0).isOrphaned(client)); + + client.delete(images1); + client.delete(images2); + List endImages = dataset.getImages(client); + client.delete(dataset); + + assertTrue(endImages.isEmpty()); + } + + + @Test + void testReplaceImagesFileset3() throws Exception { + String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&series=2&sizeX=512&sizeY=512.fake"; + + DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); + client.getProject(PROJECT1.id).addDataset(client, dataset); + + File imageFile = createFile(filename); + + List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); + assertEquals(2, ids1.size()); + List images1 = dataset.getImages(client); + assertEquals(ids1.size(), images1.size()); + dataset.removeImage(client, images1.get(0)); + List fsImages = images1.get(0).getFilesetImages(client); + assertEquals(images1.size(), fsImages.size()); + assertTrue(ids1.contains(fsImages.get(0).getId())); + assertTrue(ids1.contains(fsImages.get(1).getId())); + + List ids2 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE_ORPHANED); + assertEquals(2, ids2.size()); + List images2 = dataset.getImages(client); + assertEquals(ids2.size(), images2.size()); + + removeFile(imageFile); + + assertEquals(2, ids1.size()); + assertEquals(2, ids2.size()); + assertEquals(ids1.size(), images1.size()); + assertEquals(ids2.size(), images2.size()); + assertTrue(client.getImages(ids1.get(0), ids1.get(1)).isEmpty()); + + client.delete(images2); + List endImages = dataset.getImages(client); + client.delete(dataset); + + assertTrue(endImages.isEmpty()); + } + + +} diff --git a/src/test/java/fr/igred/omero/repository/ImageTest.java b/src/test/java/fr/igred/omero/repository/ImageTest.java index ee340166..1e14101c 100644 --- a/src/test/java/fr/igred/omero/repository/ImageTest.java +++ b/src/test/java/fr/igred/omero/repository/ImageTest.java @@ -19,7 +19,6 @@ import fr.igred.omero.UserTest; import fr.igred.omero.annotations.FileAnnotationWrapper; import fr.igred.omero.annotations.MapAnnotationWrapper; -import fr.igred.omero.annotations.TableWrapper; import fr.igred.omero.annotations.TagAnnotationWrapper; import fr.igred.omero.roi.EllipseWrapper; import fr.igred.omero.roi.ROIWrapper; @@ -31,7 +30,7 @@ import loci.plugins.BF; import omero.gateway.model.MapAnnotationData; import omero.model.NamedValue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.awt.image.BufferedImage; import java.io.File; @@ -44,315 +43,241 @@ import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Random; -import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE; -import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE_ORPHANED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ImageTest extends UserTest { +class ImageTest extends UserTest { @Test - public void testGetDatasets() throws Exception { + void testGetDatasets() throws Exception { assertEquals(DATASET1.id, client.getImage(IMAGE1.id).getDatasets(client).get(0).getId()); } @Test - public void testGetProjects() throws Exception { + void testGetProjects() throws Exception { assertEquals(PROJECT1.id, client.getImage(IMAGE1.id).getProjects(client).get(0).getId()); } @Test - public void testImportImage() throws Exception { - String filename1 = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; - String filename2 = "8bit-unsigned&pixelType=uint8&sizeZ=4&sizeC=5&sizeT=6&sizeX=512&sizeY=512.fake"; - - File f1 = createFile(filename1); - File f2 = createFile(filename2); - - DatasetWrapper dataset = client.getDataset(DATASET2.id); - - boolean imported = dataset.importImages(client, f1.getAbsolutePath(), f2.getAbsolutePath()); - - removeFile(f1); - removeFile(f2); - - List images = dataset.getImages(client); - client.delete(images); - List endImages = dataset.getImages(client); - - assertEquals(2, images.size()); - assertTrue(endImages.isEmpty()); - assertTrue(imported); + void testGetScreens() throws Exception { + final long id = 5L; + assertEquals(SCREEN1.id, client.getImage(id).getScreens(client).get(0).getId()); } @Test - public void testPairKeyValue() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; - - File f = createFile(filename); - - DatasetWrapper dataset = client.getDataset(DATASET2.id); - - List newIDs = dataset.importImage(client, f.getAbsolutePath()); - assertEquals(1, newIDs.size()); - - removeFile(f); - - List images = dataset.getImages(client); - - ImageWrapper image = images.get(0); + void testGetPlates() throws Exception { + final long id = 5L; + assertEquals(PLATE1.id, client.getImage(id).getPlates(client).get(0).getId()); + } - List result1 = new ArrayList<>(2); - result1.add(new NamedValue("Test result1", "Value Test")); - result1.add(new NamedValue("Test2 result1", "Value Test2")); - Collection result2 = new ArrayList<>(2); - result2.add(new NamedValue("Test result2", "Value Test")); - result2.add(new NamedValue("Test2 result2", "Value Test2")); + @Test + void testGetWells() throws Exception { + final long wellId = 1L; + WellWrapper well = client.getWell(wellId); - MapAnnotationWrapper mapAnnotation1 = new MapAnnotationWrapper(result1); + long imageId = well.getWellSamples().get(0).getImage().getId(); + assertEquals(wellId, client.getImage(imageId).getWells(client).get(0).getId()); + } - MapAnnotationData mapData2 = new MapAnnotationData(); - mapData2.setContent(result2); - MapAnnotationWrapper mapAnnotation2 = new MapAnnotationWrapper(mapData2); - assertEquals(result1, mapAnnotation1.getContent()); + @Test + void testGetKeyValuePair1() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + Map pairs = image.getKeyValuePairs(client); + assertEquals(2, pairs.size()); + } - image.addMapAnnotation(client, mapAnnotation1); - image.addMapAnnotation(client, mapAnnotation2); - Map result = image.getKeyValuePairs(client); + @Test + void testGetKeyValuePair2() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + List annotations = image.getMapAnnotations(client); + assertEquals(1, annotations.size()); + } - assertEquals(4, result.size()); - assertEquals("Value Test", image.getValue(client, "Test result1")); - client.delete(image); + @Test + void testGetValue() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + String value = image.getValue(client, "testKey1"); + assertEquals("testValue1", value); } @Test - public void testPairKeyValue2() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; - - File f = createFile(filename); + void testGetValueWrongKey() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + assertThrows(NoSuchElementException.class, () -> image.getValue(client, "testKey")); + } - DatasetWrapper dataset = client.getDataset(DATASET2.id); - dataset.importImages(client, f.getAbsolutePath()); - removeFile(f); - List images = dataset.getImages(client); - ImageWrapper image = images.get(0); + @Test + void testAddKeyValuePair1() throws Exception { + final long imageId = 4L; + ImageWrapper image = client.getImage(imageId); - List result = new ArrayList<>(2); - result.add(new NamedValue("Test result1", "Value Test")); - result.add(new NamedValue("Test2 result1", "Value Test2")); + String name1 = "Test result1"; + String name2 = "Test2 result1"; + String value1 = "Value Test"; + String value2 = "Value Test2"; - MapAnnotationWrapper mapAnnotation = new MapAnnotationWrapper(); - mapAnnotation.setContent(result); + List values = new ArrayList<>(2); + values.add(new NamedValue(name1, value1)); + values.add(new NamedValue(name2, value2)); + MapAnnotationWrapper mapAnnotation = new MapAnnotationWrapper(values); image.addMapAnnotation(client, mapAnnotation); - Map results = image.getKeyValuePairs(client); + Map pairs = image.getKeyValuePairs(client); - assertEquals(2, results.size()); - assertEquals("Value Test", image.getValue(client, "Test result1")); + String value = image.getValue(client, name1); - client.delete(image); + client.delete(image.getMapAnnotations(client)); + + assertEquals(values, mapAnnotation.getContent()); + assertEquals(2, pairs.size()); + assertEquals(value1, value); } @Test - public void testPairKeyValue3() throws Exception { - boolean exception = false; - - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; + void testAddKeyValuePair2() throws Exception { + final long imageId = 4L; + ImageWrapper image = client.getImage(imageId); - File f = createFile(filename); + String name1 = "Test result2"; + String name2 = "Test2 result2"; + String value1 = "Value Test"; + String value2 = "Value Test2"; - DatasetWrapper dataset = client.getDataset(DATASET2.id); - dataset.importImages(client, f.getAbsolutePath()); - removeFile(f); - List images = dataset.getImages(client); + Collection values = new ArrayList<>(2); + values.add(new NamedValue(name1, value1)); + values.add(new NamedValue(name2, value2)); - ImageWrapper image = images.get(0); + MapAnnotationData mapData = new MapAnnotationData(); + mapData.setContent(values); - image.addPairKeyValue(client, "Test result1", "Value Test"); - image.addPairKeyValue(client, "Test result2", "Value Test2"); + MapAnnotationWrapper mapAnnotation = new MapAnnotationWrapper(mapData); + image.addMapAnnotation(client, mapAnnotation); - Map results = image.getKeyValuePairs(client); + Map pairs = image.getKeyValuePairs(client); - assertEquals(2, results.size()); - try { - image.getValue(client, "Nonexistent value"); - } catch (Exception e) { - exception = true; - } - client.delete(image); - assertTrue(exception); - } + String value = image.getValue(client, name2); + client.delete(image.getMapAnnotations(client)); - @Test - public void testGetImageInfo() throws Exception { - ImageWrapper image = client.getImage(IMAGE1.id); - assertEquals(IMAGE1.name, image.getName()); - assertNull(image.getDescription()); - assertEquals(1L, image.getId()); + assertEquals(values, mapAnnotation.getContent()); + assertEquals(2, pairs.size()); + assertEquals(value2, value); } @Test - public void testGetImageTag() throws Exception { - ImageWrapper image = client.getImage(IMAGE1.id); - - List tags = image.getTags(client); - assertEquals(2, tags.size()); - } + void testAddKeyValuePair3() throws Exception { + final long imageId = 4L; + ImageWrapper image = client.getImage(imageId); + String name1 = "Test result3"; + String name2 = "Test2 result3"; + String value1 = "Value Test"; + String value2 = "Value Test2"; - @Test - public void testGetImageSize() throws Exception { - final int sizeXY = 512; - final int sizeC = 5; - final int sizeZ = 3; - final int sizeT = 7; + List values = new ArrayList<>(2); + values.add(new NamedValue(name1, value1)); + values.add(new NamedValue(name2, value2)); - ImageWrapper image = client.getImage(IMAGE1.id); - PixelsWrapper pixels = image.getPixels(); + MapAnnotationWrapper mapAnnotation = new MapAnnotationWrapper(); + mapAnnotation.setContent(values); + image.addMapAnnotation(client, mapAnnotation); - assertEquals(sizeXY, pixels.getSizeX()); - assertEquals(sizeXY, pixels.getSizeY()); - assertEquals(sizeC, pixels.getSizeC()); - assertEquals(sizeZ, pixels.getSizeZ()); - assertEquals(sizeT, pixels.getSizeT()); - } + List maps = image.getMapAnnotations(client); + String value = image.getValue(client, name1); - @Test - public void testGetRawData() throws Exception { - ImageWrapper image = client.getImage(IMAGE1.id); - PixelsWrapper pixels = image.getPixels(); - double[][][][][] value = pixels.getAllPixels(client); + client.delete(image.getMapAnnotations(client)); - assertEquals(pixels.getSizeX(), value[0][0][0][0].length); - assertEquals(pixels.getSizeY(), value[0][0][0].length); - assertEquals(pixels.getSizeC(), value[0][0].length); - assertEquals(pixels.getSizeZ(), value[0].length); - assertEquals(pixels.getSizeT(), value.length); + assertEquals(values, mapAnnotation.getContent()); + assertEquals(1, maps.size()); + assertEquals(value1, value); } @Test - public void testGetRawData2() throws Exception { - ImageWrapper image = client.getImage(IMAGE1.id); - PixelsWrapper pixels = image.getPixels(); - byte[][][][] value = pixels.getRawPixels(client, 1); - - int sizeX = pixels.getSizeX(); - int sizeY = pixels.getSizeY(); - int sizeZ = pixels.getSizeZ(); - int sizeC = pixels.getSizeC(); - int sizeT = pixels.getSizeT(); - - assertEquals(sizeX * sizeY, value[0][0][0].length); - assertEquals(sizeC, value[0][0].length); - assertEquals(sizeZ, value[0].length); - assertEquals(sizeT, value.length); - } + void testAddKeyValuePair4() throws Exception { + final long imageId = 4L; + ImageWrapper image = client.getImage(imageId); + String key1 = "Test result4"; + String key2 = "Test2 result4"; + String value1 = "Value Test"; + String value2 = "Value Test2"; - @Test - public void testGetRawDataBound() throws Exception { - ImageWrapper image = client.getImage(IMAGE1.id); - PixelsWrapper pixels = image.getPixels(); + image.addPairKeyValue(client, key1, value1); + image.addPairKeyValue(client, key2, value2); - int[] xBound = {0, 2}; - int[] yBound = {0, 2}; - int[] cBound = {0, 2}; - int[] zBound = {0, 2}; - int[] tBound = {0, 2}; + List maps = image.getMapAnnotations(client); - double[][][][][] value = pixels.getAllPixels(client, xBound, yBound, cBound, zBound, tBound); + String value = image.getValue(client, key1); + client.delete(maps); - assertEquals(3, value[0][0][0][0].length); - assertEquals(3, value[0][0][0].length); - assertEquals(3, value[0][0].length); - assertEquals(3, value[0].length); - assertEquals(3, value.length); + assertEquals(2, maps.size()); + assertEquals(value1, value); } @Test - public void testGetRawDataBoundError() throws Exception { - ImageWrapper image = client.getImage(IMAGE1.id); - PixelsWrapper pixels = image.getPixels(); - - final int[] xBound = {511, 513}; - final int[] yBound = {0, 2}; - final int[] cBound = {0, 2}; - final int[] zBound = {0, 2}; - final int[] tBound = {0, 2}; - - double[][][][][] value = pixels.getAllPixels(client, xBound, yBound, cBound, zBound, tBound); - assertNotEquals(xBound[1] - xBound[0] + 1, value[0][0][0][0].length); + void testGetImageInfo() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + assertEquals(IMAGE1.name, image.getName()); + assertNull(image.getDescription()); + assertEquals(1L, image.getId()); } @Test - public void testGetRawDataBoundErrorNegative() throws Exception { - boolean success = true; - - ImageWrapper image = client.getImage(IMAGE1.id); - PixelsWrapper pixels = image.getPixels(); + void testGetImageTags() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); - int[] xBound = {-1, 1}; - int[] yBound = {0, 2}; - int[] cBound = {0, 2}; - int[] zBound = {0, 2}; - int[] tBound = {0, 2}; - try { - double[][][][][] value = pixels.getAllPixels(client, xBound, yBound, cBound, zBound, tBound); - success = false; - assertNotEquals(3, value[0][0][0][0].length); - } catch (Exception e) { - assertTrue(success); - } + List tags = image.getTags(client); + assertEquals(2, tags.size()); } @Test - public void testToImagePlusBound() throws Exception { + void testToImagePlusBound() throws Exception { final int lowXY = 500; final int highXY = 507; final double pixSize = 0.5; - int[] xBound = {0, 2}; - int[] yBound = {0, 2}; - int[] cBound = {0, 2}; - int[] zBound = {0, 2}; - int[] tBound = {0, 2}; + int[] xBounds = {0, 2}; + int[] yBounds = {0, 2}; + int[] cBounds = {0, 2}; + int[] zBounds = {0, 2}; + int[] tBounds = {0, 2}; Random random = new SecureRandom(); - xBound[0] = random.nextInt(lowXY); - yBound[0] = random.nextInt(lowXY); - cBound[0] = random.nextInt(3); - tBound[0] = random.nextInt(5); - xBound[1] = random.nextInt(highXY - xBound[0]) + xBound[0] + 5; - yBound[1] = random.nextInt(highXY - yBound[0]) + yBound[0] + 5; - cBound[1] = random.nextInt(3 - cBound[0]) + cBound[0] + 2; - tBound[1] = random.nextInt(5 - tBound[0]) + tBound[0] + 2; + xBounds[0] = random.nextInt(lowXY); + yBounds[0] = random.nextInt(lowXY); + cBounds[0] = random.nextInt(3); + tBounds[0] = random.nextInt(5); + xBounds[1] = random.nextInt(highXY - xBounds[0]) + xBounds[0] + 5; + yBounds[1] = random.nextInt(highXY - yBounds[0]) + yBounds[0] + 5; + cBounds[1] = random.nextInt(3 - cBounds[0]) + cBounds[0] + 2; + tBounds[1] = random.nextInt(5 - tBounds[0]) + tBounds[0] + 2; String fake = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; File fakeFile = createFile(fake); @@ -361,15 +286,15 @@ public void testToImagePlusBound() throws Exception { removeFile(fakeFile); Duplicator duplicator = new Duplicator(); - reference.setRoi(xBound[0], yBound[0], xBound[1] - xBound[0] + 1, yBound[1] - yBound[0] + 1); + reference.setRoi(xBounds[0], yBounds[0], xBounds[1] - xBounds[0] + 1, yBounds[1] - yBounds[0] + 1); ImagePlus crop = duplicator.run(reference, - cBound[0] + 1, cBound[1] + 1, - zBound[0] + 1, zBound[1] + 1, - tBound[0] + 1, tBound[1] + 1); + cBounds[0] + 1, cBounds[1] + 1, + zBounds[0] + 1, zBounds[1] + 1, + tBounds[0] + 1, tBounds[1] + 1); ImageWrapper image = client.getImage(IMAGE1.id); - ImagePlus imp = image.toImagePlus(client, xBound, yBound, cBound, zBound, tBound); + ImagePlus imp = image.toImagePlus(client, xBounds, yBounds, cBounds, zBounds, tBounds); ImageCalculator calculator = new ImageCalculator(); ImagePlus difference = calculator.run("difference create stack", crop, imp); @@ -378,13 +303,13 @@ public void testToImagePlusBound() throws Exception { assertEquals(pixSize, imp.getCalibration().pixelHeight, Double.MIN_VALUE); assertEquals(pixSize, imp.getCalibration().pixelWidth, Double.MIN_VALUE); assertEquals(1.0, imp.getCalibration().pixelDepth, Double.MIN_VALUE); - assertEquals("MICROMETER", imp.getCalibration().getUnit()); + assertEquals("µm", imp.getCalibration().getUnit()); assertEquals(0, (int) stats.max); } @Test - public void testToImagePlus() throws Exception { + void testToImagePlus() throws Exception { String fake = "8bit-unsigned&pixelType=uint8&sizeZ=2&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake"; File fakeFile = createFile(fake); @@ -404,29 +329,21 @@ public void testToImagePlus() throws Exception { @Test - public void testGetImageChannel() throws Exception { + void testGetImageChannel() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); assertEquals("0", image.getChannelName(client, 0)); } @Test - public void testGetImageChannelError() throws Exception { - boolean success = true; - + void testGetImageChannelError() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); - try { - image.getChannelName(client, 6); - success = false; - fail(); - } catch (Exception e) { - assertTrue(success); - } + assertThrows(IndexOutOfBoundsException.class, () -> image.getChannelName(client, 6)); } @Test - public void testAddTagToImage() throws Exception { + void testAddTagToImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "image tag", "tag attached to an image"); @@ -443,7 +360,7 @@ public void testAddTagToImage() throws Exception { @Test - public void testAddTagToImage2() throws Exception { + void testAddTagToImage2() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); image.addTag(client, "image tag", "tag attached to an image"); @@ -458,7 +375,7 @@ public void testAddTagToImage2() throws Exception { @Test - public void testAddTagIdToImage() throws Exception { + void testAddTagIdToImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "image tag", "tag attached to an image"); @@ -475,7 +392,7 @@ public void testAddTagIdToImage() throws Exception { @Test - public void testAddTagsToImage() throws Exception { + void testAddTagsToImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Image tag 1", "tag attached to an image"); @@ -497,7 +414,7 @@ public void testAddTagsToImage() throws Exception { @Test - public void testAddTagsToImage2() throws Exception { + void testAddTagsToImage2() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Image tag 1", "tag attached to an image"); @@ -519,7 +436,7 @@ public void testAddTagsToImage2() throws Exception { @Test - public void testAddAndRemoveTagFromImage() throws Exception { + void testAddAndRemoveTagFromImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to an image"); @@ -537,7 +454,7 @@ public void testAddAndRemoveTagFromImage() throws Exception { @Test - public void testImageOrder() throws Exception { + void testImageOrder() throws Exception { List images = client.getImages(); for (int i = 1; i < images.size(); i++) { assertTrue(images.get(i - 1).getId() <= images.get(i).getId()); @@ -546,7 +463,7 @@ public void testImageOrder() throws Exception { @Test - public void testAddFileImage() throws Exception { + void testAddFileImage() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); File file = createRandomFile("test_image.txt"); @@ -584,7 +501,7 @@ public void testAddFileImage() throws Exception { @Test - public void testGetCreated() throws Exception { + void testGetCreated() throws Exception { LocalDate created = client.getImage(IMAGE1.id).getCreated().toLocalDateTime().toLocalDate(); LocalDate now = LocalDate.now(); @@ -593,7 +510,7 @@ public void testGetCreated() throws Exception { @Test - public void testGetAcquisitionDate() throws Exception { + void testGetAcquisitionDate() throws Exception { LocalDateTime acq = client.getImage(IMAGE1.id).getAcquisitionDate().toLocalDateTime(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"); @@ -602,7 +519,7 @@ public void testGetAcquisitionDate() throws Exception { @Test - public void testGetChannel() throws Exception { + void testGetChannel() throws Exception { ChannelWrapper channel = client.getImage(IMAGE1.id).getChannels(client).get(0); assertEquals(0, channel.getIndex()); channel.setName("Foo channel"); @@ -611,7 +528,7 @@ public void testGetChannel() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); String description = image.getDescription(); @@ -626,7 +543,7 @@ public void testSetDescription() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); String name = image.getName(); @@ -641,7 +558,7 @@ public void testSetName() throws Exception { @Test - public void testGetCropFromROI() throws Exception { + void testGetCropFromROI() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); final RectangleWrapper rectangle = new RectangleWrapper(30, 30, 20, 20); @@ -650,11 +567,11 @@ public void testGetCropFromROI() throws Exception { final EllipseWrapper ellipse = new EllipseWrapper(50, 50, 20, 40); ellipse.setCZT(1, 0, 1); - final int[] xBound = {30, 69}; - final int[] yBound = {10, 89}; - final int[] cBound = {1, 1}; - final int[] zBound = {0, 1}; - final int[] tBound = {1, 2}; + final int[] xBounds = {30, 69}; + final int[] yBounds = {10, 89}; + final int[] cBounds = {1, 1}; + final int[] zBounds = {0, 1}; + final int[] tBounds = {1, 2}; ROIWrapper roiWrapper = new ROIWrapper(); roiWrapper.setImage(image); @@ -662,7 +579,7 @@ public void testGetCropFromROI() throws Exception { roiWrapper.addShape(ellipse); ImagePlus imp1 = image.toImagePlus(client, roiWrapper); - ImagePlus imp2 = image.toImagePlus(client, xBound, yBound, cBound, zBound, tBound); + ImagePlus imp2 = image.toImagePlus(client, xBounds, yBounds, cBounds, zBounds, tBounds); ImageCalculator calculator = new ImageCalculator(); ImagePlus difference = calculator.run("difference create stack", imp1, imp2); @@ -678,7 +595,7 @@ public void testGetCropFromROI() throws Exception { @Test - public void testGetThumbnail() throws Exception { + void testGetThumbnail() throws Exception { final int size = 96; ImageWrapper image = client.getImage(IMAGE1.id); @@ -690,7 +607,7 @@ public void testGetThumbnail() throws Exception { @Test - public void testDownload() throws Exception { + void testDownload() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List files = image.download(client, "."); assertEquals(2, files.size()); @@ -700,287 +617,4 @@ public void testDownload() throws Exception { } - @Test - public void testReplaceAndDeleteImages() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&sizeX=512&sizeY=512.fake"; - - DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); - client.getProject(PROJECT1.id).addDataset(client, dataset); - - File imageFile = createFile(filename); - File file = createRandomFile("test_image.txt"); - - List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); - ImageWrapper image1 = client.getImage(ids1.get(0)); - image1.setDescription("This is"); - image1.saveAndUpdate(client); - - TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "ReplaceTestTag1", "Copy annotations"); - image1.addTag(client, tag1); - image1.addPairKeyValue(client, "Map", "ReplaceTest"); - - long fileId = image1.addFile(client, file); - removeFile(file); - assertNotEquals(0L, fileId); - - List ids2 = dataset.importImage(client, imageFile.getAbsolutePath()); - ImageWrapper image2 = client.getImage(ids2.get(0)); - image2.setDescription("a test."); - image2.saveAndUpdate(client); - - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "ReplaceTestTag2", "Copy annotations"); - image2.addTag(client, tag2); - image2.addFileAnnotation(client, image1.getFileAnnotations(client).get(0)); - image2.addMapAnnotation(client, image1.getMapAnnotations(client).get(0)); - - final RectangleWrapper rectangle = new RectangleWrapper(30, 30, 20, 20); - ROIWrapper roi = new ROIWrapper(); - roi.setImage(image2); - roi.addShape(rectangle); - image2.saveROI(client, roi); - - FolderWrapper folder = new FolderWrapper(client, "ReplaceTestFolder"); - folder.setImage(image2); - folder.addROI(client, roi); - - TableWrapper table = new TableWrapper(1, "ReplaceTestTable"); - table.setColumn(0, "Name", String.class); - table.setRowCount(1); - table.addRow("Annotation"); - image1.addTable(client, table); - image2.addTable(client, table); - - List ids3 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE); - ImageWrapper image3 = client.getImage(ids3.get(0)); - - assertEquals(2, image3.getTags(client).size()); - assertEquals(2, image3.getTables(client).size()); - assertEquals(3, image3.getFileAnnotations(client).size()); - assertEquals(1, image3.getMapAnnotations(client).size()); - assertEquals(1, image3.getROIs(client).size()); - assertEquals(1, image3.getFolders(client).size()); - assertEquals("ReplaceTestTag1", image3.getTags(client).get(0).getName()); - assertEquals("ReplaceTestTag2", image3.getTags(client).get(1).getName()); - assertEquals("ReplaceTest", image3.getValue(client, "Map")); - assertEquals("ReplaceTestTable", image3.getTables(client).get(0).getName()); - assertEquals("This is\na test.", image3.getDescription()); - - client.delete(image3.getMapAnnotations(client).get(0)); - removeFile(imageFile); - - List images = dataset.getImages(client); - - client.delete(images); - List endImages = dataset.getImages(client); - client.delete(dataset); - client.delete(tag1); - client.delete(tag2); - client.delete(table); - client.deleteFile(fileId); - client.delete(roi); - client.delete(folder); - - assertEquals(1, images.size()); - assertTrue(endImages.isEmpty()); - } - - - @Test - public void testReplaceAndUnlinkImages() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&sizeX=512&sizeY=512.fake"; - - DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); - client.getProject(PROJECT1.id).addDataset(client, dataset); - - File imageFile = createFile(filename); - File file = createRandomFile("test_image.txt"); - - List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); - ImageWrapper image1 = client.getImage(ids1.get(0)); - - TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "ReplaceTestTag1", "Copy annotations"); - image1.addTag(client, tag1); - image1.addPairKeyValue(client, "Map", "ReplaceTest"); - - long fileId = image1.addFile(client, file); - removeFile(file); - assertNotEquals(0L, fileId); - - List ids2 = dataset.importImage(client, imageFile.getAbsolutePath()); - ImageWrapper image2 = client.getImage(ids2.get(0)); - image2.setDescription("A test."); - image2.saveAndUpdate(client); - - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "ReplaceTestTag2", "Copy annotations"); - image2.addTag(client, tag2); - image2.addFileAnnotation(client, image1.getFileAnnotations(client).get(0)); - image2.addMapAnnotation(client, image1.getMapAnnotations(client).get(0)); - - final RectangleWrapper rectangle = new RectangleWrapper(30, 30, 20, 20); - ROIWrapper roi = new ROIWrapper(); - roi.setImage(image2); - roi.addShape(rectangle); - image2.saveROI(client, roi); - - FolderWrapper folder = new FolderWrapper(client, "ReplaceTestFolder"); - folder.setImage(image2); - folder.addROI(client, roi); - - TableWrapper table = new TableWrapper(1, "ReplaceTestTable"); - table.setColumn(0, "Name", String.class); - table.setRowCount(1); - table.addRow("Annotation"); - image1.addTable(client, table); - image2.addTable(client, table); - - List ids3 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath()); - ImageWrapper image3 = client.getImage(ids3.get(0)); - - assertEquals(2, image3.getTags(client).size()); - assertEquals(2, image3.getTables(client).size()); - assertEquals(3, image3.getFileAnnotations(client).size()); - assertEquals(1, image3.getMapAnnotations(client).size()); - assertEquals(1, image3.getROIs(client).size()); - assertEquals(1, image3.getFolders(client).size()); - assertEquals("ReplaceTestTag1", image3.getTags(client).get(0).getName()); - assertEquals("ReplaceTestTag2", image3.getTags(client).get(1).getName()); - assertEquals("ReplaceTest", image3.getValue(client, "Map")); - assertEquals("ReplaceTestTable", image3.getTables(client).get(0).getName()); - assertEquals("A test.", image3.getDescription()); - - client.delete(image3.getMapAnnotations(client).get(0)); - removeFile(imageFile); - - List images = dataset.getImages(client); - - for (ImageWrapper image : images) { - client.delete(image); - } - List endImages = dataset.getImages(client); - client.delete(dataset); - client.delete(tag1); - client.delete(tag2); - client.delete(table); - client.deleteFile(fileId); - client.delete(roi); - client.delete(folder); - client.delete(image1); - client.delete(image2); - - assertEquals(1, images.size()); - assertTrue(endImages.isEmpty()); - } - - - @Test - public void testReplaceImagesFileset1() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&series=2&sizeX=512&sizeY=512.fake"; - - DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); - client.getProject(PROJECT1.id).addDataset(client, dataset); - - File imageFile = createFile(filename); - - List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); - List images1 = dataset.getImages(client); - - List ids2 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE); - List images2 = dataset.getImages(client); - - removeFile(imageFile); - - assertEquals(2, ids1.size()); - assertEquals(2, ids2.size()); - assertEquals(ids1.size(), images1.size()); - assertEquals(ids2.size(), images2.size()); - assertTrue(client.getImages(ids1.get(0), ids1.get(1)).isEmpty()); - - client.delete(images2); - List endImages = dataset.getImages(client); - client.delete(dataset); - - assertTrue(endImages.isEmpty()); - } - - - @Test - public void testReplaceImagesFileset2() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&series=2&sizeX=512&sizeY=512.fake"; - - DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); - client.getProject(PROJECT1.id).addDataset(client, dataset); - - File imageFile = createFile(filename); - - List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); - assertEquals(2, ids1.size()); - List images1 = dataset.getImages(client); - assertEquals(ids1.size(), images1.size()); - dataset.removeImage(client, images1.get(0)); - List fsImages = images1.get(0).getFilesetImages(client); - assertEquals(images1.size(), fsImages.size()); - assertTrue(ids1.contains(fsImages.get(0).getId())); - assertTrue(ids1.contains(fsImages.get(1).getId())); - - List ids2 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE); - assertEquals(2, ids2.size()); - List images2 = dataset.getImages(client); - assertEquals(ids2.size(), images2.size()); - - removeFile(imageFile); - - List images3 = client.getImages(ids1.get(0), ids1.get(1)); - assertEquals(2, images3.size()); - assertFalse(images2.get(0).isOrphaned(client)); - assertTrue(images3.get(0).isOrphaned(client)); - - client.delete(images1); - client.delete(images2); - List endImages = dataset.getImages(client); - client.delete(dataset); - - assertTrue(endImages.isEmpty()); - } - - - @Test - public void testReplaceImagesFileset3() throws Exception { - String filename = "8bit-unsigned&pixelType=uint8&sizeZ=5&sizeC=5&series=2&sizeX=512&sizeY=512.fake"; - - DatasetWrapper dataset = new DatasetWrapper("Test Import & Replace", ""); - client.getProject(PROJECT1.id).addDataset(client, dataset); - - File imageFile = createFile(filename); - - List ids1 = dataset.importImage(client, imageFile.getAbsolutePath()); - assertEquals(2, ids1.size()); - List images1 = dataset.getImages(client); - assertEquals(ids1.size(), images1.size()); - dataset.removeImage(client, images1.get(0)); - List fsImages = images1.get(0).getFilesetImages(client); - assertEquals(images1.size(), fsImages.size()); - assertTrue(ids1.contains(fsImages.get(0).getId())); - assertTrue(ids1.contains(fsImages.get(1).getId())); - - List ids2 = dataset.importAndReplaceImages(client, imageFile.getAbsolutePath(), DELETE_ORPHANED); - assertEquals(2, ids2.size()); - List images2 = dataset.getImages(client); - assertEquals(ids2.size(), images2.size()); - - removeFile(imageFile); - - assertEquals(2, ids1.size()); - assertEquals(2, ids2.size()); - assertEquals(ids1.size(), images1.size()); - assertEquals(ids2.size(), images2.size()); - assertTrue(client.getImages(ids1.get(0), ids1.get(1)).isEmpty()); - - client.delete(images2); - List endImages = dataset.getImages(client); - client.delete(dataset); - - assertTrue(endImages.isEmpty()); - } - - } diff --git a/src/test/java/fr/igred/omero/repository/PixelsTest.java b/src/test/java/fr/igred/omero/repository/PixelsTest.java new file mode 100644 index 00000000..dc9c86c9 --- /dev/null +++ b/src/test/java/fr/igred/omero/repository/PixelsTest.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2020-2022 GReD + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 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 General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package fr.igred.omero.repository; + + +import fr.igred.omero.UserTest; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + + +class PixelsTest extends UserTest { + + + @Test + void testGetImageSize() throws Exception { + final int sizeXY = 512; + final int sizeC = 5; + final int sizeZ = 3; + final int sizeT = 7; + + ImageWrapper image = client.getImage(IMAGE1.id); + PixelsWrapper pixels = image.getPixels(); + + assertEquals(sizeXY, pixels.getSizeX()); + assertEquals(sizeXY, pixels.getSizeY()); + assertEquals(sizeC, pixels.getSizeC()); + assertEquals(sizeZ, pixels.getSizeZ()); + assertEquals(sizeT, pixels.getSizeT()); + } + + + @Test + void testGetRawData() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + PixelsWrapper pixels = image.getPixels(); + double[][][][][] value = pixels.getAllPixels(client); + + assertEquals(pixels.getSizeX(), value[0][0][0][0].length); + assertEquals(pixels.getSizeY(), value[0][0][0].length); + assertEquals(pixels.getSizeC(), value[0][0].length); + assertEquals(pixels.getSizeZ(), value[0].length); + assertEquals(pixels.getSizeT(), value.length); + } + + + @Test + void testGetRawData2() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + PixelsWrapper pixels = image.getPixels(); + byte[][][][] value = pixels.getRawPixels(client, 1); + + int sizeX = pixels.getSizeX(); + int sizeY = pixels.getSizeY(); + int sizeZ = pixels.getSizeZ(); + int sizeC = pixels.getSizeC(); + int sizeT = pixels.getSizeT(); + + assertEquals(sizeX * sizeY, value[0][0][0].length); + assertEquals(sizeC, value[0][0].length); + assertEquals(sizeZ, value[0].length); + assertEquals(sizeT, value.length); + } + + + @Test + void testGetRawDataBound() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + PixelsWrapper pixels = image.getPixels(); + + int[] xBounds = {0, 2}; + int[] yBounds = {0, 2}; + int[] cBounds = {0, 2}; + int[] zBounds = {0, 2}; + int[] tBounds = {0, 2}; + + double[][][][][] value = pixels.getAllPixels(client, xBounds, yBounds, cBounds, zBounds, tBounds); + + assertEquals(3, value[0][0][0][0].length); + assertEquals(3, value[0][0][0].length); + assertEquals(3, value[0][0].length); + assertEquals(3, value[0].length); + assertEquals(3, value.length); + } + + + @Test + void testGetRawDataBoundError() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + PixelsWrapper pixels = image.getPixels(); + + final int[] xBounds = {511, 513}; + final int[] yBounds = {0, 2}; + final int[] cBounds = {0, 2}; + final int[] zBounds = {0, 2}; + final int[] tBounds = {0, 2}; + + double[][][][][] value = pixels.getAllPixels(client, xBounds, yBounds, cBounds, zBounds, tBounds); + assertNotEquals(xBounds[1] - xBounds[0] + 1, value[0][0][0][0].length); + } + + + @Test + void testGetRawDataBoundErrorNegative() throws Exception { + ImageWrapper image = client.getImage(IMAGE1.id); + PixelsWrapper pixels = image.getPixels(); + + int[] xBounds = {-1, 1}; + int[] yBounds = {0, 2}; + int[] cBounds = {0, 2}; + int[] zBounds = {0, 2}; + int[] tBounds = {0, 2}; + + double[][][][][] value = pixels.getAllPixels(client, xBounds, yBounds, cBounds, zBounds, tBounds); + assertNotEquals(3, value[0][0][0][0].length); + } + + +} diff --git a/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java b/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java index 2f762c0e..bb104761 100644 --- a/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java +++ b/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java @@ -18,18 +18,18 @@ import fr.igred.omero.UserTest; import fr.igred.omero.annotations.TagAnnotationWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class PlateAcquisitionTest extends UserTest { +class PlateAcquisitionTest extends UserTest { @Test - public void testAddTagToPlateAcquisition() throws Exception { + void testAddTagToPlateAcquisition() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); @@ -46,7 +46,7 @@ public void testAddTagToPlateAcquisition() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); @@ -64,7 +64,7 @@ public void testSetName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); @@ -82,7 +82,7 @@ public void testSetDescription() throws Exception { @Test - public void testGetLabel() throws Exception { + void testGetLabel() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); @@ -91,16 +91,19 @@ public void testGetLabel() throws Exception { @Test - public void testGetRefPlateId() throws Exception { + void testGetRefPlateId() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); assertEquals(-1, acq.getRefPlateId()); + acq.setRefPlateId(PLATE1.id); + // Saving does not work: acq.saveAndUpdate(client); + assertEquals(PLATE1.id, acq.getRefPlateId()); } @Test - public void testGetStartTime() throws Exception { + void testGetStartTime() throws Exception { final long time = 1146766431000L; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -111,7 +114,7 @@ public void testGetStartTime() throws Exception { @Test - public void testGetEndTime() throws Exception { + void testGetEndTime() throws Exception { final long time = 1146766431000L; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -122,7 +125,7 @@ public void testGetEndTime() throws Exception { @Test - public void testGetMaximumFieldCount() throws Exception { + void testGetMaximumFieldCount() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); diff --git a/src/test/java/fr/igred/omero/repository/PlateTest.java b/src/test/java/fr/igred/omero/repository/PlateTest.java index 88c9ecd3..c79d5761 100644 --- a/src/test/java/fr/igred/omero/repository/PlateTest.java +++ b/src/test/java/fr/igred/omero/repository/PlateTest.java @@ -18,18 +18,18 @@ import fr.igred.omero.UserTest; import fr.igred.omero.annotations.TagAnnotationWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class PlateTest extends UserTest { +class PlateTest extends UserTest { @Test - public void testGetWellsFromPlate() throws Exception { + void testGetWellsFromPlate() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); List wells = plate.getWells(client); assertEquals(9, wells.size()); @@ -37,7 +37,7 @@ public void testGetWellsFromPlate() throws Exception { @Test - public void testGetWellsFromPlate2() throws Exception { + void testGetWellsFromPlate2() throws Exception { PlateWrapper plate = client.getPlate(PLATE2.id); List wells = plate.getWells(client); assertEquals(4, wells.size()); @@ -45,7 +45,7 @@ public void testGetWellsFromPlate2() throws Exception { @Test - public void testGetPlateAcquisitionsFromPlate() throws Exception { + void testGetPlateAcquisitionsFromPlate() throws Exception { final String name = "PlateAcquisition Name 0"; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -57,7 +57,7 @@ public void testGetPlateAcquisitionsFromPlate() throws Exception { @Test - public void testAddTagToPlate() throws Exception { + void testAddTagToPlate() throws Exception { PlateWrapper plate = client.getPlate(PLATE2.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Plate tag", "tag attached to a plate"); @@ -72,7 +72,7 @@ public void testAddTagToPlate() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); String name = plate.getName(); @@ -88,7 +88,7 @@ public void testSetName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); String description = plate.getDescription(); @@ -105,7 +105,7 @@ public void testSetDescription() throws Exception { @Test - public void testSetStatus() throws Exception { + void testSetStatus() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); String status = plate.getStatus(); @@ -122,7 +122,7 @@ public void testSetStatus() throws Exception { @Test - public void testGetDefaultSample() throws Exception { + void testGetDefaultSample() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); int sample = plate.getDefaultSample(); @@ -139,7 +139,7 @@ public void testGetDefaultSample() throws Exception { @Test - public void testSetExternalIdentifier() throws Exception { + void testSetExternalIdentifier() throws Exception { final String identifier = "External Identifier Test"; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -150,7 +150,7 @@ public void testSetExternalIdentifier() throws Exception { @Test - public void testGetPlateType() throws Exception { + void testGetPlateType() throws Exception { final String type = "9-Well Plate"; PlateWrapper plate = client.getPlate(PLATE1.id); assertEquals(type, plate.getPlateType()); @@ -158,7 +158,7 @@ public void testGetPlateType() throws Exception { @Test - public void testGetColumnSequenceIndex() throws Exception { + void testGetColumnSequenceIndex() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); int column = 0; assertEquals(column, plate.getColumnSequenceIndex()); @@ -166,7 +166,7 @@ public void testGetColumnSequenceIndex() throws Exception { @Test - public void testGetRowSequenceIndex() throws Exception { + void testGetRowSequenceIndex() throws Exception { final int column = 1; PlateWrapper plate = client.getPlate(PLATE1.id); assertEquals(column, plate.getRowSequenceIndex()); @@ -174,7 +174,7 @@ public void testGetRowSequenceIndex() throws Exception { @Test - public void testGetWellOriginX() throws Exception { + void testGetWellOriginX() throws Exception { final double origin = 0.0d; PlateWrapper plate = client.getPlate(PLATE1.id); assertEquals(origin, plate.getWellOriginX(null).getValue(), Double.MIN_VALUE); @@ -182,7 +182,7 @@ public void testGetWellOriginX() throws Exception { @Test - public void testGetWellOriginY() throws Exception { + void testGetWellOriginY() throws Exception { final double origin = 1.0d; PlateWrapper plate = client.getPlate(PLATE1.id); assertEquals(origin, plate.getWellOriginY(null).getValue(), Double.MIN_VALUE); diff --git a/src/test/java/fr/igred/omero/repository/ProjectTest.java b/src/test/java/fr/igred/omero/repository/ProjectTest.java index 52911c05..5e420d2b 100644 --- a/src/test/java/fr/igred/omero/repository/ProjectTest.java +++ b/src/test/java/fr/igred/omero/repository/ProjectTest.java @@ -21,22 +21,22 @@ import fr.igred.omero.annotations.MapAnnotationWrapper; import fr.igred.omero.annotations.TableWrapper; import fr.igred.omero.annotations.TagAnnotationWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE; import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE_ORPHANED; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; -public class ProjectTest extends UserTest { +class ProjectTest extends UserTest { @Test - public void testGetDatasetFromProject() throws Exception { + void testGetDatasetFromProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List datasets = project.getDatasets(); @@ -46,7 +46,7 @@ public void testGetDatasetFromProject() throws Exception { @Test - public void testGetDatasetFromProject2() throws Exception { + void testGetDatasetFromProject2() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List datasets = project.getDatasets(DATASET1.name); @@ -56,7 +56,7 @@ public void testGetDatasetFromProject2() throws Exception { @Test - public void testAddAndRemoveDataset() throws Exception { + void testAddAndRemoveDataset() throws Exception { ProjectWrapper project = new ProjectWrapper(client, "To delete", ""); DatasetWrapper dataset = client.getDataset(DATASET2.id); @@ -77,7 +77,7 @@ public void testAddAndRemoveDataset() throws Exception { @Test - public void testAddTagToProject() throws Exception { + void testAddTagToProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); @@ -93,7 +93,7 @@ public void testAddTagToProject() throws Exception { @Test - public void testAddTagToProject2() throws Exception { + void testAddTagToProject2() throws Exception { final String name = "test"; final String description = "test"; @@ -110,7 +110,7 @@ public void testAddTagToProject2() throws Exception { @Test - public void testAddTagIdToProject() throws Exception { + void testAddTagIdToProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); @@ -126,7 +126,7 @@ public void testAddTagIdToProject() throws Exception { @Test - public void testAddTagsToProject() throws Exception { + void testAddTagsToProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Project tag 1", "tag attached to a project"); @@ -148,7 +148,7 @@ public void testAddTagsToProject() throws Exception { @Test - public void testAddTagsToProject2() throws Exception { + void testAddTagsToProject2() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); @@ -170,7 +170,7 @@ public void testAddTagsToProject2() throws Exception { @Test - public void testAddAndRemoveTagFromProject() throws Exception { + void testAddAndRemoveTagFromProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); @@ -186,7 +186,7 @@ public void testAddAndRemoveTagFromProject() throws Exception { @Test - public void testGetImagesInProject() throws Exception { + void testGetImagesInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List images = project.getImages(client); @@ -196,7 +196,7 @@ public void testGetImagesInProject() throws Exception { @Test - public void testGetImagesByNameInProject() throws Exception { + void testGetImagesByNameInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List images = project.getImages(client, "image1.fake"); @@ -206,7 +206,7 @@ public void testGetImagesByNameInProject() throws Exception { @Test - public void testGetImagesLikeInProject() throws Exception { + void testGetImagesLikeInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List images = project.getImagesLike(client, ".fake"); @@ -216,7 +216,7 @@ public void testGetImagesLikeInProject() throws Exception { @Test - public void testGetImagesTaggedInProject() throws Exception { + void testGetImagesTaggedInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List images = project.getImagesTagged(client, TAG1.id); @@ -226,7 +226,7 @@ public void testGetImagesTaggedInProject() throws Exception { @Test - public void testGetImagesTaggedInProject2() throws Exception { + void testGetImagesTaggedInProject2() throws Exception { TagAnnotationWrapper tag = client.getTag(TAG2.id); ProjectWrapper project = client.getProject(PROJECT1.id); @@ -237,7 +237,7 @@ public void testGetImagesTaggedInProject2() throws Exception { @Test - public void testGetImagesKeyInProject() throws Exception { + void testGetImagesKeyInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List images = project.getImagesKey(client, "testKey1"); @@ -247,7 +247,7 @@ public void testGetImagesKeyInProject() throws Exception { @Test - public void testGetImagesPairKeyValueInProject() throws Exception { + void testGetImagesPairKeyValueInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); List images = project.getImagesPairKeyValue(client, "testKey1", "testValue1"); @@ -257,7 +257,7 @@ public void testGetImagesPairKeyValueInProject() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); String name = project.getName(); @@ -273,7 +273,7 @@ public void testSetName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); String description = project.getDescription(); @@ -290,7 +290,7 @@ public void testSetDescription() throws Exception { @Test - public void testCopyAnnotations() throws Exception { + void testCopyAnnotations() throws Exception { ProjectWrapper project1 = client.getProject(PROJECT1.id); ProjectWrapper project2 = new ProjectWrapper(client, "CopyTest", "Copy annotations"); @@ -335,7 +335,7 @@ public void testCopyAnnotations() throws Exception { @Test - public void testCopyFileAnnotation() throws Exception { + void testCopyFileAnnotation() throws Exception { ProjectWrapper project1 = client.getProject(PROJECT1.id); ProjectWrapper project2 = new ProjectWrapper(client, "CopyTest", "Copy file annotation"); @@ -361,7 +361,7 @@ public void testCopyFileAnnotation() throws Exception { @Test - public void testReplaceAndUnlinkFile() throws Exception { + void testReplaceAndUnlinkFile() throws Exception { ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); ProjectWrapper project2 = new ProjectWrapper(client, "ReplaceTest2", "Replace file annotation"); @@ -384,7 +384,7 @@ public void testReplaceAndUnlinkFile() throws Exception { @Test - public void testReplaceAndDeleteFile() throws Exception { + void testReplaceAndDeleteFile() throws Exception { ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); ProjectWrapper project2 = new ProjectWrapper(client, "ReplaceTest2", "Replace file annotation"); @@ -406,7 +406,7 @@ public void testReplaceAndDeleteFile() throws Exception { @Test - public void testReplaceAndDeleteOrphanedFile1() throws Exception { + void testReplaceAndDeleteOrphanedFile1() throws Exception { ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); ProjectWrapper project2 = new ProjectWrapper(client, "ReplaceTest2", "Replace file annotation"); @@ -429,7 +429,7 @@ public void testReplaceAndDeleteOrphanedFile1() throws Exception { @Test - public void testReplaceAndDeleteOrphanedFile2() throws Exception { + void testReplaceAndDeleteOrphanedFile2() throws Exception { ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); File file = createRandomFile("test_project.txt"); diff --git a/src/test/java/fr/igred/omero/repository/ScreenTest.java b/src/test/java/fr/igred/omero/repository/ScreenTest.java index 4b44df41..b8fff396 100644 --- a/src/test/java/fr/igred/omero/repository/ScreenTest.java +++ b/src/test/java/fr/igred/omero/repository/ScreenTest.java @@ -18,18 +18,21 @@ import fr.igred.omero.UserTest; import fr.igred.omero.annotations.TagAnnotationWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import java.io.File; import java.util.List; +import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class ScreenTest extends UserTest { +class ScreenTest extends UserTest { @Test - public void testGetPlatesFromScreen() throws Exception { + void testGetPlatesFromScreen() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN2.id); List plates = screen.getPlates(); assertEquals(2, plates.size()); @@ -37,7 +40,7 @@ public void testGetPlatesFromScreen() throws Exception { @Test - public void testGetPlatesFromScreen2() throws Exception { + void testGetPlatesFromScreen2() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN2.id); List plates = screen.getPlates("Plate Name 1"); assertEquals(1, plates.size()); @@ -45,7 +48,7 @@ public void testGetPlatesFromScreen2() throws Exception { @Test - public void testAddTagToScreen() throws Exception { + void testAddTagToScreen() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN2.id); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Screen tag", "tag attached to a screen"); @@ -60,7 +63,7 @@ public void testAddTagToScreen() throws Exception { @Test - public void testSetName() throws Exception { + void testSetName() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); String name = screen.getName(); @@ -76,7 +79,7 @@ public void testSetName() throws Exception { @Test - public void testSetDescription() throws Exception { + void testSetDescription() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); String description = screen.getDescription(); @@ -93,7 +96,7 @@ public void testSetDescription() throws Exception { @Test - public void testSetProtocolDescription() throws Exception { + void testSetProtocolDescription() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); String description = "Protocol Description Test"; @@ -104,7 +107,7 @@ public void testSetProtocolDescription() throws Exception { @Test - public void testSetProtocolIdentifier() throws Exception { + void testSetProtocolIdentifier() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); String identifier = "Protocol Identifier Test"; @@ -115,7 +118,7 @@ public void testSetProtocolIdentifier() throws Exception { @Test - public void testSetReagentSetDescription() throws Exception { + void testSetReagentSetDescription() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); String description = "Reagent Description Test"; @@ -126,7 +129,7 @@ public void testSetReagentSetDescription() throws Exception { @Test - public void testSetReagentSetIdentifier() throws Exception { + void testSetReagentSetIdentifier() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); String identifier = "Reagent Identifier Test"; @@ -135,4 +138,88 @@ public void testSetReagentSetIdentifier() throws Exception { assertEquals(identifier, client.getScreen(SCREEN1.id).getReagentSetIdentifier()); } + + @Test + void testImportImages() throws Exception { + + String filename1 = "default-screen&screens=1&plates=1&plateAcqs=1&plateRows=3&plateCols=3&fields=4.fake"; + String filename2 = "default-screen&screens=1&plates=1&plateAcqs=1&plateRows=2&plateCols=2&fields=2.fake"; + + File f1 = createFile(filename1); + File f2 = createFile(filename2); + + ScreenWrapper screen = new ScreenWrapper(client, "Import", "test-import"); + + boolean imported = screen.importImages(client, f1.getAbsolutePath(), f2.getAbsolutePath()); + + removeFile(f1); + removeFile(f2); + + List plates = screen.getPlates(); + assertEquals(2, plates.size()); + List wells = plates.get(0).getWells(client); + wells.addAll(plates.get(1).getWells(client)); + assertEquals(13, wells.size()); + List samples = wells.stream() + .map(WellWrapper::getWellSamples) + .flatMap(List::stream) + .collect(Collectors.toList()); + assertEquals(44, samples.size()); + List images = samples.stream() + .map(WellSampleWrapper::getImage) + .collect(Collectors.toList()); + + client.delete(images); + client.delete(samples); + client.delete(wells); + client.delete(plates); + + screen.refresh(client); + assertTrue(screen.getPlates().isEmpty()); + + client.delete(screen); + assertTrue(imported); + } + + + @Test + void testImportImage() throws Exception { + + String filename = "default-screen&screens=1&plates=1&plateAcqs=1&plateRows=2&plateCols=2&fields=2.fake"; + + File f = createFile(filename); + + ScreenWrapper screen = new ScreenWrapper(client, "Import", "test-import"); + + List ids = screen.importImage(client, f.getAbsolutePath()); + + removeFile(f); + + List plates = screen.getPlates(); + assertEquals(1, plates.size()); + List wells = plates.get(0).getWells(client); + assertEquals(4, wells.size()); + List samples = wells.stream() + .map(WellWrapper::getWellSamples) + .flatMap(List::stream) + .collect(Collectors.toList()); + assertEquals(8, samples.size()); + List images = samples.stream() + .map(WellSampleWrapper::getImage) + .collect(Collectors.toList()); + + assertEquals(images.size(), ids.size()); + client.delete(images); + client.delete(samples); + client.delete(wells); + client.delete(plates); + + screen.refresh(client); + List endPlates = screen.getPlates(); + + client.delete(screen); + + assertTrue(endPlates.isEmpty()); + } + } diff --git a/src/test/java/fr/igred/omero/repository/WellSampleTest.java b/src/test/java/fr/igred/omero/repository/WellSampleTest.java index 276c3bec..09473dc7 100644 --- a/src/test/java/fr/igred/omero/repository/WellSampleTest.java +++ b/src/test/java/fr/igred/omero/repository/WellSampleTest.java @@ -17,17 +17,17 @@ import fr.igred.omero.UserTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -public class WellSampleTest extends UserTest { +class WellSampleTest extends UserTest { @Test - public void testGetImage() throws Exception { + void testGetImage() throws Exception { final String name = "screen1.fake [screen1 2]"; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -43,7 +43,17 @@ public void testGetImage() throws Exception { @Test - public void testGetPositionX() throws Exception { + void testGetWell() throws Exception { + final long wellId = 1L; + WellWrapper well = client.getWell(wellId); + WellSampleWrapper sample = well.getWellSamples().get(0); + + assertEquals(wellId, sample.getWell(client).getId()); + } + + + @Test + void testGetPositionX() throws Exception { WellWrapper well = client.getWells(1L).get(0); WellSampleWrapper sample = well.getWellSamples().get(0); @@ -52,7 +62,7 @@ public void testGetPositionX() throws Exception { @Test - public void testGetPositionY() throws Exception { + void testGetPositionY() throws Exception { WellWrapper well = client.getWells(1L).get(0); WellSampleWrapper sample = well.getWellSamples().get(0); @@ -61,7 +71,7 @@ public void testGetPositionY() throws Exception { @Test - public void testGetStartTime() throws Exception { + void testGetStartTime() throws Exception { final long time = 1146766431000L; WellWrapper well = client.getWells(1L).get(0); diff --git a/src/test/java/fr/igred/omero/repository/WellTest.java b/src/test/java/fr/igred/omero/repository/WellTest.java index d16ae7b1..72caf4f5 100644 --- a/src/test/java/fr/igred/omero/repository/WellTest.java +++ b/src/test/java/fr/igred/omero/repository/WellTest.java @@ -18,18 +18,18 @@ import fr.igred.omero.UserTest; import fr.igred.omero.annotations.TagAnnotationWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class WellTest extends UserTest { +class WellTest extends UserTest { @Test - public void testAddTagToWell() throws Exception { + void testAddTagToWell() throws Exception { WellWrapper well = client.getWell(2L); TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Well tag", "tag attached to a well"); @@ -44,7 +44,7 @@ public void testAddTagToWell() throws Exception { @Test - public void testGetWellSamples() throws Exception { + void testGetWellSamples() throws Exception { WellWrapper well = client.getWell(1L); List samples = well.getWellSamples(); assertEquals(4, samples.size()); @@ -52,7 +52,7 @@ public void testGetWellSamples() throws Exception { @Test - public void testTestGetName() throws Exception { + void testTestGetName() throws Exception { final String name = "Well A-1"; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -63,7 +63,7 @@ public void testTestGetName() throws Exception { @Test - public void testGetDescription() throws Exception { + void testGetDescription() throws Exception { final String description = "External Description"; PlateWrapper plate = client.getPlate(PLATE1.id); @@ -74,7 +74,7 @@ public void testGetDescription() throws Exception { @Test - public void testGetColumn() throws Exception { + void testGetColumn() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); WellWrapper well = plate.getWells(client).get(1); assertEquals(1, well.getColumn().intValue()); @@ -82,7 +82,7 @@ public void testGetColumn() throws Exception { @Test - public void testGetRow() throws Exception { + void testGetRow() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); WellWrapper well = plate.getWells(client).get(6); assertEquals(2, well.getRow().intValue()); @@ -90,7 +90,7 @@ public void testGetRow() throws Exception { @Test - public void testSetStatus() throws Exception { + void testSetStatus() throws Exception { WellWrapper well = client.getWell(1L); String status = well.getStatus(); @@ -107,7 +107,7 @@ public void testSetStatus() throws Exception { @Test - public void testSetWellType() throws Exception { + void testSetWellType() throws Exception { WellWrapper well = client.getWell(1L); String type = well.getWellType(); @@ -124,7 +124,7 @@ public void testSetWellType() throws Exception { @Test - public void testSetRed() throws Exception { + void testSetRed() throws Exception { WellWrapper well = client.getWell(1L); int red = well.getRed(); @@ -141,7 +141,7 @@ public void testSetRed() throws Exception { @Test - public void testSetGreen() throws Exception { + void testSetGreen() throws Exception { WellWrapper well = client.getWell(1L); int green = well.getGreen(); @@ -158,7 +158,7 @@ public void testSetGreen() throws Exception { @Test - public void testSetBlue() throws Exception { + void testSetBlue() throws Exception { WellWrapper well = client.getWell(1L); int blue = well.getBlue(); @@ -175,7 +175,7 @@ public void testSetBlue() throws Exception { @Test - public void testSetAlpha() throws Exception { + void testSetAlpha() throws Exception { WellWrapper well = client.getWell(1L); int alpha = well.getAlpha(); diff --git a/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java b/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java index 23309bb7..b40a131c 100644 --- a/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java +++ b/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java @@ -26,7 +26,7 @@ import ij.gui.Roi; import ij.gui.ShapeRoi; import ij.gui.TextRoi; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; @@ -37,15 +37,15 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ROI2ImageJTest extends BasicTest { +class ROI2ImageJTest extends BasicTest { @Test - public void testROIsFromImageJ() { - final List rois = new ArrayList<>(11); + void testROIsFromImageJ() { + List rois = new ArrayList<>(11); final float[] x1 = {0.0f, 3.0f, 3.0f}; final float[] y1 = {0.0f, 0.0f, 4.0f}; @@ -108,7 +108,7 @@ public void testROIsFromImageJ() { @Test - public void testROItoImageJ() { + void testROItoImageJ() { final int nRois = 11; AffineTransform transform = new AffineTransform(); @@ -190,7 +190,7 @@ public void testROItoImageJ() { @Test - public void convertEllipse() { + void convertEllipse() { EllipseWrapper ellipse = new EllipseWrapper(3, 4, 10, 8); ellipse.setCZT(0, 0, 2); @@ -215,7 +215,7 @@ public void convertEllipse() { @Test - public void convertRectangle() { + void convertRectangle() { RectangleWrapper rectangle = new RectangleWrapper(3, 3, 10, 10); rectangle.setCZT(0, 0, 2); @@ -239,7 +239,7 @@ public void convertRectangle() { @Test - public void convertArrow() { + void convertArrow() { LineWrapper arrow = new LineWrapper(3, 3, 10, 10); arrow.setCZT(0, 0, 2); arrow.asShapeData().getShapeSettings().setMarkerStart(LineWrapper.ARROW); @@ -269,7 +269,7 @@ public void convertArrow() { @Test - public void convertLine() { + void convertLine() { final LineWrapper line = new LineWrapper(3, 3, 10, 10); line.setCZT(0, 0, 2); @@ -296,7 +296,7 @@ public void convertLine() { @Test - public void convertMask() { + void convertMask() { MaskWrapper mask = new MaskWrapper(); mask.setCoordinates(3, 3, 10, 10); mask.setCZT(0, 0, 2); @@ -321,7 +321,7 @@ public void convertMask() { @Test - public void convertPoint() { + void convertPoint() { PointWrapper point = new PointWrapper(); point.setCoordinates(3, 3); point.setCZT(0, 0, 2); @@ -345,7 +345,7 @@ public void convertPoint() { @Test - public void convertText() { + void convertText() { //noinspection HardcodedLineSeparator final Pattern c = Pattern.compile("\r", Pattern.LITERAL); // Oddly, IJ adds \r @@ -375,7 +375,7 @@ public void convertText() { @Test - public void convertPolygon() { + void convertPolygon() { List points2D = new ArrayList<>(3); Point2D.Double p1 = new Point2D.Double(0, 0); @@ -405,7 +405,7 @@ public void convertPolygon() { @Test - public void convertPolyline() { + void convertPolyline() { List points2D = new ArrayList<>(3); Point2D.Double p1 = new Point2D.Double(0, 0); @@ -419,7 +419,8 @@ public void convertPolyline() { polyline.setCZT(0, 0, 2); Roi ijPolyline = polyline.toImageJ(); - assertEquals(polyline.toAWTShape().getBounds(), ijPolyline.getBounds()); + // Compare to getFloatPolygon().getBounds() because polyline bounds are different for ij 1.53h+ + assertEquals(polyline.toAWTShape().getBounds(), ijPolyline.getFloatPolygon().getBounds()); List roiList = new ArrayList<>(1); roiList.add(ijPolyline); diff --git a/src/test/java/fr/igred/omero/roi/ROITest.java b/src/test/java/fr/igred/omero/roi/ROITest.java index f7ebb3d8..a6bf7164 100644 --- a/src/test/java/fr/igred/omero/roi/ROITest.java +++ b/src/test/java/fr/igred/omero/roi/ROITest.java @@ -18,20 +18,20 @@ import fr.igred.omero.UserTest; import fr.igred.omero.repository.ImageWrapper; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ROITest extends UserTest { +class ROITest extends UserTest { @Test - public void testROI() throws Exception { + void testROI() throws Exception { ROIWrapper roiWrapper = new ROIWrapper(); ImageWrapper image = client.getImage(IMAGE1.id); @@ -64,7 +64,7 @@ public void testROI() throws Exception { @Test - public void testROI2() throws Exception { + void testROI2() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List> shapes = new ArrayList<>(4); @@ -97,7 +97,7 @@ public void testROI2() throws Exception { @Test - public void testRoiAddShapeAndDeleteIt() throws Exception { + void testRoiAddShapeAndDeleteIt() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); List> shapes = new ArrayList<>(4); @@ -154,7 +154,7 @@ public void testRoiAddShapeAndDeleteIt() throws Exception { @Test - public void testROIAllShapes() throws Exception { + void testROIAllShapes() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); PointWrapper point = new PointWrapper(1, 1); diff --git a/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java b/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java index fdf2da12..91899886 100644 --- a/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java +++ b/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java @@ -18,99 +18,101 @@ package fr.igred.omero.roi; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertThrows; -public class ShapeErrorTest { +class ShapeErrorTest { - @Test(expected = IllegalArgumentException.class) - public void testPointNullCoordinates() { + + @Test + void testPointNullCoordinates() { PointWrapper point = new PointWrapper(); - point.setCoordinates(null); + assertThrows(IllegalArgumentException.class, () -> point.setCoordinates(null)); } - @Test(expected = IllegalArgumentException.class) - public void testTextNullCoordinates() { + @Test + void testTextNullCoordinates() { TextWrapper text = new TextWrapper(); - text.setCoordinates(null); + assertThrows(IllegalArgumentException.class, () -> text.setCoordinates(null)); } - @Test(expected = IllegalArgumentException.class) - public void testRectangleNullCoordinates() { + @Test + void testRectangleNullCoordinates() { RectangleWrapper rectangle = new RectangleWrapper(); - rectangle.setCoordinates(null); + assertThrows(IllegalArgumentException.class, () -> rectangle.setCoordinates(null)); } - @Test(expected = IllegalArgumentException.class) - public void testMaskNullCoordinates() { + @Test + void testMaskNullCoordinates() { MaskWrapper mask = new MaskWrapper(); - mask.setCoordinates(null); + assertThrows(IllegalArgumentException.class, () -> mask.setCoordinates(null)); } - @Test(expected = IllegalArgumentException.class) - public void testEllipseNullCoordinates() { + @Test + void testEllipseNullCoordinates() { EllipseWrapper ellipse = new EllipseWrapper(); - ellipse.setCoordinates(null); + assertThrows(IllegalArgumentException.class, () -> ellipse.setCoordinates(null)); } - @Test(expected = IllegalArgumentException.class) - public void testLineNullCoordinates() { + @Test + void testLineNullCoordinates() { LineWrapper line = new LineWrapper(); - line.setCoordinates(null); + assertThrows(IllegalArgumentException.class, () -> line.setCoordinates(null)); } - @Test(expected = IllegalArgumentException.class) - public void testPointWrongCoordinates() { + @Test + void testPointWrongCoordinates() { PointWrapper point = new PointWrapper(); double[] coordinates = {2, 2, 4, 4}; - point.setCoordinates(coordinates); + assertThrows(IllegalArgumentException.class, () -> point.setCoordinates(coordinates)); } - @Test(expected = IllegalArgumentException.class) - public void testTextWrongCoordinates() { + @Test + void testTextWrongCoordinates() { TextWrapper text = new TextWrapper(); double[] coordinates = {2, 2, 4, 4}; - text.setCoordinates(coordinates); + assertThrows(IllegalArgumentException.class, () -> text.setCoordinates(coordinates)); } - @Test(expected = IllegalArgumentException.class) - public void testRectangleWrongCoordinates() { + @Test + void testRectangleWrongCoordinates() { RectangleWrapper rectangle = new RectangleWrapper(); double[] coordinates = {2, 2}; - rectangle.setCoordinates(coordinates); + assertThrows(IllegalArgumentException.class, () -> rectangle.setCoordinates(coordinates)); } - @Test(expected = IllegalArgumentException.class) - public void testMaskWrongCoordinates() { + @Test + void testMaskWrongCoordinates() { MaskWrapper mask = new MaskWrapper(); double[] coordinates = {2, 2}; - mask.setCoordinates(coordinates); + assertThrows(IllegalArgumentException.class, () -> mask.setCoordinates(coordinates)); } - @Test(expected = IllegalArgumentException.class) - public void testEllipseWrongCoordinates() { + @Test + void testEllipseWrongCoordinates() { EllipseWrapper ellipse = new EllipseWrapper(); double[] coordinates = {2, 2}; - ellipse.setCoordinates(coordinates); + assertThrows(IllegalArgumentException.class, () -> ellipse.setCoordinates(coordinates)); } - @Test(expected = IllegalArgumentException.class) - public void testLineWrongCoordinates() { + @Test + void testLineWrongCoordinates() { LineWrapper line = new LineWrapper(); double[] coordinates = {2, 2}; - line.setCoordinates(coordinates); + assertThrows(IllegalArgumentException.class, () -> line.setCoordinates(coordinates)); } } diff --git a/src/test/java/fr/igred/omero/roi/ShapeTest.java b/src/test/java/fr/igred/omero/roi/ShapeTest.java index 85335f0f..8adf8451 100644 --- a/src/test/java/fr/igred/omero/roi/ShapeTest.java +++ b/src/test/java/fr/igred/omero/roi/ShapeTest.java @@ -23,7 +23,7 @@ import omero.gateway.model.PointData; import omero.gateway.model.RectangleData; import omero.gateway.model.TextData; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.awt.Color; import java.awt.geom.AffineTransform; @@ -36,14 +36,14 @@ import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -public class ShapeTest extends BasicTest { +class ShapeTest extends BasicTest { @Test - public void testPoint() { + void testPoint() { final String text = "Point"; PointWrapper point = new PointWrapper(); @@ -64,7 +64,7 @@ public void testPoint() { @Test - public void testText() { + void testText() { final String value = "Point"; final int font = 25; @@ -90,7 +90,7 @@ public void testText() { @Test - public void testRectangle() { + void testRectangle() { RectangleWrapper rectangle = new RectangleWrapper(); double[] rectangleCoordinates = {2, 2, 5, 5}; @@ -107,7 +107,7 @@ public void testRectangle() { @Test - public void testRectangleCZT() { + void testRectangleCZT() { final String text = "Rectangle"; RectangleWrapper rectangle = new RectangleWrapper(); @@ -139,7 +139,7 @@ public void testRectangleCZT() { @Test - public void testMask() { + void testMask() { MaskWrapper mask = new MaskWrapper(); double[] maskCoordinates = {3, 3, 10, 10}; @@ -156,7 +156,7 @@ public void testMask() { @Test - public void testValuesMask() { + void testValuesMask() { final String text = "Mask"; MaskWrapper mask = new MaskWrapper(); mask.setCoordinates(3, 3, 10, 10); @@ -185,7 +185,7 @@ public void testValuesMask() { @Test - public void testEllipse() { + void testEllipse() { final String text = "Ellipse"; EllipseWrapper ellipse = new EllipseWrapper(); @@ -212,7 +212,7 @@ public void testEllipse() { @Test - public void testLine() { + void testLine() { final String text = "Line"; LineWrapper line = new LineWrapper(); @@ -235,7 +235,7 @@ public void testLine() { @Test - public void testPointsLine() { + void testPointsLine() { LineWrapper line = new LineWrapper(); double[] lineCoordinates = {3, 3, 10, 10}; @@ -255,7 +255,7 @@ public void testPointsLine() { @Test - public void testPolyline() { + void testPolyline() { final String text = "Polyline"; PolylineWrapper polyline = new PolylineWrapper(); List points = new ArrayList<>(3); @@ -277,7 +277,7 @@ public void testPolyline() { @Test - public void testPolygon() { + void testPolygon() { final String text = "Polygon"; PolygonWrapper polygon = new PolygonWrapper(); List points = new ArrayList<>(3); @@ -300,7 +300,7 @@ public void testPolygon() { @Test - public void testPointConstructor() { + void testPointConstructor() { final PointWrapper point1 = new PointWrapper(0, 0); final PointWrapper point2 = new PointWrapper(new PointData(25, 25)); @@ -319,7 +319,7 @@ public void testPointConstructor() { @Test - public void testTextConstructor() { + void testTextConstructor() { final TextWrapper text1 = new TextWrapper("Text1", 0, 0); final TextWrapper text2 = new TextWrapper(new TextData("Text1", 25, 25)); @@ -339,7 +339,7 @@ public void testTextConstructor() { @Test - public void testLineConstructor() { + void testLineConstructor() { final LineWrapper line1 = new LineWrapper(0, 0, 0, 0); final LineWrapper line2 = new LineWrapper(new LineData(25, 25, 50, 50)); @@ -358,7 +358,7 @@ public void testLineConstructor() { @Test - public void testRectangleConstructor() { + void testRectangleConstructor() { final RectangleWrapper r1 = new RectangleWrapper(0, 0, 0, 0); final RectangleWrapper r2 = new RectangleWrapper(new RectangleData(25, 25, 50, 50)); @@ -377,7 +377,7 @@ public void testRectangleConstructor() { @Test - public void testMaskConstructor() { + void testMaskConstructor() { final byte[] maskValues = new byte[25]; for (int i = 0; i < maskValues.length; i++) { maskValues[i] = (byte) (i >= maskValues.length/2 ? 1 : 0); @@ -395,7 +395,7 @@ public void testMaskConstructor() { int differences = 0; for (int i = 0; i < 4; i++) - differences = (int) (differences + Math.abs(coordinates1[i] - coordinates2[i])); + differences += (int) Math.abs(coordinates1[i] - coordinates2[i]); for (int i = 0; i < maskValues.length; i++) differences += Math.abs(checkValues2[i] - checkValues1[i]); @@ -404,7 +404,7 @@ public void testMaskConstructor() { @Test - public void testEllipseConstructor() { + void testEllipseConstructor() { final EllipseWrapper e1 = new EllipseWrapper(0, 0, 0, 0); final EllipseWrapper e2 = new EllipseWrapper(new EllipseData(25, 25, 50, 50)); @@ -423,7 +423,7 @@ public void testEllipseConstructor() { @Test - public void testPolylineConstructor() { + void testPolylineConstructor() { List points = new ArrayList<>(3); Point2D.Double p1 = new Point2D.Double(0, 0); @@ -441,7 +441,7 @@ public void testPolylineConstructor() { @Test - public void testPolygonConstructor() { + void testPolygonConstructor() { List points = new ArrayList<>(3); Point2D.Double p1 = new Point2D.Double(0, 0); @@ -459,7 +459,7 @@ public void testPolygonConstructor() { @Test - public void testAWTRectangle() { + void testAWTRectangle() { final RectangleWrapper shape = new RectangleWrapper(25, 26, 27, 28); final Rectangle2D awtShape = new Rectangle2D.Double(25, 26, 27, 28); java.awt.Shape awtShape2 = shape.toAWTShape(); @@ -468,7 +468,7 @@ public void testAWTRectangle() { @Test - public void testAWTMask() { + void testAWTMask() { final byte[] maskValues = new byte[25]; for (int i = 0; i < maskValues.length; i++) { maskValues[i] = (byte) (i >= maskValues.length/2 ? 1 : 0); @@ -482,7 +482,7 @@ public void testAWTMask() { @Test - public void testAWTEllipse() { + void testAWTEllipse() { final EllipseWrapper shape = new EllipseWrapper(28, 27, 26, 25); final Ellipse2D awtShape = new Ellipse2D.Double(2, 2, 52, 50); java.awt.Shape awtShape2 = shape.toAWTShape(); @@ -491,7 +491,7 @@ public void testAWTEllipse() { @Test - public void testAWTLine() { + void testAWTLine() { LineWrapper shape = new LineWrapper(0, 1, 2, 3); Line2D awtShape = new Line2D.Double(0, 1, 2, 3); Line2D awtShape2 = (Line2D) shape.toAWTShape(); @@ -501,7 +501,7 @@ public void testAWTLine() { @Test - public void testAWTPolygon() { + void testAWTPolygon() { List points = new ArrayList<>(3); Point2D.Double p1 = new Point2D.Double(0, 0); @@ -537,7 +537,7 @@ public void testAWTPolygon() { @Test - public void testAWTPolyline() { + void testAWTPolyline() { List points = new ArrayList<>(3); Point2D.Double p1 = new Point2D.Double(0, 0); @@ -573,7 +573,7 @@ public void testAWTPolyline() { @Test - public void testAWTPoint() { + void testAWTPoint() { PointWrapper shape = new PointWrapper(1, 2); Path2D awtShape = new Path2D.Double(); @@ -597,7 +597,7 @@ public void testAWTPoint() { @Test - public void testAWTText() { + void testAWTText() { TextWrapper shape = new TextWrapper("Text", 1, 2); Path2D awtShape = new Path2D.Double(); @@ -621,7 +621,7 @@ public void testAWTText() { @Test - public void testAffineTransform() { + void testAffineTransform() { RectangleWrapper shape = new RectangleWrapper(1, 2, 3, 4); shape.setTransform(1, 2, 3, 4, 5, 6); @@ -631,7 +631,7 @@ public void testAffineTransform() { @Test - public void testNoAffineTransform() { + void testNoAffineTransform() { RectangleWrapper shape = new RectangleWrapper(1, 2, 3, 4); java.awt.Shape awtShape = new Rectangle2D.Double(1, 2, 3, 4); @@ -640,7 +640,7 @@ public void testNoAffineTransform() { @Test - public void testBoundingBox() { + void testBoundingBox() { RectangleWrapper shape = new RectangleWrapper(1, 2, 3, 4); RectangleWrapper box = new RectangleWrapper(-6, 1, 4, 3); @@ -660,7 +660,7 @@ public void testBoundingBox() { @Test - public void testBoundingBox2() { + void testBoundingBox2() { final EllipseWrapper shape = new EllipseWrapper(50, 50, 20, 40); final RectangleWrapper box = new RectangleWrapper(30, 10, 40, 80); diff --git a/src/test/java/fr/igred/omero/util/LibraryCheckerTest.java b/src/test/java/fr/igred/omero/util/LibraryCheckerTest.java new file mode 100644 index 00000000..36ba5a91 --- /dev/null +++ b/src/test/java/fr/igred/omero/util/LibraryCheckerTest.java @@ -0,0 +1,88 @@ +/* + * Copyright (C) 2020-2022 GReD + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 2 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 General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +package fr.igred.omero.util; + + +import fr.igred.omero.BasicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + + +class LibraryCheckerTest extends BasicTest { + + @Test + void checkAvailableLibraries() { + assertTrue(LibraryChecker.areRequirementsAvailable(), "Libraries are unavailable"); + } + + + @ParameterizedTest + @ValueSource(strings = {"omero-gateway", + "omero-model", + "omero-blitz", + "ome-common", + "formats-api"}) + void checkUnavailableLibraries(String excluded) { + //noinspection ClassLoaderInstantiation + try (URLClassLoader testClassLoader = new TestClassLoader(excluded)) { + Class checker = testClassLoader.loadClass("fr.igred.omero.util.LibraryChecker"); + Method check = checker.getMethod("areRequirementsAvailable"); + assertFalse((Boolean) check.invoke(null), "Libraries are available"); + } catch (ClassNotFoundException | NoSuchMethodException e) { + fail(String.format("Class or method not found: %s.", e.getMessage())); + } catch (InvocationTargetException | IllegalAccessException e) { + fail(String.format("Call to check method failed: %s.", e.getMessage())); + } catch (IOException e) { + fail(String.format("Could not create TestClassLoader: %s.", e.getMessage())); + } + } + + + @SuppressWarnings("CustomClassloader") + private static class TestClassLoader extends URLClassLoader { + + TestClassLoader(CharSequence excluded) throws MalformedURLException { + //noinspection ZeroLengthArrayAllocation + super(new URL[0], getSystemClassLoader().getParent()); + @SuppressWarnings("AccessOfSystemProperties") + String classpath = System.getProperty("java.class.path"); + String[] entries = classpath.split(File.pathSeparator); + for (String entry : entries) { + if (!entry.contains(excluded)) { + super.addURL(Paths.get(entry).toAbsolutePath().toUri().toURL()); + } + } + } + + } + +} diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 00000000..83465c91 --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + %d{yyyy-MM-dd} | %d{HH:mm:ss.SSS} | %-9.9t | %-5p | %-27.27logger{27} | %m%n + + + + + + + + \ No newline at end of file