From d51db23dc0e94694910c14ff895cc8106cd4cb5b Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Fri, 15 Mar 2024 10:52:13 +0100 Subject: [PATCH 01/10] Bump version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index d41bbe39..88984262 100644 --- a/pom.xml +++ b/pom.xml @@ -9,7 +9,7 @@ fr.igred simple-omero-client - 5.17.0 + 5.18.0-SNAPSHOT jar Simple OMERO Client From db5281789a2b497cf27481b25a4cc61fafa69a29 Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Tue, 12 Mar 2024 11:12:11 +0100 Subject: [PATCH 02/10] Use GitHub variables for Sonar * Use variables for Sonar * Update actions versions in maven.yml --- .github/workflows/maven.yml | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index e7de3c26..a6dc759a 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -11,41 +11,42 @@ jobs: env: HAVE_SONAR_TOKEN: ${{ secrets.SONAR_TOKEN != '' }} + HAVE_SONAR_DETAILS: ${{ vars.SONAR_PROJECTKEY != '' && vars.SONAR_ORGANIZATION != '' }} HAVE_DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN != '' }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Checkout omero-test-infra - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: repository: openmicroscopy/omero-test-infra submodules: true path: .omero - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: '17' distribution: 'adopt' server-id: github # Value of the distributionManagement/repository/id field of the pom.xml settings-path: ${{ github.workspace }} # location for the settings.xml file - name: Cache SonarCloud packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Cache Maven packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ secrets.CACHE_VERSION }}-${{ hashFiles('**/pom.xml') }} restore-keys: ${{ runner.os }}-m2-${{ secrets.CACHE_VERSION }} - name: Login to Docker Hub if: ${{ env.HAVE_DOCKERHUB_TOKEN == 'true' }} - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} @@ -63,20 +64,20 @@ jobs: - name: Set folders ownership back to current user run: sudo chown -R $(id -u):$(id -g) $GITHUB_WORKSPACE && sudo chown -R $(id -u):$(id -g) $HOME - name: Sonar analysis - if: ${{ env.HAVE_SONAR_TOKEN == 'true' }} + if: ${{ env.HAVE_SONAR_TOKEN == 'true' && env.HAVE_SONAR_DETAILS == 'true' }} run: mvn sonar:sonar -Dsonar.host.url=$SONAR_URL -Dsonar.projectKey=$SONAR_PROJECTKEY -Dsonar.organization=$SONAR_ORGANIZATION env: - SONAR_PROJECTKEY: GReD-Clermont_simple-omero-client - SONAR_ORGANIZATION: gred-clermont - SONAR_URL: https://sonarcloud.io + SONAR_PROJECTKEY: ${{ vars.SONAR_PROJECTKEY }} + SONAR_ORGANIZATION: ${{ vars.SONAR_ORGANIZATION }} + SONAR_URL: ${{ vars.SONAR_URL }} GITHUB_TOKEN: ${{ github.token }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - name: Upload to codecov after successful tests - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v4 with: token: ${{secrets.CODECOV_TOKEN}} - name: Upload Artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: jars path: | @@ -89,11 +90,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up JDK 17 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: '17' distribution: 'adopt' @@ -101,7 +102,7 @@ jobs: gpg-private-key: ${{ secrets.GPG_KEY }} # Value of the GPG private key to import gpg-passphrase: GPG_PASSPHRASE # env variable for GPG private key passphrase - name: Cache Maven packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.m2 key: ${{ runner.os }}-m2-${{ secrets.CACHE_VERSION }}-${{ hashFiles('**/pom.xml') }} From 198bc82eef2a424f81a8ee4784d07c57a4a7782e Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Sat, 25 Feb 2023 00:57:46 +0100 Subject: [PATCH 03/10] Add getImages() method to DatasetWrapper --- .../java/fr/igred/omero/repository/DatasetWrapper.java | 10 ++++++++++ .../java/fr/igred/omero/repository/DatasetTest.java | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java index e199ac7b..150a6a7e 100644 --- a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java +++ b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java @@ -168,6 +168,16 @@ public List getProjects(Client client) } + /** + * Gets all the images in the dataset (if it was properly loaded from OMERO). + * + * @return See above. + */ + public List getImages() { + return wrap(data.getImages(), ImageWrapper::new); + } + + /** * Gets all images in the dataset available from OMERO. * diff --git a/src/test/java/fr/igred/omero/repository/DatasetTest.java b/src/test/java/fr/igred/omero/repository/DatasetTest.java index 62f01779..9fe5a9d7 100644 --- a/src/test/java/fr/igred/omero/repository/DatasetTest.java +++ b/src/test/java/fr/igred/omero/repository/DatasetTest.java @@ -313,7 +313,7 @@ void testGetImagesPairKeyValueInDataset() throws Exception { void testGetImagesFromDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - List images = dataset.getImages(client); + List images = dataset.getImages(); assertEquals(3, images.size()); } From 509188736c600ffa9793410c89d857cb626d2b17 Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Mon, 18 Mar 2024 11:13:01 +0100 Subject: [PATCH 04/10] Add method to retrieve an ImagePlus within specified Bounds --- .../igred/omero/repository/ImageWrapper.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/fr/igred/omero/repository/ImageWrapper.java b/src/main/java/fr/igred/omero/repository/ImageWrapper.java index 826d9c40..e0e842ab 100644 --- a/src/main/java/fr/igred/omero/repository/ImageWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ImageWrapper.java @@ -670,7 +670,7 @@ public ImagePlus toImagePlus(Client client) /** - * Gets the imagePlus generated from the image from OMERO corresponding to the bound. + * Gets the ImagePlus from the image within the specified boundaries. * * @param client The client handling the connection. * @param xBounds Array containing the X bounds from which the pixels should be retrieved. @@ -781,7 +781,7 @@ public ImagePlus toImagePlus(Client client, /** - * Gets the imagePlus from the image generated from the ROI. + * Gets the ImagePlus from the image, but only inside the ROI. * * @param client The client handling the connection. * @param roi The ROI. @@ -794,8 +794,24 @@ public ImagePlus toImagePlus(Client client, */ public ImagePlus toImagePlus(Client client, ROIWrapper roi) throws ServiceException, AccessException, ExecutionException { - Bounds bounds = roi.getBounds(); + return toImagePlus(client, roi.getBounds()); + } + + /** + * Gets the ImagePlus from the image within the specified boundaries. + * + * @param client The client handling the connection. + * @param bounds The bounds. + * + * @return an ImagePlus from the ij library. + * + * @throws ServiceException Cannot connect to OMERO. + * @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, Bounds bounds) + throws ServiceException, AccessException, ExecutionException { int[] x = {bounds.getStart().getX(), bounds.getEnd().getX()}; int[] y = {bounds.getStart().getY(), bounds.getEnd().getY()}; int[] c = {bounds.getStart().getC(), bounds.getEnd().getC()}; From 0d8d774cc1d94e8e370acc64aa7796f03fd29d49 Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Mon, 18 Mar 2024 12:06:57 +0100 Subject: [PATCH 05/10] Shorten lines to improve readability --- .../fr/igred/omero/AnnotatableWrapper.java | 8 +- src/main/java/fr/igred/omero/Browser.java | 63 ++++++++++------ src/main/java/fr/igred/omero/Client.java | 23 ++++-- .../java/fr/igred/omero/GatewayWrapper.java | 34 ++++++--- .../annotations/FileAnnotationWrapper.java | 3 +- .../annotations/GenericAnnotationWrapper.java | 47 +++++++++--- .../igred/omero/annotations/TableWrapper.java | 4 +- .../omero/annotations/TagSetWrapper.java | 8 +- .../omero/repository/DatasetWrapper.java | 33 +++++---- .../igred/omero/repository/ImageWrapper.java | 74 ++++++++++++------- .../repository/PlateAcquisitionWrapper.java | 16 ++-- .../igred/omero/repository/PlateWrapper.java | 11 ++- .../omero/repository/ProjectWrapper.java | 4 +- .../igred/omero/repository/ScreenWrapper.java | 9 ++- .../omero/repository/WellSampleWrapper.java | 12 +-- .../igred/omero/roi/GenericShapeWrapper.java | 12 +-- .../java/fr/igred/omero/roi/ROIWrapper.java | 2 +- .../java/fr/igred/omero/util/Wrapper.java | 11 ++- 18 files changed, 244 insertions(+), 130 deletions(-) diff --git a/src/main/java/fr/igred/omero/AnnotatableWrapper.java b/src/main/java/fr/igred/omero/AnnotatableWrapper.java index 39f565fd..21ccbb7a 100644 --- a/src/main/java/fr/igred/omero/AnnotatableWrapper.java +++ b/src/main/java/fr/igred/omero/AnnotatableWrapper.java @@ -879,9 +879,11 @@ public > void unlink(Client client, Collec */ protected void removeLinks(Client client, String linkType, Collection childIds) throws ServiceException, OMEROServerError, AccessException, ExecutionException, InterruptedException { - String template = "select link from %s link where link.parent = %d and link.child.id in (:ids)"; - String query = String.format(template, linkType, getId()); - ParametersI param = new ParametersI(); + String template = "select link from %s link" + + " where link.parent = %d" + + " and link.child.id in (:ids)"; + String query = String.format(template, linkType, getId()); + ParametersI param = new ParametersI(); param.addIds(childIds); List os = ExceptionHandler.of(client.getGateway(), g -> g.getQueryService(client.getCtx()) diff --git a/src/main/java/fr/igred/omero/Browser.java b/src/main/java/fr/igred/omero/Browser.java index 5a5e6634..2c1907db 100644 --- a/src/main/java/fr/igred/omero/Browser.java +++ b/src/main/java/fr/igred/omero/Browser.java @@ -54,12 +54,13 @@ import java.util.Comparator; import java.util.List; import java.util.NoSuchElementException; -import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static fr.igred.omero.GenericObjectWrapper.flatten; import static fr.igred.omero.GenericObjectWrapper.wrap; +import static java.lang.String.format; +import static java.util.Objects.requireNonNull; /** @@ -96,7 +97,8 @@ public ProjectWrapper getProject(Long id) throws ServiceException, AccessException, ExecutionException { List projects = getProjects(id); if (projects.isEmpty()) { - throw new NoSuchElementException(String.format("Project %d doesn't exist in this context", id)); + String msg = format("Project %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return projects.iterator().next(); } @@ -203,7 +205,8 @@ public DatasetWrapper getDataset(Long id) throws ServiceException, AccessException, ExecutionException { List datasets = getDatasets(id); if (datasets.isEmpty()) { - throw new NoSuchElementException(String.format("Dataset %d doesn't exist in this context", id)); + String msg = format("Dataset %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return datasets.iterator().next(); } @@ -266,7 +269,8 @@ public List getDatasets() */ public List getDatasets(ExperimenterWrapper experimenter) throws ServiceException, AccessException, OMEROServerError, ExecutionException { - String query = String.format("select d from Dataset d where d.details.owner.id=%d", experimenter.getId()); + String template = "select d from Dataset d where d.details.owner.id=%d"; + String query = format(template, experimenter.getId()); Long[] ids = this.findByQuery(query) .stream() .map(IObject::getId) @@ -315,8 +319,10 @@ public List getOrphanedDatasets(ExperimenterWrapper experimenter String template = "select dataset from Dataset as dataset" + " join fetch dataset.details.owner as o" + " where o.id = %d" + - " and not exists (select obl from ProjectDatasetLink as obl where obl.child = dataset.id) "; - String query = String.format(template, experimenter.getId()); + " and not exists" + + " (select obl from ProjectDatasetLink as obl" + + " where obl.child = dataset.id)"; + String query = format(template, experimenter.getId()); Long[] ids = this.findByQuery(query) .stream() .map(IObject::getId) @@ -362,7 +368,8 @@ public ImageWrapper getImage(Long id) .handleOMEROException(error) .get(); if (image == null) { - throw new NoSuchElementException(String.format("Image %d doesn't exist in this context", id)); + String msg = format("Image %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return new ImageWrapper(image); } @@ -654,7 +661,8 @@ public ScreenWrapper getScreen(Long id) throws ServiceException, AccessException, ExecutionException { List screens = getScreens(id); if (screens.isEmpty()) { - throw new NoSuchElementException(String.format("Screen %d doesn't exist in this context", id)); + String msg = format("Screen %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return screens.iterator().next(); } @@ -714,7 +722,7 @@ public List getScreens() */ public List getScreens(ExperimenterWrapper experimenter) throws ServiceException, AccessException, ExecutionException { - String error = String.format("Cannot get screens for user %s", experimenter); + String error = format("Cannot get screens for user %s", experimenter); Collection screens = ExceptionHandler.of(getBrowseFacility(), bf -> bf.getScreens(getCtx(), experimenter.getId())) .handleOMEROException(error) @@ -739,7 +747,8 @@ public PlateWrapper getPlate(Long id) throws ServiceException, AccessException, ExecutionException { List plates = getPlates(id); if (plates.isEmpty()) { - throw new NoSuchElementException(String.format("Plate %d doesn't exist in this context", id)); + String msg = format("Plate %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return plates.iterator().next(); } @@ -825,9 +834,10 @@ public List getOrphanedPlates(ExperimenterWrapper experimenter) String template = "select plate from Plate as plate" + " join fetch plate.details.owner as o" + " where o.id = %d" + - " and not exists (select obl from " + - " ScreenPlateLink as obl where obl.child = plate.id) "; - String query = String.format(template, experimenter.getId()); + " and not exists" + + " (select obl from ScreenPlateLink as obl" + + " where obl.child = plate.id)"; + String query = format(template, experimenter.getId()); Long[] ids = this.findByQuery(query) .stream() .map(IObject::getId) @@ -869,7 +879,8 @@ public WellWrapper getWell(Long id) throws ServiceException, AccessException, ExecutionException { List wells = getWells(id); if (wells.isEmpty()) { - throw new NoSuchElementException(String.format("Plate %d doesn't exist in this context", id)); + String msg = format("Plate %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return wells.iterator().next(); } @@ -932,7 +943,8 @@ public List getWells() */ public List getWells(ExperimenterWrapper experimenter) throws ServiceException, AccessException, ExecutionException, OMEROServerError { - String query = String.format("select w from Well w where w.details.owner.id=%d", experimenter.getId()); + String template = "select w from Well w where w.details.owner.id=%d"; + String query = format(template, experimenter.getId()); Long[] ids = this.findByQuery(query) .stream() .map(IObject::getId) @@ -958,7 +970,8 @@ public FolderWrapper getFolder(long id) throws ServiceException, AccessException, ExecutionException { List folders = loadFolders(id); if (folders.isEmpty()) { - throw new NoSuchElementException(String.format("Folder %d doesn't exist in this context", id)); + String msg = format("Folder %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } return folders.iterator().next(); } @@ -996,7 +1009,7 @@ public List getFolders() */ public List getFolders(ExperimenterWrapper experimenter) throws ExecutionException, AccessException, ServiceException { - String error = String.format("Cannot get folders for user %s", experimenter); + String error = format("Cannot get folders for user %s", experimenter); Collection folders = ExceptionHandler.of(getBrowseFacility(), b -> b.getFolders(getCtx(), experimenter.getId())) .handleOMEROException(error) @@ -1088,9 +1101,10 @@ public TagAnnotationWrapper getTag(Long id) .get(); TagAnnotationData tag; if (o == null) { - throw new NoSuchElementException(String.format("Tag %d doesn't exist in this context", id)); + String msg = format("Tag %d doesn't exist in this context", id); + throw new NoSuchElementException(msg); } else { - tag = new TagAnnotationData((TagAnnotation) Objects.requireNonNull(o)); + tag = new TagAnnotationData((TagAnnotation) requireNonNull(o)); } return new TagAnnotationWrapper(tag); } @@ -1131,7 +1145,10 @@ public List getMapAnnotations() */ public List getMapAnnotations(String key) throws OMEROServerError, ServiceException { - String q = String.format("select m from MapAnnotation as m join m.mapValue as mv where mv.name = '%s'", key); + String template = "select m from MapAnnotation as m" + + " join m.mapValue as mv" + + " where mv.name = '%s'"; + String q = format(template, key); return findByQuery(q).stream() .map(omero.model.MapAnnotation.class::cast) .map(MapAnnotationData::new) @@ -1154,8 +1171,10 @@ public List getMapAnnotations(String key) */ public List getMapAnnotations(String key, String value) throws OMEROServerError, ServiceException { - String q = String.format("select m from MapAnnotation as m join m.mapValue as mv " + - "where mv.name = '%s' and mv.value = '%s'", key, value); + String template = "select m from MapAnnotation as m" + + " join m.mapValue as mv" + + " where mv.name = '%s' and mv.value = '%s'"; + String q = format(template, key, value); return findByQuery(q).stream() .map(omero.model.MapAnnotation.class::cast) .map(MapAnnotationData::new) diff --git a/src/main/java/fr/igred/omero/Client.java b/src/main/java/fr/igred/omero/Client.java index b39ce38b..d2401692 100644 --- a/src/main/java/fr/igred/omero/Client.java +++ b/src/main/java/fr/igred/omero/Client.java @@ -297,7 +297,8 @@ public ExperimenterWrapper getUser(String username) if (experimenter != null) { return new ExperimenterWrapper(experimenter); } else { - throw new NoSuchElementException(String.format("User not found: %s", username)); + String msg = String.format("User not found: %s", username); + throw new NoSuchElementException(msg); } } @@ -315,7 +316,9 @@ public ExperimenterWrapper getUser(String username) */ public ExperimenterWrapper getUser(long userId) throws ServiceException, OMEROServerError { - Experimenter user = ExceptionHandler.of(getGateway(), g -> g.getAdminService(getCtx()).getExperimenter(userId)) + Experimenter user = ExceptionHandler.of(getGateway(), + g -> g.getAdminService(getCtx()) + .getExperimenter(userId)) .rethrow(ApiUsageException.class, (m, e) -> new NoSuchElementException(m), "User not found: " + userId) @@ -339,13 +342,15 @@ public ExperimenterWrapper getUser(long userId) */ public GroupWrapper getGroup(String groupName) throws ExecutionException, ServiceException, AccessException { - GroupData group = ExceptionHandler.of(getAdminFacility(), a -> a.lookupGroup(getCtx(), groupName)) + GroupData group = ExceptionHandler.of(getAdminFacility(), + a -> a.lookupGroup(getCtx(), groupName)) .handleOMEROException("Cannot retrieve group: " + groupName) .get(); if (group != null) { return new GroupWrapper(group); } else { - throw new NoSuchElementException(String.format("Group not found: %s", groupName)); + String msg = String.format("Group not found: %s", groupName); + throw new NoSuchElementException(msg); } } @@ -363,7 +368,8 @@ public GroupWrapper getGroup(String groupName) */ public GroupWrapper getGroup(long groupId) throws ServiceException, OMEROServerError { - ExperimenterGroup group = ExceptionHandler.of(getGateway(), g -> g.getAdminService(getCtx()).getGroup(groupId)) + ExperimenterGroup group = ExceptionHandler.of(getGateway(), + g -> g.getAdminService(getCtx()).getGroup(groupId)) .rethrow(ApiUsageException.class, (m, e) -> new NoSuchElementException(m), "Group not found: " + groupId) @@ -378,8 +384,8 @@ public GroupWrapper getGroup(long groupId) * * @return See above. * - * @throws ServiceException Cannot connect to OMERO. - * @throws AccessException Cannot access data. + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. */ public List getGroups() throws ServiceException, AccessException { @@ -412,8 +418,9 @@ public List getGroups() public Client sudoGetUser(String username) throws ServiceException, AccessException, ExecutionException { ExperimenterWrapper sudoUser = getUser(username); + long groupId = sudoUser.getDefaultGroup().getId(); - SecurityContext context = new SecurityContext(sudoUser.getDefaultGroup().getId()); + SecurityContext context = new SecurityContext(groupId); context.setExperimenter(sudoUser.asDataObject()); context.sudo(); diff --git a/src/main/java/fr/igred/omero/GatewayWrapper.java b/src/main/java/fr/igred/omero/GatewayWrapper.java index 7f6f9b0a..1f5104ef 100644 --- a/src/main/java/fr/igred/omero/GatewayWrapper.java +++ b/src/main/java/fr/igred/omero/GatewayWrapper.java @@ -175,8 +175,10 @@ public long getCurrentGroupId() { * @throws ServiceException If the connection is broken, or not logged in */ public String getSessionId() throws ServiceException { - return ExceptionHandler.of(gateway, g -> g.getSessionId(user.asDataObject())) - .rethrow(DSOutOfServiceException.class, ServiceException::new, + return ExceptionHandler.of(gateway, + g -> g.getSessionId(user.asDataObject())) + .rethrow(DSOutOfServiceException.class, + ServiceException::new, "Could not retrieve session ID") .get(); } @@ -222,7 +224,10 @@ public void connect(String hostname, int port, String sessionId) */ public void connect(String hostname, int port, String username, char[] password, Long groupID) throws ServiceException { - LoginCredentials cred = new LoginCredentials(username, String.valueOf(password), hostname, port); + LoginCredentials cred = new LoginCredentials(username, + String.valueOf(password), + hostname, + port); cred.setGroupID(groupID); connect(cred); } @@ -242,7 +247,10 @@ public void connect(String hostname, int port, String username, char[] password, */ public void connect(String hostname, int port, String username, char[] password) throws ServiceException { - connect(new LoginCredentials(username, String.valueOf(password), hostname, port)); + connect(new LoginCredentials(username, + String.valueOf(password), + hostname, + port)); } @@ -323,7 +331,8 @@ public BrowseFacility getBrowseFacility() throws ExecutionException { */ public IQueryPrx getQueryService() throws ServiceException { return ExceptionHandler.of(gateway, g -> g.getQueryService(ctx)) - .rethrow(DSOutOfServiceException.class, ServiceException::new, + .rethrow(DSOutOfServiceException.class, + ServiceException::new, "Could not retrieve Query Service") .get(); } @@ -399,7 +408,8 @@ public AdminFacility getAdminFacility() throws ExecutionException { public OMEROMetadataStoreClient getImportStore() throws ServiceException { storeUses.incrementAndGet(); return ExceptionHandler.of(this, GatewayWrapper::getImportStoreLocked) - .rethrow(DSOutOfServiceException.class, ServiceException::new, + .rethrow(DSOutOfServiceException.class, + ServiceException::new, "Could not retrieve import store") .get(); } @@ -428,7 +438,8 @@ public void closeImport() { */ public List findByQuery(String query) throws ServiceException, OMEROServerError { - return ExceptionHandler.of(gateway, g -> g.getQueryService(ctx).findAllByQuery(query, null)) + return ExceptionHandler.of(gateway, + g -> g.getQueryService(ctx).findAllByQuery(query, null)) .handleServiceOrServer("Query failed: " + query) .get(); } @@ -447,7 +458,8 @@ public List findByQuery(String query) */ public IObject save(IObject object) throws ServiceException, AccessException, ExecutionException { - return ExceptionHandler.of(getDm(), d -> d.saveAndReturnObject(ctx, object)) + return ExceptionHandler.of(getDm(), + d -> d.saveAndReturnObject(ctx, object)) .handleOMEROException("Cannot save object") .get(); } @@ -467,7 +479,8 @@ public IObject save(IObject object) void delete(IObject object) throws ServiceException, AccessException, ExecutionException, OMEROServerError, InterruptedException { final long wait = 500L; - ExceptionHandler.ofConsumer(getDm(), d -> d.delete(ctx, object).loop(10, wait)) + ExceptionHandler.ofConsumer(getDm(), + d -> d.delete(ctx, object).loop(10, wait)) .rethrow(InterruptedException.class) .handleException("Cannot delete object") .rethrow(); @@ -488,7 +501,8 @@ void delete(IObject object) void delete(List objects) throws ServiceException, AccessException, ExecutionException, OMEROServerError, InterruptedException { final long wait = 500L; - ExceptionHandler.ofConsumer(getDm(), d -> d.delete(ctx, objects).loop(10, wait)) + ExceptionHandler.ofConsumer(getDm(), + d -> d.delete(ctx, objects).loop(10, wait)) .rethrow(InterruptedException.class) .handleException("Cannot delete objects") .rethrow(); diff --git a/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java b/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java index 599c0787..aea3c39b 100644 --- a/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/FileAnnotationWrapper.java @@ -65,7 +65,8 @@ private RawFileStorePrx writeFile(Client client, FileOutputStream stream) throws ServerError, DSOutOfServiceException, IOException { final int inc = 262144; - RawFileStorePrx store = client.getGateway().getRawFileService(client.getCtx()); + RawFileStorePrx store = client.getGateway() + .getRawFileService(client.getCtx()); store.setFileId(this.getFileID()); long size = getFileSize(); diff --git a/src/main/java/fr/igred/omero/annotations/GenericAnnotationWrapper.java b/src/main/java/fr/igred/omero/annotations/GenericAnnotationWrapper.java index 8560c7b6..e1f7a432 100644 --- a/src/main/java/fr/igred/omero/annotations/GenericAnnotationWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/GenericAnnotationWrapper.java @@ -123,8 +123,9 @@ public void setDescription(String description) { */ public int countAnnotationLinks(Client client) throws ServiceException, OMEROServerError { - return client.findByQuery("select link.parent from ome.model.IAnnotationLink link " + - "where link.child.id=" + getId()).size(); + String q = "select link.parent from ome.model.IAnnotationLink link" + + " where link.child.id=" + getId(); + return client.findByQuery(q).size(); } @@ -143,7 +144,11 @@ public int countAnnotationLinks(Client client) public List getProjects(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, ProjectWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.getProjects(ids); } @@ -163,7 +168,11 @@ public List getProjects(Client client) public List getDatasets(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, DatasetWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.getDatasets(ids); } @@ -183,7 +192,11 @@ public List getDatasets(Client client) public List getImages(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, ImageWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.getImages(ids); } @@ -203,7 +216,11 @@ public List getImages(Client client) public List getScreens(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, ScreenWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.getScreens(ids); } @@ -223,7 +240,11 @@ public List getScreens(Client client) public List getPlates(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, PlateWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.getPlates(ids); } @@ -262,7 +283,11 @@ public List getPlateAcquisitions(Client client) public List getWells(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, WellWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.getWells(ids); } @@ -282,7 +307,11 @@ public List getWells(Client client) public List getFolders(Client client) throws ServiceException, AccessException, OMEROServerError, ExecutionException { List os = getLinks(client, FolderWrapper.ANNOTATION_LINK); - Long[] ids = os.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); return client.loadFolders(ids); } diff --git a/src/main/java/fr/igred/omero/annotations/TableWrapper.java b/src/main/java/fr/igred/omero/annotations/TableWrapper.java index 7bb34704..b4106464 100644 --- a/src/main/java/fr/igred/omero/annotations/TableWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/TableWrapper.java @@ -37,7 +37,6 @@ import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; import java.text.NumberFormat; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; @@ -49,6 +48,7 @@ import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; +import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.toMap; @@ -898,7 +898,7 @@ public void saveAs(String path, char delimiter) String sol = "\""; String sep = String.format("\"%c\"", delimiter); String eol = String.format("\"%n"); - try (PrintWriter stream = new PrintWriter(file, StandardCharsets.UTF_8.name())) { + try (PrintWriter stream = new PrintWriter(file, UTF_8.name())) { sb.append(sol); for (int j = 0; j < columnCount; j++) { sb.append(columns[j].getName()); diff --git a/src/main/java/fr/igred/omero/annotations/TagSetWrapper.java b/src/main/java/fr/igred/omero/annotations/TagSetWrapper.java index 90ce57d5..2ec224c1 100644 --- a/src/main/java/fr/igred/omero/annotations/TagSetWrapper.java +++ b/src/main/java/fr/igred/omero/annotations/TagSetWrapper.java @@ -146,10 +146,10 @@ public void link(Client dm, TagAnnotationWrapper... tags) */ public void reload(Browser browser) throws ServiceException, AccessException, ExecutionException, OMEROServerError { - String query = "select t from TagAnnotation as t " + - "left outer join fetch t.annotationLinks as l " + - "left outer join fetch l.child as a " + - "where t.id=" + getId(); + String query = "select t from TagAnnotation as t" + + " left outer join fetch t.annotationLinks as l" + + " left outer join fetch l.child as a" + + " where t.id=" + getId(); IObject o = browser.findByQuery(query).iterator().next(); data = new TagAnnotationData((omero.model.TagAnnotation) o); } diff --git a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java index 150a6a7e..faf2fb63 100644 --- a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java +++ b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java @@ -67,8 +67,8 @@ public class DatasetWrapper extends GenericRepositoryObjectWrapper */ public DatasetWrapper(String name, String description) { super(new DatasetData()); - this.data.setName(name); - this.data.setDescription(description); + data.setName(name); + data.setDescription(description); } @@ -162,9 +162,14 @@ protected String annotationLinkType() { */ 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).distinct().toArray(Long[]::new)); + String query = "select link.parent from ProjectDatasetLink as link" + + " where link.child=" + getId(); + List os = client.findByQuery(query); + return client.getProjects(os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .distinct() + .toArray(Long[]::new)); } @@ -276,14 +281,14 @@ public List getImagesTagged(Client client, TagAnnotationWrapper ta */ public List getImagesTagged(Client client, Long tagId) throws ServiceException, AccessException, OMEROServerError, ExecutionException { - Long[] ids = client.findByQuery("select link.parent " + - "from ImageAnnotationLink link " + - "where link.child = " + + Long[] ids = client.findByQuery("select link.parent" + + " from ImageAnnotationLink link" + + " where link.child = " + tagId + - " and link.parent in " + - "(select link2.child " + - "from DatasetImageLink link2 " + - "where link2.parent = " + + " and link.parent in" + + " (select link2.child" + + " from DatasetImageLink link2" + + " where link2.parent = " + data.getId() + ")") .stream() .map(IObject::getId) @@ -597,7 +602,9 @@ public List importAndReplaceImages(Client client, String path, ReplacePoli } } if (policy == ReplacePolicy.DELETE_ORPHANED) { - List idsToDelete = toDelete.stream().map(GenericObjectWrapper::getId).collect(Collectors.toList()); + List idsToDelete = toDelete.stream() + .map(GenericObjectWrapper::getId) + .collect(Collectors.toList()); Iterable orphans = new ArrayList<>(toDelete); for (ImageWrapper orphan : orphans) { diff --git a/src/main/java/fr/igred/omero/repository/ImageWrapper.java b/src/main/java/fr/igred/omero/repository/ImageWrapper.java index e0e842ab..c075de73 100644 --- a/src/main/java/fr/igred/omero/repository/ImageWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ImageWrapper.java @@ -69,10 +69,10 @@ import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; -import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; +import static java.util.logging.Level.WARNING; import static omero.rtypes.rint; @@ -302,10 +302,15 @@ public List getProjects(Client client) */ 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()); + String query = "select link.parent from DatasetImageLink as link" + + " where link.child=" + getId(); + List os = client.findByQuery(query); - return client.getDatasets(os.stream().map(IObject::getId).map(RLong::getValue).distinct().toArray(Long[]::new)); + return client.getDatasets(os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .distinct() + .toArray(Long[]::new)); } @@ -404,7 +409,9 @@ public List getPlateAcquisitions(Client client) */ public List getPlates(Client client) throws AccessException, ServiceException, ExecutionException { - return distinct(getWells(client).stream().map(WellWrapper::getPlate).collect(Collectors.toList())); + return distinct(getWells(client).stream() + .map(WellWrapper::getPlate) + .collect(Collectors.toList())); } @@ -444,10 +451,13 @@ public List getScreens(Client client) */ public boolean isOrphaned(Client client) throws ServiceException, OMEROServerError { - boolean noDataset = client.findByQuery("select link.parent from DatasetImageLink link " + - "where link.child=" + getId()).isEmpty(); - boolean noWell = client.findByQuery("select ws from WellSample ws where image=" + getId()).isEmpty(); - return noDataset && noWell; + String dsQuery = "select link.parent from DatasetImageLink link" + + " where link.child=" + getId(); + String wsQuery = "select ws from WellSample ws where image=" + getId(); + + boolean noDataset = client.findByQuery(dsQuery).isEmpty(); + boolean noWellSample = client.findByQuery(wsQuery).isEmpty(); + return noDataset && noWellSample; } @@ -467,11 +477,16 @@ public List getFilesetImages(Client client) throws AccessException, ServiceException, ExecutionException, OMEROServerError { List related = new ArrayList<>(0); if (data.isFSImage()) { - long fsId = this.asDataObject().getFilesetId(); + long fsId = this.asDataObject().getFilesetId(); + String query = "select i from Image i where fileset=" + fsId; - List objects = client.findByQuery("select i from Image i where fileset=" + fsId); + List objects = client.findByQuery(query); - Long[] ids = objects.stream().map(IObject::getId).map(RLong::getValue).sorted().toArray(Long[]::new); + Long[] ids = objects.stream() + .map(IObject::getId) + .map(RLong::getValue) + .sorted() + .toArray(Long[]::new); related = client.getImages(ids); } return related; @@ -587,7 +602,7 @@ public List getROIFolders(Client client) Collection folders = ExceptionHandler.of(roiFacility, rf -> rf.getROIFolders(client.getCtx(), - this.data.getId())) + data.getId())) .handleOMEROException("Cannot get folders for " + this) .get(); @@ -609,8 +624,13 @@ public List getROIFolders(Client client) */ public List getFolders(Client client) throws ServiceException, AccessException, ExecutionException, OMEROServerError { - String query = String.format("select link.parent from FolderImageLink as link where link.child.id=%d", getId()); - Long[] ids = client.findByQuery(query).stream().map(o -> o.getId().getValue()).toArray(Long[]::new); + String template = "select link.parent from FolderImageLink as link" + + " where link.child.id=%d"; + String query = String.format(template, getId()); + Long[] ids = client.findByQuery(query) + .stream() + .map(o -> o.getId().getValue()) + .toArray(Long[]::new); return client.loadFolders(ids); } @@ -635,7 +655,7 @@ public FolderWrapper getFolder(Client client, Long folderId) folderId); FolderWrapper folderWrapper = new FolderWrapper((Folder) os.iterator().next()); - folderWrapper.setImage(this.data.getId()); + folderWrapper.setImage(data.getId()); return folderWrapper; } @@ -665,7 +685,7 @@ public PixelsWrapper getPixels() { */ public ImagePlus toImagePlus(Client client) throws ServiceException, AccessException, ExecutionException { - return this.toImagePlus(client, null, null, null, null, null); + return toImagePlus(client, null, null, null, null, null); } @@ -899,7 +919,9 @@ public Color getChannelColor(Client client, int index) long pixelsId = data.getDefaultPixels().getId(); Color color = getChannelImportedColor(client, index); try { - RenderingEnginePrx re = client.getGateway().getRenderingService(client.getCtx(), pixelsId); + RenderingEnginePrx re = client.getGateway() + .getRenderingService(client.getCtx(), + pixelsId); re.lookupPixels(pixelsId); if (!(re.lookupRenderingDef(pixelsId))) { re.resetDefaultSettings(true); @@ -911,7 +933,7 @@ public Color getChannelColor(Client client, int index) re.close(); } catch (DSOutOfServiceException | ServerError e) { Logger.getLogger(getClass().getName()) - .log(Level.WARNING, "Error while retrieving current color", e); + .log(WARNING, "Error while retrieving current color", e); } return color; } @@ -934,11 +956,12 @@ public BufferedImage getThumbnail(Client client, int size) throws ServiceException, OMEROServerError, IOException { BufferedImage thumbnail = null; - byte[] array = ExceptionHandler.of(client, c -> getThumbnailBytes(c, size)) - .handleServiceOrServer("Error retrieving thumbnail.") - .get(); - if (array != null) { - try (ByteArrayInputStream stream = new ByteArrayInputStream(array)) { + byte[] arr = ExceptionHandler.of(client, + c -> getThumbnailBytes(c, size)) + .handleServiceOrServer("Error retrieving thumbnail.") + .get(); + if (arr != null) { + try (ByteArrayInputStream stream = new ByteArrayInputStream(arr)) { //Create a buffered image to display thumbnail = ImageIO.read(stream); } @@ -964,7 +987,8 @@ public List download(Client client, String path) List files = new ArrayList<>(0); try { TransferFacility transfer = client.getGateway().getFacility(TransferFacility.class); - files = ExceptionHandler.of(transfer, t -> t.downloadImage(client.getCtx(), path, getId())) + files = ExceptionHandler.of(transfer, + t -> t.downloadImage(client.getCtx(), path, getId())) .handleException("Could not download image " + getId()) .get(); } catch (ExecutionException e) { diff --git a/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java b/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java index f5b43023..30ad4a42 100644 --- a/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PlateAcquisitionWrapper.java @@ -350,14 +350,14 @@ public int getMaximumFieldCount() { public void reload(Browser browser) throws ServiceException, AccessException, ExecutionException { String query = "select pa from PlateAcquisition as pa " + - "left outer join fetch pa.plate as p " + - "left outer join fetch pa.wellSample as ws " + - "left outer join fetch ws.plateAcquisition as pa2 " + - "left outer join fetch ws.well as w " + - "left outer join fetch ws.image as img " + - "left outer join fetch img.pixels as pix " + - "left outer join fetch pix.pixelsType as pt " + - "where pa.id=" + getId(); + " left outer join fetch pa.plate as p" + + " left outer join fetch pa.wellSample as ws" + + " left outer join fetch ws.plateAcquisition as pa2" + + " left outer join fetch ws.well as w" + + " left outer join fetch ws.image as img" + + " left outer join fetch img.pixels as pix" + + " left outer join fetch pix.pixelsType as pt" + + " where pa.id=" + getId(); // TODO: replace with Browser::findByQuery when possible IObject o = ExceptionHandler.of(browser.getGateway(), g -> g.getQueryService(browser.getCtx()) diff --git a/src/main/java/fr/igred/omero/repository/PlateWrapper.java b/src/main/java/fr/igred/omero/repository/PlateWrapper.java index d2ee382c..8ed74f02 100644 --- a/src/main/java/fr/igred/omero/repository/PlateWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PlateWrapper.java @@ -142,9 +142,14 @@ public void setDescription(String description) { */ 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)); + String query = "select link.parent from ScreenPlateLink as link" + + " where link.child=" + getId(); + List os = client.findByQuery(query); + return client.getScreens(os.stream() + .map(IObject::getId) + .map(RLong::getValue) + .distinct() + .toArray(Long[]::new)); } diff --git a/src/main/java/fr/igred/omero/repository/ProjectWrapper.java b/src/main/java/fr/igred/omero/repository/ProjectWrapper.java index 9e0d071b..1c65408d 100644 --- a/src/main/java/fr/igred/omero/repository/ProjectWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ProjectWrapper.java @@ -33,12 +33,12 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static java.util.Collections.singletonList; +import static java.util.Comparator.comparing; /** @@ -305,7 +305,7 @@ public List getImages(Client client, String datasetName, String im } List images = lists.stream() .flatMap(Collection::stream) - .sorted(Comparator.comparing(GenericObjectWrapper::getId)) + .sorted(comparing(GenericObjectWrapper::getId)) .collect(Collectors.toList()); return distinct(images); diff --git a/src/main/java/fr/igred/omero/repository/ScreenWrapper.java b/src/main/java/fr/igred/omero/repository/ScreenWrapper.java index 00d74776..f29e2e68 100644 --- a/src/main/java/fr/igred/omero/repository/ScreenWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ScreenWrapper.java @@ -30,12 +30,12 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import static java.util.Collections.singletonList; +import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toMap; @@ -186,10 +186,11 @@ public List getPlateAcquisitions(Client client) return getPlates().stream() .map(PlateWrapper::getPlateAcquisitions) .flatMap(Collection::stream) - .collect(toMap(GenericRepositoryObjectWrapper::getId, p -> p, (p1, p2) -> p1)) + .collect(toMap(GenericRepositoryObjectWrapper::getId, + p -> p, (p1, p2) -> p1)) .values() .stream() - .sorted(Comparator.comparing(GenericRepositoryObjectWrapper::getId)) + .sorted(comparing(GenericRepositoryObjectWrapper::getId)) .collect(Collectors.toList()); } @@ -376,7 +377,7 @@ public void reload(Browser browser) */ public boolean importImages(GatewayWrapper client, String... paths) throws ServiceException, OMEROServerError, AccessException, IOException, ExecutionException { - return this.importImages(client, 1, paths); + return importImages(client, 1, paths); } diff --git a/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java b/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java index b7149b2d..46de6ac8 100644 --- a/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java +++ b/src/main/java/fr/igred/omero/repository/WellSampleWrapper.java @@ -213,12 +213,12 @@ public long getStartTime() { */ public void reload(Browser browser) throws ServiceException, AccessException, ExecutionException { - String query = "select ws from WellSample as ws " + - "left outer join fetch ws.plateAcquisition as pa " + - "left outer join fetch ws.well as w " + - "left outer join fetch ws.image as img " + - "left outer join fetch img.pixels as pix " + - "where ws.id=" + getId(); + String query = "select ws from WellSample as ws" + + " left outer join fetch ws.plateAcquisition as pa" + + " left outer join fetch ws.well as w" + + " left outer join fetch ws.image as img" + + " left outer join fetch img.pixels as pix" + + " where ws.id=" + getId(); // TODO: replace with Browser::findByQuery when possible IObject o = ExceptionHandler.of(browser.getGateway(), g -> g.getQueryService(browser.getCtx()) diff --git a/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java b/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java index 932d09ac..74e8ae05 100644 --- a/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java +++ b/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java @@ -316,7 +316,7 @@ public T asShapeData() { * @return the channel. -1 if the shape applies to all channels of the image. */ public int getC() { - return this.data.getC(); + return data.getC(); } @@ -326,7 +326,7 @@ public int getC() { * @param c the channel. Pass -1 to remove z value, i.e. shape applies to all channels of the image. */ public void setC(int c) { - this.data.setC(c); + data.setC(c); } @@ -336,7 +336,7 @@ public void setC(int c) { * @return the z-section. -1 if the shape applies to all z-sections of the image. */ public int getZ() { - return this.data.getZ(); + return data.getZ(); } @@ -346,7 +346,7 @@ public int getZ() { * @param z the z-section. Pass -1 to remove z value, i.e. shape applies to all z-sections of the image. */ public void setZ(int z) { - this.data.setZ(z); + data.setZ(z); } @@ -356,7 +356,7 @@ public void setZ(int z) { * @return the time-point. -1 if the shape applies to all time-points of the image. */ public int getT() { - return this.data.getT(); + return data.getT(); } @@ -366,7 +366,7 @@ public int getT() { * @param t the time-point. Pass -1 to remove t value, i.e. shape applies to all time-points of the image. */ public void setT(int t) { - this.data.setT(t); + data.setT(t); } diff --git a/src/main/java/fr/igred/omero/roi/ROIWrapper.java b/src/main/java/fr/igred/omero/roi/ROIWrapper.java index dab8c05b..a73a3f0c 100644 --- a/src/main/java/fr/igred/omero/roi/ROIWrapper.java +++ b/src/main/java/fr/igred/omero/roi/ROIWrapper.java @@ -514,7 +514,7 @@ public Bounds getBounds() { * @return A list of ROIs. */ public List toImageJ() { - return this.toImageJ(IJ_PROPERTY); + return toImageJ(IJ_PROPERTY); } diff --git a/src/main/java/fr/igred/omero/util/Wrapper.java b/src/main/java/fr/igred/omero/util/Wrapper.java index cd94e94e..0395cd05 100644 --- a/src/main/java/fr/igred/omero/util/Wrapper.java +++ b/src/main/java/fr/igred/omero/util/Wrapper.java @@ -83,6 +83,8 @@ import omero.gateway.model.WellData; import omero.gateway.model.WellSampleData; +import static java.lang.String.format; + /** * Utility class to convert DataObjects dynamically. @@ -126,7 +128,8 @@ public static > } else if (object instanceof MaskData) { converted = (U) new MaskWrapper((MaskData) object); } else { - throw new IllegalArgumentException(String.format(UNKNOWN_TYPE, object.getClass().getName())); + String msg = format(UNKNOWN_TYPE, object.getClass().getName()); + throw new IllegalArgumentException(msg); } return converted; } @@ -155,7 +158,8 @@ public static Date: Mon, 18 Mar 2024 12:26:56 +0100 Subject: [PATCH 06/10] Add static method call() to ExceptionHandler to improve readability --- .../fr/igred/omero/AnnotatableWrapper.java | 155 +++++++------ src/main/java/fr/igred/omero/Browser.java | 207 +++++++++--------- src/main/java/fr/igred/omero/Client.java | 38 ++-- .../java/fr/igred/omero/GatewayWrapper.java | 9 +- .../fr/igred/omero/GenericObjectWrapper.java | 10 +- .../omero/exception/ExceptionHandler.java | 37 ++++ .../igred/omero/meta/ExperimenterWrapper.java | 10 +- .../omero/repository/DatasetWrapper.java | 43 ++-- .../igred/omero/repository/FolderWrapper.java | 26 +-- .../igred/omero/repository/ImageWrapper.java | 56 +++-- .../igred/omero/repository/PixelsWrapper.java | 9 +- .../repository/PlateAcquisitionWrapper.java | 16 +- .../igred/omero/repository/PlateWrapper.java | 22 +- .../omero/repository/ProjectWrapper.java | 23 +- .../igred/omero/repository/ScreenWrapper.java | 28 ++- .../omero/repository/WellSampleWrapper.java | 16 +- .../igred/omero/repository/WellWrapper.java | 15 +- 17 files changed, 372 insertions(+), 348 deletions(-) diff --git a/src/main/java/fr/igred/omero/AnnotatableWrapper.java b/src/main/java/fr/igred/omero/AnnotatableWrapper.java index 21ccbb7a..d0be30b1 100644 --- a/src/main/java/fr/igred/omero/AnnotatableWrapper.java +++ b/src/main/java/fr/igred/omero/AnnotatableWrapper.java @@ -26,7 +26,6 @@ import fr.igred.omero.annotations.TableWrapper; import fr.igred.omero.annotations.TagAnnotationWrapper; import fr.igred.omero.exception.AccessException; -import fr.igred.omero.exception.ExceptionHandler; import fr.igred.omero.exception.OMEROServerError; import fr.igred.omero.exception.ServiceException; import fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy; @@ -57,6 +56,8 @@ import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; +import static fr.igred.omero.exception.ExceptionHandler.call; + /** * Generic class containing a DataObject (or a subclass) object. @@ -116,9 +117,9 @@ public > boolean isLinked(Client client, A protected void link(Client client, A annotation) throws ServiceException, AccessException, ExecutionException { String error = String.format("Cannot add %s to %s", annotation, this); - ExceptionHandler.of(client.getDm(), d -> d.attachAnnotation(client.getCtx(), annotation, data)) - .handleOMEROException(error) - .rethrow(); + call(client.getDm(), + d -> d.attachAnnotation(client.getCtx(), annotation, data), + error); } @@ -285,13 +286,12 @@ public List getTags(Client client) throws ServiceException, AccessException, ExecutionException { List> types = Collections.singletonList(TagAnnotationData.class); - List annotations = ExceptionHandler.of(client.getMetadata(), - m -> m.getAnnotations(client.getCtx(), - data, - types, - null)) - .handleOMEROException("Cannot get tags for " + this) - .get(); + List annotations = call(client.getMetadata(), + m -> m.getAnnotations(client.getCtx(), + data, + types, + null), + "Cannot get tags for " + this); return annotations.stream() .filter(TagAnnotationData.class::isInstance) @@ -316,14 +316,13 @@ public List getTags(Client client) public List getMapAnnotations(Client client) throws ServiceException, AccessException, ExecutionException { List> types = Collections.singletonList(MapAnnotationData.class); - List annotations = ExceptionHandler.of(client.getMetadata(), - m -> m.getAnnotations(client.getCtx(), - data, - types, - null)) - .handleOMEROException("Cannot get map annotations for " - + this) - .get(); + List annotations = call(client.getMetadata(), + m -> m.getAnnotations(client.getCtx(), + data, + types, + null), + "Cannot get map annotations for " + + this); return annotations.stream() .filter(MapAnnotationData.class::isInstance) @@ -434,13 +433,12 @@ private List getRatings(Client client, List userI List> types = Collections.singletonList(RatingAnnotationData.class); - List annotations = ExceptionHandler.of(client.getMetadata(), - m -> m.getAnnotations(client.getCtx(), - data, - types, - userIds)) - .handleOMEROException(error) - .get(); + List annotations = call(client.getMetadata(), + m -> m.getAnnotations(client.getCtx(), + data, + types, + userIds), + error); annotations = annotations == null ? Collections.emptyList() : annotations; return annotations.stream() .filter(RatingAnnotationData.class::isInstance) @@ -555,23 +553,24 @@ public void addTable(Client client, TableWrapper table) String error = "Cannot add table to " + this; TablesFacility tablesFacility = client.getTablesFacility(); - TableData tableData = ExceptionHandler.of(tablesFacility, - tf -> tf.addTable(client.getCtx(), - data, - table.getName(), - table.createTable())) - .handleOMEROException(error) - .get(); - - Collection tables = ExceptionHandler.of(tablesFacility, - tf -> tf.getAvailableTables(client.getCtx(), - data)) - .handleOMEROException(error) - .get(); + TableData tableData = call(tablesFacility, + tf -> tf.addTable(client.getCtx(), + data, + table.getName(), + table.createTable()), + error); + + Collection tables = call(tablesFacility, + tf -> tf.getAvailableTables(client.getCtx(), + data), + error); long fileId = tableData.getOriginalFileId(); - long id = tables.stream().filter(v -> v.getFileID() == fileId) - .mapToLong(DataObject::getId).max().orElse(-1L); + long id = tables.stream() + .filter(v -> v.getFileID() == fileId) + .mapToLong(DataObject::getId) + .max() + .orElse(-1L); table.setId(id); table.setFileId(tableData.getOriginalFileId()); } @@ -593,12 +592,10 @@ public void addTable(Client client, TableWrapper table) public void addAndReplaceTable(Client client, TableWrapper table, ReplacePolicy policy) throws ServiceException, AccessException, ExecutionException, OMEROServerError, InterruptedException { String error = "Cannot add table to " + this; - - Collection tables = wrap(ExceptionHandler.of(client.getTablesFacility(), - t -> t.getAvailableTables( - client.getCtx(), data)) - .handleOMEROException(error) - .get(), + Collection tables = wrap(call(client.getTablesFacility(), + t -> t.getAvailableTables(client.getCtx(), + data), + error), FileAnnotationWrapper::new); addTable(client, table); tables.removeIf(t -> !t.getDescription().equals(table.getName())); @@ -645,21 +642,22 @@ public void addAndReplaceTable(Client client, TableWrapper table) */ public TableWrapper getTable(Client client, Long fileId) throws ServiceException, AccessException, ExecutionException { - TableData info = ExceptionHandler.of(client.getTablesFacility(), tf -> tf.getTableInfo(client.getCtx(), fileId)) - .handleOMEROException("Cannot get table from " + this) - .get(); + TableData info = call(client.getTablesFacility(), + tf -> tf.getTableInfo(client.getCtx(), fileId), + "Cannot get table from " + this); long nRows = info.getNumberOfRows(); - TableData table = ExceptionHandler.of(client.getTablesFacility(), - tf -> tf.getTable(client.getCtx(), fileId, 0, nRows - 1)) - .handleOMEROException("Cannot get table from " + this) - .get(); - String name = ExceptionHandler.of(client.getTablesFacility(), - tf -> tf.getAvailableTables(client.getCtx(), data) - .stream().filter(t -> t.getFileID() == fileId) - .map(FileAnnotationData::getDescription) - .findFirst().orElse(null)) - .handleOMEROException("Cannot get table name from " + this) - .get(); + TableData table = call(client.getTablesFacility(), + tf -> tf.getTable(client.getCtx(), fileId, + 0, nRows - 1), + "Cannot get table from " + this); + String name = call(client.getTablesFacility(), + tf -> tf.getAvailableTables(client.getCtx(), data) + .stream() + .filter(t -> t.getFileID() == fileId) + .map(FileAnnotationData::getDescription) + .findFirst() + .orElse(null), + "Cannot get table name from " + this); TableWrapper result = new TableWrapper(Objects.requireNonNull(table)); result.setName(name); return result; @@ -679,10 +677,9 @@ public TableWrapper getTable(Client client, Long fileId) */ public List getTables(Client client) throws ServiceException, AccessException, ExecutionException { - Collection tables = ExceptionHandler.of(client.getTablesFacility(), - tf -> tf.getAvailableTables(client.getCtx(), data)) - .handleOMEROException("Cannot get tables from " + this) - .get(); + Collection tables = call(client.getTablesFacility(), + tf -> tf.getAvailableTables(client.getCtx(), data), + "Cannot get tables from " + this); List tablesWrapper = new ArrayList<>(tables.size()); for (FileAnnotationData table : tables) { @@ -810,13 +807,12 @@ public List getFileAnnotations(Client client) List> types = Collections.singletonList(FileAnnotationData.class); - List annotations = ExceptionHandler.of(client.getMetadata(), - m -> m.getAnnotations(client.getCtx(), - data, - types, - null)) - .handleOMEROException(error) - .get(); + List annotations = call(client.getMetadata(), + m -> m.getAnnotations(client.getCtx(), + data, + types, + null), + error); return annotations.stream() .filter(FileAnnotationData.class::isInstance) @@ -885,11 +881,10 @@ protected void removeLinks(Client client, String linkType, Collection chil String query = String.format(template, linkType, getId()); ParametersI param = new ParametersI(); param.addIds(childIds); - List os = ExceptionHandler.of(client.getGateway(), - g -> g.getQueryService(client.getCtx()) - .findAllByQuery(query, param)) - .handleOMEROException("Cannot get links from " + this) - .get(); + List os = call(client.getGateway(), + g -> g.getQueryService(client.getCtx()) + .findAllByQuery(query, param), + "Cannot get links from " + this); client.delete(os); } @@ -926,9 +921,9 @@ protected void removeLink(Client client, String linkType, long childId) */ private List getAnnotationData(Client client) throws AccessException, ServiceException, ExecutionException { - return ExceptionHandler.of(client.getMetadata(), m -> m.getAnnotations(client.getCtx(), data)) - .handleOMEROException("Cannot get annotations from " + this) - .get(); + return call(client.getMetadata(), + m -> m.getAnnotations(client.getCtx(), data), + "Cannot get annotations from " + this); } diff --git a/src/main/java/fr/igred/omero/Browser.java b/src/main/java/fr/igred/omero/Browser.java index 2c1907db..60fc9527 100644 --- a/src/main/java/fr/igred/omero/Browser.java +++ b/src/main/java/fr/igred/omero/Browser.java @@ -59,7 +59,9 @@ import static fr.igred.omero.GenericObjectWrapper.flatten; import static fr.igred.omero.GenericObjectWrapper.wrap; +import static fr.igred.omero.exception.ExceptionHandler.call; import static java.lang.String.format; +import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; @@ -117,11 +119,11 @@ public ProjectWrapper getProject(Long id) */ public List getProjects(Long... ids) throws ServiceException, AccessException, ExecutionException { - Collection projects = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getProjects(getCtx(), Arrays.asList(ids))) - .handleOMEROException("Cannot get projects with IDs: " - + Arrays.toString(ids)) - .get(); + Collection projects = call(getBrowseFacility(), + bf -> bf.getProjects(getCtx(), + asList(ids)), + "Cannot get projects with IDs: " + + Arrays.toString(ids)); return wrap(projects, ProjectWrapper::new); } @@ -137,10 +139,9 @@ public List getProjects(Long... ids) */ public List getProjects() throws ServiceException, AccessException, ExecutionException { - Collection projects = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getProjects(getCtx())) - .handleOMEROException("Cannot get projects") - .get(); + Collection projects = call(getBrowseFacility(), + bf -> bf.getProjects(getCtx()), + "Cannot get projects"); return wrap(projects, ProjectWrapper::new); } @@ -158,11 +159,12 @@ public List getProjects() */ public List getProjects(ExperimenterWrapper experimenter) throws ServiceException, AccessException, ExecutionException { - Collection projects = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getProjects(getCtx(), experimenter.getId())) - .handleOMEROException("Cannot get projects for user " - + experimenter) - .get(); + long exId = experimenter.getId(); + Collection projects = call(getBrowseFacility(), + bf -> bf.getProjects(getCtx(), + exId), + "Cannot get projects for user " + + experimenter); return wrap(projects, ProjectWrapper::new); } @@ -180,11 +182,11 @@ public List getProjects(ExperimenterWrapper experimenter) */ public List getProjects(String name) throws ServiceException, AccessException, ExecutionException { - Collection projects = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getProjects(getCtx(), name)) - .handleOMEROException("Cannot get projects with name: " - + name) - .get(); + Collection projects = call(getBrowseFacility(), + bf -> bf.getProjects(getCtx(), + name), + "Cannot get projects with name: " + + name); return wrap(projects, ProjectWrapper::new); } @@ -225,11 +227,11 @@ public DatasetWrapper getDataset(Long id) */ public List getDatasets(Long... ids) throws ServiceException, AccessException, ExecutionException { - Collection datasets = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getDatasets(getCtx(), Arrays.asList(ids))) - .handleOMEROException("Cannot get datasets with IDs: " - + Arrays.toString(ids)) - .get(); + Collection datasets = call(getBrowseFacility(), + bf -> bf.getDatasets(getCtx(), + asList(ids)), + "Cannot get datasets with IDs: " + + Arrays.toString(ids)); return wrap(datasets, DatasetWrapper::new); } @@ -294,10 +296,10 @@ public List getDatasets(ExperimenterWrapper experimenter) public List getDatasets(String name) throws ServiceException, AccessException, ExecutionException { String error = "Cannot get datasets with name: " + name; - Collection datasets = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getDatasets(getCtx(), name)) - .handleOMEROException(error) - .get(); + Collection datasets = call(getBrowseFacility(), + bf -> bf.getDatasets(getCtx(), + name), + error); return wrap(datasets, DatasetWrapper::new); } @@ -363,10 +365,9 @@ public List getOrphanedDatasets() public ImageWrapper getImage(Long id) throws ServiceException, AccessException, ExecutionException { String error = "Cannot get image with ID: " + id; - ImageData image = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getImage(getCtx(), id)) - .handleOMEROException(error) - .get(); + ImageData image = call(getBrowseFacility(), + bf -> bf.getImage(getCtx(), id), + error); if (image == null) { String msg = format("Image %d doesn't exist in this context", id); throw new NoSuchElementException(msg); @@ -389,10 +390,10 @@ public ImageWrapper getImage(Long id) public List getImages(Long... ids) throws ServiceException, AccessException, ExecutionException { String error = "Cannot get images with IDs: " + Arrays.toString(ids); - Collection images = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getImages(getCtx(), Arrays.asList(ids))) - .handleOMEROException(error) - .get(); + Collection images = call(getBrowseFacility(), + bf -> bf.getImages(getCtx(), + asList(ids)), + error); return wrap(images, ImageWrapper::new); } @@ -408,10 +409,9 @@ public List getImages(Long... ids) */ public List getImages() throws ServiceException, AccessException, ExecutionException { - Collection images = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getUserImages(getCtx())) - .handleOMEROException("Cannot get images") - .get(); + Collection images = call(getBrowseFacility(), + bf -> bf.getUserImages(getCtx()), + "Cannot get images"); return wrap(images, ImageWrapper::new); } @@ -429,10 +429,9 @@ public List getImages() */ public List getImages(String name) throws ServiceException, AccessException, ExecutionException { - Collection images = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getImages(getCtx(), name)) - .handleOMEROException("Cannot get images with name: " + name) - .get(); + Collection images = call(getBrowseFacility(), + bf -> bf.getImages(getCtx(), name), + "Cannot get images with name: " + name); images.removeIf(image -> !image.getName().equals(name)); return wrap(images, ImageWrapper::new); } @@ -451,10 +450,11 @@ public List getImages(String name) */ public List getOrphanedImages(ExperimenterWrapper experimenter) throws ServiceException, AccessException, ExecutionException { - Collection images = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getOrphanedImages(getCtx(), experimenter.getId())) - .handleOMEROException("Cannot get orphaned images") - .get(); + long exId = experimenter.getId(); + Collection images = call(getBrowseFacility(), + bf -> bf.getOrphanedImages(getCtx(), + exId), + "Cannot get orphaned images"); return wrap(images, ImageWrapper::new); } @@ -681,11 +681,11 @@ public ScreenWrapper getScreen(Long id) */ public List getScreens(Long... ids) throws ServiceException, AccessException, ExecutionException { - Collection screens = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getScreens(getCtx(), Arrays.asList(ids))) - .handleOMEROException("Cannot get screens with IDs: " - + Arrays.toString(ids)) - .get(); + Collection screens = call(getBrowseFacility(), + bf -> bf.getScreens(getCtx(), + asList(ids)), + "Cannot get screens with IDs: " + + Arrays.toString(ids)); return wrap(screens, ScreenWrapper::new); } @@ -701,10 +701,9 @@ public List getScreens(Long... ids) */ public List getScreens() throws ServiceException, AccessException, ExecutionException { - Collection screens = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getScreens(getCtx())) - .handleOMEROException("Cannot get screens") - .get(); + Collection screens = call(getBrowseFacility(), + bf -> bf.getScreens(getCtx()), + "Cannot get screens"); return wrap(screens, ScreenWrapper::new); } @@ -723,10 +722,11 @@ public List getScreens() public List getScreens(ExperimenterWrapper experimenter) throws ServiceException, AccessException, ExecutionException { String error = format("Cannot get screens for user %s", experimenter); - Collection screens = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getScreens(getCtx(), experimenter.getId())) - .handleOMEROException(error) - .get(); + long exId = experimenter.getId(); + Collection screens = call(getBrowseFacility(), + bf -> bf.getScreens(getCtx(), + exId), + error); return wrap(screens, ScreenWrapper::new); } @@ -767,11 +767,11 @@ public PlateWrapper getPlate(Long id) */ public List getPlates(Long... ids) throws ServiceException, AccessException, ExecutionException { - Collection plates = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getPlates(getCtx(), Arrays.asList(ids))) - .handleOMEROException("Cannot get plates with IDs: " - + Arrays.toString(ids)) - .get(); + Collection plates = call(getBrowseFacility(), + bf -> bf.getPlates(getCtx(), + asList(ids)), + "Cannot get plates with IDs: " + + Arrays.toString(ids)); return wrap(plates, PlateWrapper::new); } @@ -787,10 +787,9 @@ public List getPlates(Long... ids) */ public List getPlates() throws ServiceException, AccessException, ExecutionException { - Collection plates = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getPlates(getCtx())) - .handleOMEROException("Cannot get plates") - .get(); + Collection plates = call(getBrowseFacility(), + bf -> bf.getPlates(getCtx()), + "Cannot get plates"); return wrap(plates, PlateWrapper::new); } @@ -808,11 +807,11 @@ public List getPlates() */ public List getPlates(ExperimenterWrapper experimenter) throws ServiceException, AccessException, ExecutionException { - Collection plates = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getPlates(getCtx(), experimenter.getId())) - .handleOMEROException("Cannot get plates for user " - + experimenter) - .get(); + long exId = experimenter.getId(); + Collection plates = call(getBrowseFacility(), + bf -> bf.getPlates(getCtx(), exId), + "Cannot get plates for user " + + experimenter); return wrap(plates, PlateWrapper::new); } @@ -899,11 +898,11 @@ public WellWrapper getWell(Long id) */ public List getWells(Long... ids) throws ServiceException, AccessException, ExecutionException { - Collection wells = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.getWells(getCtx(), Arrays.asList(ids))) - .handleOMEROException("Cannot get wells with IDs: " - + Arrays.toString(ids)) - .get(); + Collection wells = call(getBrowseFacility(), + bf -> bf.getWells(getCtx(), + asList(ids)), + "Cannot get wells with IDs: " + + Arrays.toString(ids)); return wrap(wells, WellWrapper::new); } @@ -988,10 +987,9 @@ public FolderWrapper getFolder(long id) */ public List getFolders() throws ExecutionException, AccessException, ServiceException { - Collection folders = ExceptionHandler.of(getBrowseFacility(), - b -> b.getFolders(getCtx())) - .handleOMEROException("Cannot get folders") - .get(); + Collection folders = call(getBrowseFacility(), + b -> b.getFolders(getCtx()), + "Cannot get folders"); return wrap(folders, FolderWrapper::new); } @@ -1010,10 +1008,10 @@ public List getFolders() public List getFolders(ExperimenterWrapper experimenter) throws ExecutionException, AccessException, ServiceException { String error = format("Cannot get folders for user %s", experimenter); - Collection folders = ExceptionHandler.of(getBrowseFacility(), - b -> b.getFolders(getCtx(), experimenter.getId())) - .handleOMEROException(error) - .get(); + long exId = experimenter.getId(); + Collection folders = call(getBrowseFacility(), + b -> b.getFolders(getCtx(), exId), + error); return wrap(folders, FolderWrapper::new); } @@ -1032,10 +1030,10 @@ public List getFolders(ExperimenterWrapper experimenter) public List loadFolders(Long... ids) throws ServiceException, AccessException, ExecutionException { String error = "Cannot get folders with IDs: " + Arrays.toString(ids); - Collection folders = ExceptionHandler.of(getBrowseFacility(), - bf -> bf.loadFolders(getCtx(), Arrays.asList(ids))) - .handleOMEROException(error) - .get(); + Collection folders = call(getBrowseFacility(), + bf -> bf.loadFolders(getCtx(), + asList(ids)), + error); return wrap(folders, FolderWrapper::new); } @@ -1050,8 +1048,10 @@ public List loadFolders(Long... ids) */ public List getTags() throws OMEROServerError, ServiceException { - List os = ExceptionHandler.of(getGateway(), g -> g.getQueryService(getCtx()) - .findAll(TagAnnotation.class.getSimpleName(), null)) + String klass = TagAnnotation.class.getSimpleName(); + List os = ExceptionHandler.of(getGateway(), + g -> g.getQueryService(getCtx()) + .findAll(klass, null)) .handleServiceOrServer("Cannot get tags") .get(); return os.stream() @@ -1095,8 +1095,10 @@ public List getTags(String name) */ public TagAnnotationWrapper getTag(Long id) throws OMEROServerError, ServiceException { - IObject o = ExceptionHandler.of(getGateway(), g -> g.getQueryService(getCtx()) - .find(TagAnnotation.class.getSimpleName(), id)) + String klass = TagAnnotation.class.getSimpleName(); + IObject o = ExceptionHandler.of(getGateway(), + g -> g.getQueryService(getCtx()) + .find(klass, id)) .handleServiceOrServer("Cannot get tag ID: " + id) .get(); TagAnnotationData tag; @@ -1120,8 +1122,10 @@ public TagAnnotationWrapper getTag(Long id) */ public List getMapAnnotations() throws OMEROServerError, ServiceException { - return ExceptionHandler.of(getGateway(), g -> g.getQueryService(getCtx()) - .findAll(omero.model.MapAnnotation.class.getSimpleName(), null)) + String klass = omero.model.MapAnnotation.class.getSimpleName(); + return ExceptionHandler.of(getGateway(), + g -> g.getQueryService(getCtx()) + .findAll(klass, null)) .handleServiceOrServer("Cannot get map annotations") .get() .stream() @@ -1197,9 +1201,10 @@ public List getMapAnnotations(String key, String value) */ public MapAnnotationWrapper getMapAnnotation(Long id) throws ServiceException, ExecutionException, AccessException { - MapAnnotationData kv = ExceptionHandler.of(getBrowseFacility(), b -> b.findObject(getCtx(), - MapAnnotationData.class, - id)) + MapAnnotationData kv = ExceptionHandler.of(getBrowseFacility(), + b -> b.findObject(getCtx(), + MapAnnotationData.class, + id)) .handleServiceOrAccess("Cannot get map annotation with ID: " + id) .get(); diff --git a/src/main/java/fr/igred/omero/Client.java b/src/main/java/fr/igred/omero/Client.java index d2401692..a411906d 100644 --- a/src/main/java/fr/igred/omero/Client.java +++ b/src/main/java/fr/igred/omero/Client.java @@ -47,6 +47,7 @@ import java.util.stream.Collectors; import static fr.igred.omero.GenericObjectWrapper.flatten; +import static fr.igred.omero.exception.ExceptionHandler.call; /** @@ -290,12 +291,12 @@ public void deleteTables(Collection tables) */ public ExperimenterWrapper getUser(String username) throws ExecutionException, ServiceException, AccessException { - ExperimenterData experimenter = ExceptionHandler.of(getAdminFacility(), - a -> a.lookupExperimenter(getCtx(), username)) - .handleOMEROException("Cannot retrieve user: " + username) - .get(); - if (experimenter != null) { - return new ExperimenterWrapper(experimenter); + ExperimenterData user = call(getAdminFacility(), + a -> a.lookupExperimenter(getCtx(), + username), + "Cannot retrieve user: " + username); + if (user != null) { + return new ExperimenterWrapper(user); } else { String msg = String.format("User not found: %s", username); throw new NoSuchElementException(msg); @@ -342,10 +343,9 @@ public ExperimenterWrapper getUser(long userId) */ public GroupWrapper getGroup(String groupName) throws ExecutionException, ServiceException, AccessException { - GroupData group = ExceptionHandler.of(getAdminFacility(), - a -> a.lookupGroup(getCtx(), groupName)) - .handleOMEROException("Cannot retrieve group: " + groupName) - .get(); + GroupData group = call(getAdminFacility(), + a -> a.lookupGroup(getCtx(), groupName), + "Cannot retrieve group: " + groupName); if (group != null) { return new GroupWrapper(group); } else { @@ -390,15 +390,15 @@ public GroupWrapper getGroup(long groupId) public List getGroups() throws ServiceException, AccessException { String error = "Cannot retrieve the groups on OMERO"; - return ExceptionHandler.of(getGateway(), - g -> g.getAdminService(getCtx()).lookupGroups()) - .handleOMEROException(error) - .get() - .stream() - .filter(Objects::nonNull) - .map(GroupData::new) - .map(GroupWrapper::new) - .collect(Collectors.toList()); + List groups = call(getGateway(), + g -> g.getAdminService(getCtx()) + .lookupGroups(), + error); + return groups.stream() + .filter(Objects::nonNull) + .map(GroupData::new) + .map(GroupWrapper::new) + .collect(Collectors.toList()); } diff --git a/src/main/java/fr/igred/omero/GatewayWrapper.java b/src/main/java/fr/igred/omero/GatewayWrapper.java index 1f5104ef..7a9e65ca 100644 --- a/src/main/java/fr/igred/omero/GatewayWrapper.java +++ b/src/main/java/fr/igred/omero/GatewayWrapper.java @@ -48,6 +48,8 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; +import static fr.igred.omero.exception.ExceptionHandler.call; + /** * Basic class, contains the gateway, the security context, and multiple facilities. @@ -458,10 +460,9 @@ public List findByQuery(String query) */ public IObject save(IObject object) throws ServiceException, AccessException, ExecutionException { - return ExceptionHandler.of(getDm(), - d -> d.saveAndReturnObject(ctx, object)) - .handleOMEROException("Cannot save object") - .get(); + return call(getDm(), + d -> d.saveAndReturnObject(ctx, object), + "Cannot save object"); } diff --git a/src/main/java/fr/igred/omero/GenericObjectWrapper.java b/src/main/java/fr/igred/omero/GenericObjectWrapper.java index a67b829b..f053ddec 100644 --- a/src/main/java/fr/igred/omero/GenericObjectWrapper.java +++ b/src/main/java/fr/igred/omero/GenericObjectWrapper.java @@ -19,7 +19,6 @@ import fr.igred.omero.exception.AccessException; -import fr.igred.omero.exception.ExceptionHandler; import fr.igred.omero.exception.ServiceException; import fr.igred.omero.meta.ExperimenterWrapper; import omero.gateway.model.DataObject; @@ -33,6 +32,8 @@ import java.util.function.Function; import java.util.stream.Collectors; +import static fr.igred.omero.exception.ExceptionHandler.call; + /** * Generic class containing a DataObject (or a subclass) object. @@ -222,10 +223,9 @@ public String toString() { @SuppressWarnings("unchecked") public void saveAndUpdate(Client client) throws ExecutionException, ServiceException, AccessException { - data = (T) ExceptionHandler.of(client.getDm(), - d -> d.saveAndReturnObject(client.getCtx(), data)) - .handleOMEROException("Cannot save and update object.") - .get(); + data = (T) call(client.getDm(), + d -> d.saveAndReturnObject(client.getCtx(), data), + "Cannot save and update object."); } diff --git a/src/main/java/fr/igred/omero/exception/ExceptionHandler.java b/src/main/java/fr/igred/omero/exception/ExceptionHandler.java index e7fc652f..e7c02f0c 100644 --- a/src/main/java/fr/igred/omero/exception/ExceptionHandler.java +++ b/src/main/java/fr/igred/omero/exception/ExceptionHandler.java @@ -225,6 +225,29 @@ private static void doThrow(Exception t) throws E { } + /** + * Calls the provided function on the given input and return the result or handles any OMERO exception and rethrows + * the appropriate exception with the specified message. + * + * @param Input argument type. + * @param Returned object type. + * @param input Object to process. + * @param mapper Lambda to apply on object. + * @param message The message, if an exception is thrown. + * + * @return The function output. + * + * @throws ServiceException Cannot connect to OMERO. + * @throws AccessException Cannot access data. + */ + public static R call(I input, + OMEROFunction mapper, + String message) + throws AccessException, ServiceException { + return of(input, mapper).handleOMEROException(message).get(); + } + + /** * Checks the cause of an exception on OMERO and throws: * * - * @param message Error message. + * @param msg Error message. * * @return The same ExceptionHandler. * * @throws AccessException Cannot access data. * @throws ServiceException Cannot connect to OMERO. */ - public ExceptionHandler handleOMEROException(String message) + public ExceptionHandler handleOMEROException(String msg) throws ServiceException, AccessException { - return this.rethrow(DSAccessException.class, AccessException::new, message) - .handleServerAndService(message); + return this.rethrow(DSAccessException.class, AccessException::new, msg) + .handleServerAndService(msg); } diff --git a/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java b/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java index bf2aab57..fbfdae66 100644 --- a/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java +++ b/src/main/java/fr/igred/omero/meta/ExperimenterWrapper.java @@ -227,7 +227,9 @@ public boolean isLDAP() { * @return See above. */ public boolean isLeader(GroupWrapper group) { - return group.getLeaders().stream().anyMatch(l -> l.getId() == data.getId()); + return group.getLeaders() + .stream() + .anyMatch(l -> l.getId() == data.getId()); } diff --git a/src/main/java/fr/igred/omero/meta/GroupWrapper.java b/src/main/java/fr/igred/omero/meta/GroupWrapper.java index aae8849c..e7f1c81d 100644 --- a/src/main/java/fr/igred/omero/meta/GroupWrapper.java +++ b/src/main/java/fr/igred/omero/meta/GroupWrapper.java @@ -120,7 +120,9 @@ public void setDescription(String description) { * @return See above. */ public List getLeaders() { - return wrap(data.getLeaders(), ExperimenterWrapper::new, ExperimenterWrapper::getLastName); + return wrap(data.getLeaders(), + ExperimenterWrapper::new, + ExperimenterWrapper::getLastName); } @@ -130,7 +132,9 @@ public List getLeaders() { * @return See above. */ public List getExperimenters() { - return wrap(data.getExperimenters(), ExperimenterWrapper::new, ExperimenterWrapper::getLastName); + return wrap(data.getExperimenters(), + ExperimenterWrapper::new, + ExperimenterWrapper::getLastName); } @@ -140,7 +144,9 @@ public List getExperimenters() { * @return See above. */ public List getMembersOnly() { - return wrap(data.getMembersOnly(), ExperimenterWrapper::new, ExperimenterWrapper::getLastName); + return wrap(data.getMembersOnly(), + ExperimenterWrapper::new, + ExperimenterWrapper::getLastName); } diff --git a/src/main/java/fr/igred/omero/meta/PlaneInfoWrapper.java b/src/main/java/fr/igred/omero/meta/PlaneInfoWrapper.java index ae3e9b56..e9cfd5b8 100644 --- a/src/main/java/fr/igred/omero/meta/PlaneInfoWrapper.java +++ b/src/main/java/fr/igred/omero/meta/PlaneInfoWrapper.java @@ -20,7 +20,6 @@ import fr.igred.omero.GenericObjectWrapper; import ome.formats.model.UnitsFactory; -import ome.units.UNITS; import ome.units.unit.Unit; import omero.gateway.model.PlaneInfoData; import omero.model.Length; @@ -34,7 +33,9 @@ import java.util.Objects; import java.util.function.Function; +import static java.lang.Double.NaN; import static ome.formats.model.UnitsFactory.convertTime; +import static ome.units.UNITS.SECOND; public class PlaneInfoWrapper extends GenericObjectWrapper { @@ -59,29 +60,32 @@ public PlaneInfoWrapper(PlaneInfoData object) { */ public static Time computeMeanTimeInterval(Collection planesInfo, int sizeT) { // planesInfo should be larger than sizeT, unless it is empty - ome.units.quantity.Time[] deltas = new ome.units.quantity.Time[Math.min(sizeT, planesInfo.size())]; + int size = Math.min(sizeT, planesInfo.size()); + ome.units.quantity.Time[] deltas = new ome.units.quantity.Time[size]; planesInfo.stream() - .filter(p -> p.getTheC() == 0 && p.getTheZ() == 0 && p.getTheT() < deltas.length) + .filter(p -> p.getTheC() == 0 + && p.getTheZ() == 0 + && p.getTheT() < deltas.length) .forEach(p -> deltas[p.getTheT()] = convertTime(p.getDeltaT())); Unit unit = Arrays.stream(deltas) .filter(Objects::nonNull) .findFirst() .map(ome.units.quantity.Time::unit) - .orElse(UNITS.SECOND); + .orElse(SECOND); double mean = 0; int count = 0; for (int i = 1; i < deltas.length; i++) { - double delta1 = deltas[i - 1] != null ? deltas[i - 1].value(unit).doubleValue() : Double.NaN; - double delta2 = deltas[i] != null ? deltas[i].value(unit).doubleValue() : Double.NaN; + double delta1 = deltas[i - 1] != null ? deltas[i - 1].value(unit).doubleValue() : NaN; + double delta2 = deltas[i] != null ? deltas[i].value(unit).doubleValue() : NaN; if (!Double.isNaN(delta1) && !Double.isNaN(delta2)) { mean += delta2 - delta1; count++; } } - mean /= count == 0 ? Double.NaN : count; + mean /= count == 0 ? NaN : count; return new TimeI(mean, unit); } @@ -95,22 +99,22 @@ public static Time computeMeanTimeInterval(Collection planesInfo, int channel) { - ome.units.quantity.Time t = null; + ome.units.quantity.Time t0 = null; Iterator iterator = planesInfo.iterator(); - while (t == null && iterator.hasNext()) { - t = convertTime(planesInfo.iterator().next().getExposureTime()); + while (t0 == null && iterator.hasNext()) { + t0 = convertTime(planesInfo.iterator().next().getExposureTime()); } - Unit unit = t == null ? UNITS.SECOND : t.unit(); + Unit unit = t0 == null ? SECOND : t0.unit(); double mean = 0; int count = 0; - for (PlaneInfoWrapper plane : planesInfo) { - if (channel == plane.getTheC()) { - ome.units.quantity.Time time = convertTime(plane.getExposureTime()); - if (time != null) { - Number value = time.value(unit); + for (PlaneInfoWrapper p : planesInfo) { + if (channel == p.getTheC()) { + ome.units.quantity.Time t = convertTime(p.getExposureTime()); + if (t != null) { + Number value = t.value(unit); if (value != null) { mean += value.doubleValue(); } @@ -118,7 +122,7 @@ public static Time computeMeanExposureTime(Iterable } } } - mean /= count == 0 ? Double.NaN : count; + mean /= count == 0 ? NaN : count; return new TimeI(mean, unit); } diff --git a/src/main/java/fr/igred/omero/repository/ChannelWrapper.java b/src/main/java/fr/igred/omero/repository/ChannelWrapper.java index 12e81c5d..629ac24a 100644 --- a/src/main/java/fr/igred/omero/repository/ChannelWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ChannelWrapper.java @@ -58,10 +58,10 @@ public ChannelData asChannelData() { * @return See above. */ public boolean hasRGBA() { - return data.asChannel().getRed() != null && - data.asChannel().getGreen() != null && - data.asChannel().getBlue() != null && - data.asChannel().getAlpha() != null; + return data.asChannel().getRed() != null + && data.asChannel().getGreen() != null + && data.asChannel().getBlue() != null + && data.asChannel().getAlpha() != null; } diff --git a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java index 0d55ec46..e139eee3 100644 --- a/src/main/java/fr/igred/omero/repository/DatasetWrapper.java +++ b/src/main/java/fr/igred/omero/repository/DatasetWrapper.java @@ -393,8 +393,8 @@ public List getImagesWithKeyValuePair(Client client, String key, S for (ImageData image : images) { ImageWrapper imageWrapper = new ImageWrapper(image); - Map pairsKeyValue = imageWrapper.getKeyValuePairs(client); - if (pairsKeyValue.get(key) != null && pairsKeyValue.get(key).equals(value)) { + Map pairs = imageWrapper.getKeyValuePairs(client); + if (pairs.get(key) != null && pairs.get(key).equals(value)) { selected.add(imageWrapper); } } @@ -605,7 +605,7 @@ public List importAndReplaceImages(Client client, String path, ReplacePoli Iterable orphans = new ArrayList<>(toDelete); for (ImageWrapper orphan : orphans) { for (ImageWrapper other : orphan.getFilesetImages(client)) { - if (!idsToDelete.contains(other.getId()) && other.isOrphaned(client)) { + if (other.isOrphaned(client) && !idsToDelete.contains(other.getId())) { toDelete.add(other); } } diff --git a/src/main/java/fr/igred/omero/repository/FolderWrapper.java b/src/main/java/fr/igred/omero/repository/FolderWrapper.java index 8692dd34..670f0830 100644 --- a/src/main/java/fr/igred/omero/repository/FolderWrapper.java +++ b/src/main/java/fr/igred/omero/repository/FolderWrapper.java @@ -45,10 +45,10 @@ import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; import static fr.igred.omero.exception.ExceptionHandler.call; import static java.util.Collections.singletonList; +import static java.util.stream.Collectors.toList; /** @@ -247,10 +247,11 @@ public void addChild(FolderWrapper folder) { * @param folders The new children folders. */ public void addChildren(Collection folders) { - data.asFolder().addAllChildFoldersSet(folders.stream() - .map(GenericObjectWrapper::asDataObject) - .map(DataObject::asFolder) - .collect(Collectors.toList())); + data.asFolder() + .addAllChildFoldersSet(folders.stream() + .map(GenericObjectWrapper::asDataObject) + .map(DataObject::asFolder) + .collect(toList())); } @@ -276,8 +277,10 @@ public List getChildren() { */ public void addImages(Client client, ImageWrapper... images) throws ServiceException, AccessException, ExecutionException { - List links = new ArrayList<>(images.length); - List linkedIds = getImages().stream().map(GenericObjectWrapper::getId).collect(Collectors.toList()); + List links = new ArrayList<>(images.length); + List linkedIds = getImages().stream() + .map(GenericObjectWrapper::getId) + .collect(toList()); for (ImageWrapper image : images) { if (!linkedIds.contains(image.getId())) { FolderImageLink link = new FolderImageLinkI(); @@ -286,7 +289,8 @@ public void addImages(Client client, ImageWrapper... images) links.add(link); } } - ExceptionHandler.of(client.getDm(), d -> d.saveAndReturnObject(client.getCtx(), links, null, null)) + ExceptionHandler.of(client.getDm(), + d -> d.saveAndReturnObject(client.getCtx(), links, null, null)) .handleOMEROException("Cannot save links.") .rethrow(); } @@ -373,7 +377,7 @@ public void addROIs(Client client, long imageId, ROIWrapper... rois) throws ServiceException, AccessException, ExecutionException { List roiData = Arrays.stream(rois) .map(GenericObjectWrapper::asDataObject) - .collect(Collectors.toList()); + .collect(toList()); ROIFacility roiFac = client.getRoiFacility(); ExceptionHandler.of(roiFac, rf -> rf.addRoisToFolders(client.getCtx(), @@ -445,7 +449,7 @@ public List getROIs(Client client, long imageId) .flatMap(Collection::stream) .map(ROIWrapper::new) .sorted(Comparator.comparing(GenericObjectWrapper::getId)) - .collect(Collectors.toList()); + .collect(toList()); return distinct(roiWrappers); } @@ -585,7 +589,7 @@ public void unlinkROIs(Client client, Collection rois) throws ServiceException, AccessException, ExecutionException { List roiData = rois.stream() .map(ROIWrapper::asDataObject) - .collect(Collectors.toList()); + .collect(toList()); ExceptionHandler.ofConsumer(client.getRoiFacility(), rf -> rf.removeRoisFromFolders(client.getCtx(), -1L, diff --git a/src/main/java/fr/igred/omero/repository/ImageWrapper.java b/src/main/java/fr/igred/omero/repository/ImageWrapper.java index b1c130e8..1ee96502 100644 --- a/src/main/java/fr/igred/omero/repository/ImageWrapper.java +++ b/src/main/java/fr/igred/omero/repository/ImageWrapper.java @@ -35,14 +35,12 @@ import ij.measure.Calibration; import ij.process.ImageProcessor; import ij.process.LUT; -import loci.common.DataTools; import loci.formats.FormatTools; import omero.RLong; import omero.ServerError; import omero.api.RenderingEnginePrx; import omero.api.ThumbnailStorePrx; import omero.gateway.exception.DSOutOfServiceException; -import omero.gateway.facility.ROIFacility; import omero.gateway.facility.TransferFacility; import omero.gateway.model.ChannelData; import omero.gateway.model.FolderData; @@ -74,6 +72,7 @@ import static fr.igred.omero.exception.ExceptionHandler.call; import static java.util.Comparator.comparing; import static java.util.logging.Level.WARNING; +import static loci.common.DataTools.makeDataArray; import static omero.rtypes.rint; @@ -366,7 +365,8 @@ public List getWellSamples(Client client) public List getWells(Client client) throws AccessException, ServiceException, ExecutionException { List wellSamples = getWellSamples(client); - Collection wells = new ArrayList<>(wellSamples.size()); + + Collection wells = new ArrayList<>(wellSamples.size()); for (WellSampleWrapper ws : wellSamples) { wells.add(ws.getWell(client)); } @@ -600,9 +600,7 @@ public List getROIs(Client client) */ public List getROIFolders(Client client) throws ServiceException, AccessException, ExecutionException { - ROIFacility roiFacility = client.getRoiFacility(); - - Collection folders = call(roiFacility, + Collection folders = call(client.getRoiFacility(), rf -> rf.getROIFolders(client.getCtx(), data.getId()), "Cannot get folders for " + this); @@ -762,7 +760,7 @@ public ImagePlus toImagePlus(Client client, byte[] tiles = pixels.getRawTile(client, pos, sizeX, sizeY, bpp); int n = imp.getStackIndex(c + 1, z + 1, t + 1); - stack.setPixels(DataTools.makeDataArray(tiles, bpp, isFloat, false), n); + stack.setPixels(makeDataArray(tiles, bpp, isFloat, false), n); ImageProcessor ip = stack.getProcessor(n); ip.resetMinAndMax(); @@ -856,10 +854,11 @@ public ImagePlus toImagePlus(Client client, Bounds bounds) */ public List getChannels(Client client) throws ServiceException, AccessException, ExecutionException { + String error = "Cannot get the channel name for " + this; List channels = call(client.getMetadata(), m -> m.getChannelData(client.getCtx(), getId()), - "Cannot get the channel name for " + this); + error); return channels.stream() .sorted(comparing(ChannelData::getIndex)) .map(ChannelWrapper::new) diff --git a/src/main/java/fr/igred/omero/repository/PixelsWrapper.java b/src/main/java/fr/igred/omero/repository/PixelsWrapper.java index 43251fa2..63a1acfb 100644 --- a/src/main/java/fr/igred/omero/repository/PixelsWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PixelsWrapper.java @@ -24,7 +24,6 @@ import fr.igred.omero.exception.ExceptionHandler; import fr.igred.omero.exception.ServiceException; import fr.igred.omero.meta.PlaneInfoWrapper; -import ome.units.UNITS; import ome.units.unit.Unit; import omero.gateway.exception.DataSourceException; import omero.gateway.facility.RawDataFacility; @@ -41,6 +40,7 @@ import static fr.igred.omero.exception.ExceptionHandler.call; import static ome.formats.model.UnitsFactory.convertLength; +import static ome.units.UNITS.MICROMETER; /** @@ -102,12 +102,12 @@ private static void copy(double[][] tab, Plane2D p, Coordinates start, int width * @param bpp Bytes per pixels of the image. */ private static void copy(byte[] bytes, Plane2D p, Coordinates start, int width, int height, int imgWidth, int bpp) { - int startX = start.getX(); - int startY = start.getY(); + int x0 = start.getX(); + int y0 = start.getY(); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { for (int i = 0; i < bpp; i++) { - bytes[((y + startY) * imgWidth + x + startX) * bpp + i] = p.getRawValue((x + y * width) * bpp + i); + bytes[((y + y0) * imgWidth + x + x0) * bpp + i] = p.getRawValue((x + y * width) * bpp + i); } } } @@ -244,9 +244,12 @@ public Time getMeanExposureTime(int channel) { * @return See above. */ public Length getPositionX() { - ome.units.quantity.Length pixSizeX = convertLength(getPixelSizeX()); - Unit unit = pixSizeX == null ? UNITS.MICROMETER : pixSizeX.unit(); - return PlaneInfoWrapper.getMinPosition(planesInfo, PlaneInfoWrapper::getPositionX, unit); + ome.units.quantity.Length pixSizeX = convertLength(getPixelSizeX()); + + Unit unit = pixSizeX == null ? MICROMETER : pixSizeX.unit(); + return PlaneInfoWrapper.getMinPosition(planesInfo, + PlaneInfoWrapper::getPositionX, + unit); } @@ -257,9 +260,12 @@ public Length getPositionX() { * @return See above. */ public Length getPositionY() { - ome.units.quantity.Length pixSizeY = convertLength(getPixelSizeY()); - Unit unit = pixSizeY == null ? UNITS.MICROMETER : pixSizeY.unit(); - return PlaneInfoWrapper.getMinPosition(planesInfo, PlaneInfoWrapper::getPositionY, unit); + ome.units.quantity.Length pixSizeY = convertLength(getPixelSizeY()); + + Unit unit = pixSizeY == null ? MICROMETER : pixSizeY.unit(); + return PlaneInfoWrapper.getMinPosition(planesInfo, + PlaneInfoWrapper::getPositionY, + unit); } @@ -270,9 +276,12 @@ public Length getPositionY() { * @return See above. */ public Length getPositionZ() { - ome.units.quantity.Length pixSizeZ = convertLength(getPixelSizeZ()); - Unit unit = pixSizeZ == null ? UNITS.MICROMETER : pixSizeZ.unit(); - return PlaneInfoWrapper.getMinPosition(planesInfo, PlaneInfoWrapper::getPositionZ, unit); + ome.units.quantity.Length pixSizeZ = convertLength(getPixelSizeZ()); + + Unit unit = pixSizeZ == null ? MICROMETER : pixSizeZ.unit(); + return PlaneInfoWrapper.getMinPosition(planesInfo, + PlaneInfoWrapper::getPositionZ, + unit); } @@ -339,7 +348,8 @@ public int getSizeT() { boolean createRawDataFacility(Client client) throws ExecutionException { boolean created = false; if (rawDataFacility == null) { - rawDataFacility = client.getGateway().getFacility(RawDataFacility.class); + rawDataFacility = client.getGateway() + .getFacility(RawDataFacility.class); created = true; } return created; @@ -399,13 +409,25 @@ public double[][][][][] getAllPixels(Client client, Coordinates start = lim.getStart(); Coordinates size = lim.getSize(); - double[][][][][] tab = new double[size.getT()][size.getZ()][size.getC()][][]; - - for (int t = 0, posT = start.getT(); t < size.getT(); t++, posT++) { - for (int z = 0, posZ = start.getZ(); z < size.getZ(); z++, posZ++) { - for (int c = 0, posC = start.getC(); c < size.getC(); c++, posC++) { - Coordinates pos = new Coordinates(start.getX(), start.getY(), posC, posZ, posT); - tab[t][z][c] = getTile(client, pos, size.getX(), size.getY()); + int x0 = start.getX(); + int y0 = start.getY(); + int sx = size.getX(); + int sy = size.getY(); + + int startC = start.getC(); + int startZ = start.getZ(); + int startT = start.getT(); + int sizeC = size.getC(); + int sizeZ = size.getZ(); + int sizeT = size.getT(); + + double[][][][][] tab = new double[sizeT][sizeZ][sizeC][][]; + + for (int t = 0, posT = startT; t < sizeT; t++, posT++) { + for (int z = 0, posZ = startZ; z < sizeZ; z++, posZ++) { + for (int c = 0, posC = startC; c < sizeC; c++, posC++) { + Coordinates pos = new Coordinates(x0, y0, posC, posZ, posT); + tab[t][z][c] = getTile(client, pos, sx, sy); } } } @@ -433,8 +455,11 @@ public double[][][][][] getAllPixels(Client client, double[][] getTile(Client client, Coordinates start, int width, int height) throws AccessException, ExecutionException { boolean rdf = createRawDataFacility(client); - double[][] tile = ExceptionHandler.of(this, t -> t.getTileUnchecked(client, start, width, height)) - .rethrow(DataSourceException.class, AccessException::new, "Cannot read tile") + double[][] tile = ExceptionHandler.of(this, + t -> t.getTileUnchecked(client, start, width, height)) + .rethrow(DataSourceException.class, + AccessException::new, + "Cannot read tile") .get(); if (rdf) { destroyRawDataFacility(); @@ -524,13 +549,25 @@ public byte[][][][] getRawPixels(Client client, Coordinates start = lim.getStart(); Coordinates size = lim.getSize(); - byte[][][][] bytes = new byte[size.getT()][size.getZ()][size.getC()][]; - - for (int t = 0, posT = start.getT(); t < size.getT(); t++, posT++) { - for (int z = 0, posZ = start.getZ(); z < size.getZ(); z++, posZ++) { - for (int c = 0, posC = start.getC(); c < size.getC(); c++, posC++) { - Coordinates pos = new Coordinates(start.getX(), start.getY(), posC, posZ, posT); - bytes[t][z][c] = getRawTile(client, pos, size.getX(), size.getY(), bpp); + int x0 = start.getX(); + int y0 = start.getY(); + int startC = start.getC(); + int startZ = start.getZ(); + int startT = start.getT(); + + int sx = size.getX(); + int sy = size.getY(); + int sizeC = size.getC(); + int sizeZ = size.getZ(); + int sizeT = size.getT(); + + byte[][][][] bytes = new byte[sizeT][sizeZ][sizeC][]; + + for (int t = 0, posT = startT; t < sizeT; t++, posT++) { + for (int z = 0, posZ = startZ; z < sizeZ; z++, posZ++) { + for (int c = 0, posC = startC; c < sizeC; c++, posC++) { + Coordinates pos = new Coordinates(x0, y0, posC, posZ, posT); + bytes[t][z][c] = getRawTile(client, pos, sx, sy, bpp); } } } @@ -558,8 +595,11 @@ public byte[][][][] getRawPixels(Client client, byte[] getRawTile(Client client, Coordinates start, int width, int height, int bpp) throws AccessException, ExecutionException { boolean rdf = createRawDataFacility(client); - byte[] tile = ExceptionHandler.of(this, t -> t.getRawTileUnchecked(client, start, width, height, bpp)) - .rethrow(DataSourceException.class, AccessException::new, "Cannot read raw tile") + byte[] tile = ExceptionHandler.of(this, + t -> t.getRawTileUnchecked(client, start, width, height, bpp)) + .rethrow(DataSourceException.class, + AccessException::new, + "Cannot read raw tile") .get(); if (rdf) { destroyRawDataFacility(); diff --git a/src/main/java/fr/igred/omero/repository/PlateWrapper.java b/src/main/java/fr/igred/omero/repository/PlateWrapper.java index 4c2f67ab..6b413980 100644 --- a/src/main/java/fr/igred/omero/repository/PlateWrapper.java +++ b/src/main/java/fr/igred/omero/repository/PlateWrapper.java @@ -40,6 +40,7 @@ import static fr.igred.omero.exception.ExceptionHandler.call; import static java.util.Collections.singletonList; +import static java.util.stream.Collectors.toMap; /** @@ -205,7 +206,8 @@ public List getImages(Client client) return getWells(client).stream() .map(WellWrapper::getImages) .flatMap(Collection::stream) - .collect(Collectors.toMap(GenericObjectWrapper::getId, i -> i, (i1, i2) -> i1)) + .collect(toMap(GenericObjectWrapper::getId, + i -> i, (i1, i2) -> i1)) .values() .stream() .sorted(Comparator.comparing(GenericObjectWrapper::getId)) diff --git a/src/main/java/fr/igred/omero/repository/WellWrapper.java b/src/main/java/fr/igred/omero/repository/WellWrapper.java index 3a48a09e..c22b611b 100644 --- a/src/main/java/fr/igred/omero/repository/WellWrapper.java +++ b/src/main/java/fr/igred/omero/repository/WellWrapper.java @@ -124,7 +124,9 @@ public WellData asWellData() { * @return See above. */ public List getWellSamples() { - return wrap(data.getWellSamples(), WellSampleWrapper::new, w -> w.getImage().asDataObject().getSeries()); + return wrap(data.getWellSamples(), + WellSampleWrapper::new, + w -> w.getImage().asDataObject().getSeries()); } diff --git a/src/main/java/fr/igred/omero/roi/EllipseWrapper.java b/src/main/java/fr/igred/omero/roi/EllipseWrapper.java index afb9c858..d2962f76 100644 --- a/src/main/java/fr/igred/omero/roi/EllipseWrapper.java +++ b/src/main/java/fr/igred/omero/roi/EllipseWrapper.java @@ -24,6 +24,7 @@ import omero.gateway.model.EllipseData; import java.awt.geom.Ellipse2D; +import java.awt.geom.Rectangle2D; import java.awt.geom.RectangularShape; @@ -109,7 +110,10 @@ public void setText(String text) { */ @Override public java.awt.Shape toAWTShape() { - return new Ellipse2D.Double(getX() - getRadiusX(), getY() - getRadiusY(), 2 * getRadiusX(), 2 * getRadiusY()); + return new Ellipse2D.Double(getX() - getRadiusX(), + getY() - getRadiusY(), + 2 * getRadiusX(), + 2 * getRadiusY()); } @@ -231,14 +235,16 @@ public double[] getCoordinates() { */ public void setCoordinates(double[] coordinates) { if (coordinates == null) { - throw new IllegalArgumentException("EllipseData cannot set null coordinates."); + String error = "EllipseData cannot set null coordinates."; + throw new IllegalArgumentException(error); } else if (coordinates.length == 4) { data.setX(coordinates[0]); data.setY(coordinates[1]); data.setRadiusX(coordinates[2]); data.setRadiusY(coordinates[3]); } else { - throw new IllegalArgumentException("4 coordinates required for EllipseData."); + String error = "4 coordinates required for EllipseData."; + throw new IllegalArgumentException(error); } } @@ -279,8 +285,8 @@ public Roi toImageJ() { } p1.setTransform(toAWTTransform()); p2.setTransform(toAWTTransform()); - java.awt.geom.Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); - java.awt.geom.Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); double x1 = shape1.getX(); double y1 = shape1.getY(); diff --git a/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java b/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java index 74e8ae05..591fa66b 100644 --- a/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java +++ b/src/main/java/fr/igred/omero/roi/GenericShapeWrapper.java @@ -31,13 +31,11 @@ import ome.model.units.BigResult; import omero.gateway.model.AnnotationData; import omero.gateway.model.ShapeData; -import omero.gateway.model.ShapeSettingsData; import omero.model.AffineTransform; import omero.model.AffineTransformI; import omero.model.LengthI; import omero.model.ShapeAnnotationLink; import omero.model.ShapeAnnotationLinkI; -import omero.model.enums.UnitsLength; import java.awt.Color; import java.awt.Font; @@ -49,9 +47,19 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutionException; -import java.util.logging.Level; import java.util.logging.Logger; +import static java.awt.Color.YELLOW; +import static java.awt.Font.BOLD; +import static java.awt.Font.ITALIC; +import static java.awt.geom.AffineTransform.TYPE_IDENTITY; +import static java.util.logging.Level.WARNING; +import static omero.gateway.model.ShapeSettingsData.FONT_BOLD; +import static omero.gateway.model.ShapeSettingsData.FONT_BOLD_ITALIC; +import static omero.gateway.model.ShapeSettingsData.FONT_ITALIC; +import static omero.gateway.model.ShapeSettingsData.FONT_REGULAR; +import static omero.model.enums.UnitsLength.POINT; + /** * Generic class containing a ShapeData (or a subclass) object. @@ -165,11 +173,15 @@ private static double extractAngle(java.awt.geom.AffineTransform transform) { * @param ijRoi An ImageJ Roi. */ protected void copyFromIJRoi(ij.gui.Roi ijRoi) { - LengthI size = new LengthI(ijRoi.getStrokeWidth(), UnitsLength.POINT); - Color defaultStroke = Optional.ofNullable(Roi.getColor()).orElse(Color.YELLOW); - Color defaultFill = Optional.ofNullable(Roi.getDefaultFillColor()).orElse(TRANSPARENT); - Color stroke = Optional.ofNullable(ijRoi.getStrokeColor()).orElse(defaultStroke); - Color fill = Optional.ofNullable(ijRoi.getFillColor()).orElse(defaultFill); + LengthI size = new LengthI(ijRoi.getStrokeWidth(), POINT); + Color defaultStroke = Optional.ofNullable(Roi.getColor()) + .orElse(YELLOW); + Color defaultFill = Optional.ofNullable(Roi.getDefaultFillColor()) + .orElse(TRANSPARENT); + Color stroke = Optional.ofNullable(ijRoi.getStrokeColor()) + .orElse(defaultStroke); + Color fill = Optional.ofNullable(ijRoi.getFillColor()) + .orElse(defaultFill); data.getShapeSettings().setStrokeWidth(size); data.getShapeSettings().setStroke(stroke); data.getShapeSettings().setFill(fill); @@ -228,17 +240,17 @@ private void copyFromIJTextRoi(ij.gui.TextRoi text) { int style = font.getStyle(); - String styleName; - if (style == java.awt.Font.BOLD) { - styleName = ShapeSettingsData.FONT_BOLD; - } else if (style == java.awt.Font.ITALIC) { - styleName = ShapeSettingsData.FONT_ITALIC; - } else if (style == java.awt.Font.BOLD + java.awt.Font.ITALIC) { - styleName = ShapeSettingsData.FONT_BOLD_ITALIC; + String fontStyle; + if (style == BOLD) { + fontStyle = FONT_BOLD; + } else if (style == ITALIC) { + fontStyle = FONT_ITALIC; + } else if (style == BOLD + ITALIC) { + fontStyle = FONT_BOLD_ITALIC; } else { - styleName = ShapeSettingsData.FONT_REGULAR; + fontStyle = FONT_REGULAR; } - data.getShapeSettings().setFontStyle(styleName); + data.getShapeSettings().setFontStyle(fontStyle); data.getShapeSettings().setFontFamily(font.getFamily()); // Angle is negative and in degrees in IJ @@ -287,15 +299,16 @@ private void copyToIJTextRoi(ij.gui.TextRoi text) { text.setAngle(angle); String fontFamily = data.getShapeSettings().getFontFamily(); - int fontStyle = Font.PLAIN; - if (data.getShapeSettings().getFontStyle().equals(ShapeSettingsData.FONT_BOLD)) { - fontStyle = Font.BOLD; - } else if (data.getShapeSettings().getFontStyle().equals(ShapeSettingsData.FONT_ITALIC)) { - fontStyle = Font.ITALIC; - } else if (data.getShapeSettings().getFontStyle().equals(ShapeSettingsData.FONT_BOLD_ITALIC)) { - fontStyle = Font.BOLD + Font.ITALIC; + String fontStyle = data.getShapeSettings().getFontStyle(); + int style = Font.PLAIN; + if (FONT_BOLD.equals(fontStyle)) { + style = BOLD; + } else if (FONT_ITALIC.equals(fontStyle)) { + style = ITALIC; + } else if (FONT_BOLD_ITALIC.equals(fontStyle)) { + style = BOLD + ITALIC; } - text.setFont(new Font(fontFamily, fontStyle, (int) getFontSize())); + text.setFont(new Font(fontFamily, style, (int) getFontSize())); } @@ -402,10 +415,10 @@ String getCZT() { public double getFontSize() { double fontSize = Double.NaN; try { - fontSize = data.getShapeSettings().getFontSize(UnitsLength.POINT).getValue(); + fontSize = data.getShapeSettings().getFontSize(POINT).getValue(); } catch (BigResult bigResult) { - Logger.getLogger(getClass().getName()) - .log(Level.WARNING, "Error while getting font size from ShapeData.", bigResult); + String msg = "Error while getting font size from ShapeData."; + Logger.getLogger(getClass().getName()).log(WARNING, msg, bigResult); } return fontSize; } @@ -417,7 +430,7 @@ public double getFontSize() { * @param value The font size (in typography points) */ public void setFontSize(double value) { - LengthI size = new LengthI(value, UnitsLength.POINT); + LengthI size = new LengthI(value, POINT); data.getShapeSettings().setFontSize(size); } @@ -547,7 +560,7 @@ public java.awt.geom.AffineTransform toAWTTransform() { * @return A new transformed {@link java.awt.Shape}. */ public java.awt.Shape createTransformedAWTShape() { - if (toAWTTransform().getType() == java.awt.geom.AffineTransform.TYPE_IDENTITY) { + if (toAWTTransform().getType() == TYPE_IDENTITY) { return toAWTShape(); } else { return toAWTTransform().createTransformedShape(toAWTShape()); @@ -586,7 +599,7 @@ public RectangleWrapper getBoundingBox() { * @return An ImageJ ROI. */ public Roi toImageJ() { - Roi roi = new ij.gui.ShapeRoi(createTransformedAWTShape()).trySimplify(); + Roi roi = new ShapeRoi(createTransformedAWTShape()).trySimplify(); copyToIJRoi(roi); return roi; } diff --git a/src/main/java/fr/igred/omero/roi/LineWrapper.java b/src/main/java/fr/igred/omero/roi/LineWrapper.java index 7511d76d..82451969 100644 --- a/src/main/java/fr/igred/omero/roi/LineWrapper.java +++ b/src/main/java/fr/igred/omero/roi/LineWrapper.java @@ -25,6 +25,7 @@ import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; +import java.awt.geom.Rectangle2D; /** @@ -238,14 +239,16 @@ public double[] getCoordinates() { */ public void setCoordinates(double[] coordinates) { if (coordinates == null) { - throw new IllegalArgumentException("LineData cannot set null coordinates."); + String msg = "LineData cannot set null coordinates."; + throw new IllegalArgumentException(msg); } else if (coordinates.length == 4) { data.setX1(coordinates[0]); data.setY1(coordinates[1]); data.setX2(coordinates[2]); data.setY2(coordinates[3]); } else { - throw new IllegalArgumentException("4 coordinates required for LineData."); + String msg = "4 coordinates required for LineData."; + throw new IllegalArgumentException(msg); } } @@ -265,8 +268,8 @@ public Roi toImageJ() { p2.setTransform(transform); } - java.awt.geom.Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); - java.awt.geom.Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); String start = data.getShapeSettings().getMarkerStart(); String end = data.getShapeSettings().getMarkerEnd(); diff --git a/src/main/java/fr/igred/omero/roi/MaskWrapper.java b/src/main/java/fr/igred/omero/roi/MaskWrapper.java index ee2fa16e..6bd2e15c 100644 --- a/src/main/java/fr/igred/omero/roi/MaskWrapper.java +++ b/src/main/java/fr/igred/omero/roi/MaskWrapper.java @@ -74,11 +74,12 @@ public MaskWrapper(ImageRoi imageRoi) { data.setMask(ip.getIntArray()); ip.flipVertical(); - Color lut = new Color(ip.getCurrentColorModel().getRGB((int) ip.getMax())); - int r = lut.getRed(); - int g = lut.getGreen(); - int b = lut.getBlue(); - int a = (int) (imageRoi.getOpacity() * MAX_UINT8); + Color lut = new Color(ip.getCurrentColorModel() + .getRGB((int) ip.getMax())); + int r = lut.getRed(); + int g = lut.getGreen(); + int b = lut.getBlue(); + int a = (int) (imageRoi.getOpacity() * MAX_UINT8); data.setText(imageRoi.getName()); super.copyFromIJRoi(imageRoi); @@ -317,14 +318,16 @@ public double[] getCoordinates() { */ public void setCoordinates(double[] coordinates) { if (coordinates == null) { - throw new IllegalArgumentException("MaskData cannot set null coordinates."); + String msg = "MaskData cannot set null coordinates."; + throw new IllegalArgumentException(msg); } else if (coordinates.length == 4) { data.setX(coordinates[0]); data.setY(coordinates[1]); data.setWidth(coordinates[2]); data.setHeight(coordinates[3]); } else { - throw new IllegalArgumentException("4 coordinates required for MaskData."); + String msg = "4 coordinates required for MaskData."; + throw new IllegalArgumentException(msg); } } @@ -352,8 +355,8 @@ public Roi toImageJ() { p1.setTransform(transform); p2.setTransform(transform); - java.awt.geom.Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); - java.awt.geom.Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); double x1 = shape1.getX(); double y1 = shape1.getY(); diff --git a/src/main/java/fr/igred/omero/roi/PointWrapper.java b/src/main/java/fr/igred/omero/roi/PointWrapper.java index cb1362ef..323cb583 100644 --- a/src/main/java/fr/igred/omero/roi/PointWrapper.java +++ b/src/main/java/fr/igred/omero/roi/PointWrapper.java @@ -167,12 +167,14 @@ public double[] getCoordinates() { */ public void setCoordinates(double[] coordinates) { if (coordinates == null) { - throw new IllegalArgumentException("PointData cannot set null coordinates."); + String msg = "PointData cannot set null coordinates."; + throw new IllegalArgumentException(msg); } else if (coordinates.length == 2) { data.setX(coordinates[0]); data.setY(coordinates[1]); } else { - throw new IllegalArgumentException("2 coordinates required for PointData."); + String msg = "2 coordinates required for PointData."; + throw new IllegalArgumentException(msg); } } diff --git a/src/main/java/fr/igred/omero/roi/PolygonWrapper.java b/src/main/java/fr/igred/omero/roi/PolygonWrapper.java index 68546450..9edc881e 100644 --- a/src/main/java/fr/igred/omero/roi/PolygonWrapper.java +++ b/src/main/java/fr/igred/omero/roi/PolygonWrapper.java @@ -65,7 +65,8 @@ public PolygonWrapper(Roi ijRoi) { 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]))); + IntStream.range(0, x.length) + .forEach(i -> points.add(new Point2D.Double(x[i], y[i]))); data.setPoints(points); data.setText(ijRoi.getName()); diff --git a/src/main/java/fr/igred/omero/roi/PolylineWrapper.java b/src/main/java/fr/igred/omero/roi/PolylineWrapper.java index 65663f21..f06bbbfb 100644 --- a/src/main/java/fr/igred/omero/roi/PolylineWrapper.java +++ b/src/main/java/fr/igred/omero/roi/PolylineWrapper.java @@ -64,7 +64,8 @@ public PolylineWrapper(Roi ijRoi) { 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]))); + IntStream.range(0, x.length) + .forEach(i -> points.add(new Point2D.Double(x[i], y[i]))); data.setPoints(points); data.setText(ijRoi.getName()); diff --git a/src/main/java/fr/igred/omero/roi/ROIWrapper.java b/src/main/java/fr/igred/omero/roi/ROIWrapper.java index a73a3f0c..3b19f188 100644 --- a/src/main/java/fr/igred/omero/roi/ROIWrapper.java +++ b/src/main/java/fr/igred/omero/roi/ROIWrapper.java @@ -167,7 +167,9 @@ public static List fromImageJ(List ijRois) { * @return The converted list of OMERO ROIs. */ public static List fromImageJ(List ijRois, String property) { - return fromImageJ(ijRois, property, ROIWrapper::new, GenericShapeWrapper::fromImageJ); + return fromImageJ(ijRois, property, + ROIWrapper::new, + GenericShapeWrapper::fromImageJ); } @@ -209,7 +211,10 @@ private static List fromImageJ(List ijRois, } rois4D.forEach((id, roi) -> roi.setName(names.get(id))); shape2roi.forEach((key, value) -> value.addShapes(converter.apply(ijRois.get(key)))); - return shape2roi.values().stream().distinct().collect(Collectors.toList()); + return shape2roi.values() + .stream() + .distinct() + .collect(Collectors.toList()); } @@ -254,7 +259,10 @@ public static List toImageJ(Collection rois, S final int maxGroups = 255; groupRois = groupRois && rois.size() < maxGroups && IJ.getVersion().compareTo("1.52t") >= 0; - int nShapes = rois.stream().map(GenericObjectWrapper::asDataObject).mapToInt(ROIData::getShapeCount).sum(); + int nShapes = rois.stream() + .map(GenericObjectWrapper::asDataObject) + .mapToInt(ROIData::getShapeCount) + .sum(); List ijRois = new ArrayList<>(nShapes); diff --git a/src/main/java/fr/igred/omero/roi/RectangleWrapper.java b/src/main/java/fr/igred/omero/roi/RectangleWrapper.java index df2d6210..fcad3f1d 100644 --- a/src/main/java/fr/igred/omero/roi/RectangleWrapper.java +++ b/src/main/java/fr/igred/omero/roi/RectangleWrapper.java @@ -230,14 +230,16 @@ public double[] getCoordinates() { */ public void setCoordinates(double[] coordinates) { if (coordinates == null) { - throw new IllegalArgumentException("RectangleData cannot set null coordinates."); + String msg = "RectangleData cannot set null coordinates."; + throw new IllegalArgumentException(msg); } else if (coordinates.length == 4) { data.setX(coordinates[0]); data.setY(coordinates[1]); data.setWidth(coordinates[2]); data.setHeight(coordinates[3]); } else { - throw new IllegalArgumentException("4 coordinates required for RectangleData."); + String msg = "4 coordinates required for RectangleData."; + throw new IllegalArgumentException(msg); } } @@ -260,8 +262,8 @@ public Roi toImageJ() { p1.setTransform(transform); p2.setTransform(transform); - java.awt.geom.Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); - java.awt.geom.Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape1 = p1.createTransformedAWTShape().getBounds2D(); + Rectangle2D shape2 = p2.createTransformedAWTShape().getBounds2D(); double x1 = shape1.getX(); double y1 = shape1.getY(); diff --git a/src/main/java/fr/igred/omero/roi/ShapeList.java b/src/main/java/fr/igred/omero/roi/ShapeList.java index f9fe30f7..7c70ecea 100644 --- a/src/main/java/fr/igred/omero/roi/ShapeList.java +++ b/src/main/java/fr/igred/omero/roi/ShapeList.java @@ -18,13 +18,14 @@ package fr.igred.omero.roi; -import fr.igred.omero.util.Wrapper; import omero.gateway.model.ShapeData; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import static fr.igred.omero.util.Wrapper.wrap; + /** List of GenericShapeWrapper objects */ public class ShapeList extends ArrayList> { @@ -61,7 +62,9 @@ public ShapeList(int initialCapacity) { * @return See above. */ public > List getElementsOf(Class clazz) { - return stream().filter(clazz::isInstance).map(clazz::cast).collect(Collectors.toList()); + return stream().filter(clazz::isInstance) + .map(clazz::cast) + .collect(Collectors.toList()); } @@ -76,8 +79,7 @@ public boolean add(ShapeData shape) { boolean added; try { - GenericShapeWrapper wrapper = Wrapper.wrap(shape); - added = add(wrapper); + added = add(wrap(shape)); } catch (IllegalArgumentException e) { added = false; } diff --git a/src/main/java/fr/igred/omero/roi/TextWrapper.java b/src/main/java/fr/igred/omero/roi/TextWrapper.java index ad2568ce..34ce602b 100644 --- a/src/main/java/fr/igred/omero/roi/TextWrapper.java +++ b/src/main/java/fr/igred/omero/roi/TextWrapper.java @@ -179,12 +179,14 @@ public double[] getCoordinates() { */ public void setCoordinates(double[] coordinates) { if (coordinates == null) { - throw new IllegalArgumentException("TextData cannot set null coordinates."); + String msg = "TextData cannot set null coordinates."; + throw new IllegalArgumentException(msg); } else if (coordinates.length == 2) { data.setX(coordinates[0]); data.setY(coordinates[1]); } else { - throw new IllegalArgumentException("2 coordinates required for TextData."); + String msg = "2 coordinates required for TextData."; + throw new IllegalArgumentException(msg); } } diff --git a/src/main/java/fr/igred/omero/util/LibraryChecker.java b/src/main/java/fr/igred/omero/util/LibraryChecker.java index 1de59670..7ebbd4e4 100644 --- a/src/main/java/fr/igred/omero/util/LibraryChecker.java +++ b/src/main/java/fr/igred/omero/util/LibraryChecker.java @@ -33,12 +33,12 @@ private LibraryChecker() { * @return {@code true} if the libraries are available, {@code false} otherwise. */ public static boolean areRequirementsAvailable() { - return isFormatsAPIAvailable() && - isOMEROModelAvailable() && - isOMEXMLAvailable() && - isOMECommonAvailable() && - isOMEROBlitzAvailable() && - isOMEROGatewayAvailable(); + return isFormatsAPIAvailable() + && isOMEROModelAvailable() + && isOMEXMLAvailable() + && isOMECommonAvailable() + && isOMEROBlitzAvailable() + && isOMEROGatewayAvailable(); } diff --git a/src/main/java/fr/igred/omero/util/Wrapper.java b/src/main/java/fr/igred/omero/util/Wrapper.java index 0395cd05..67d761ef 100644 --- a/src/main/java/fr/igred/omero/util/Wrapper.java +++ b/src/main/java/fr/igred/omero/util/Wrapper.java @@ -89,7 +89,9 @@ /** * Utility class to convert DataObjects dynamically. */ -@SuppressWarnings({"OverlyCoupledClass", "unchecked", "IfStatementWithTooManyBranches"}) +@SuppressWarnings({"OverlyCoupledClass", + "unchecked", + "IfStatementWithTooManyBranches"}) public final class Wrapper { private static final String UNKNOWN_TYPE = "Unknown type: %s"; diff --git a/src/test/java/fr/igred/omero/BasicTest.java b/src/test/java/fr/igred/omero/BasicTest.java index f56df760..afc7519a 100644 --- a/src/test/java/fr/igred/omero/BasicTest.java +++ b/src/test/java/fr/igred/omero/BasicTest.java @@ -30,6 +30,9 @@ import java.util.Random; import java.util.logging.Logger; +import static java.lang.String.format; +import static java.util.logging.Logger.getLogger; + @ExtendWith(LoggingExtension.class) public abstract class BasicTest { @@ -40,7 +43,9 @@ public abstract class BasicTest { 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()); + protected static final Logger logger = getLogger(MethodHandles.lookup() + .lookupClass() + .getName()); protected static final String HOST = "omero"; protected static final int PORT = 4064; @@ -71,7 +76,8 @@ protected static File createFile(String filename) throws IOException { File file = new File(tmpdir + File.separator + filename); if (!file.createNewFile()) { - logger.severe("\"" + file.getCanonicalPath() + "\" could not be created."); + String template = "\"%s\" could not be created."; + logger.severe(format(template, file.getCanonicalPath())); } return file; } @@ -95,10 +101,12 @@ protected static void removeFile(File file) throws IOException { File parent = file.getParentFile(); if (file.delete()) { if (!parent.delete()) { - logger.warning("\"" + parent.getCanonicalPath() + "\" could not be deleted."); + String template = "\"%s\" could not be deleted."; + logger.warning(format(template, parent.getCanonicalPath())); } } else { - logger.severe("\"" + file.getCanonicalPath() + "\" could not be deleted."); + String template = "\"%s\" could not be deleted."; + logger.severe(format(template, file.getCanonicalPath())); } } diff --git a/src/test/java/fr/igred/omero/ClientTest.java b/src/test/java/fr/igred/omero/ClientTest.java index f90fe637..cbf551f9 100644 --- a/src/test/java/fr/igred/omero/ClientTest.java +++ b/src/test/java/fr/igred/omero/ClientTest.java @@ -88,10 +88,10 @@ void testCreateAndDeleteProject() throws Exception { ProjectWrapper project = new ProjectWrapper(client, name, ""); - long newId = project.getId(); - assertEquals(name, client.getProject(newId).getName()); - client.delete(client.getProject(newId)); - assertThrows(NoSuchElementException.class, () -> client.getProject(newId)); + long id = project.getId(); + assertEquals(name, client.getProject(id).getName()); + client.delete(client.getProject(id)); + assertThrows(NoSuchElementException.class, () -> client.getProject(id)); } @@ -169,16 +169,21 @@ void testGetImagesKey() throws Exception { @Test void testGetImagesKeyValue() throws Exception { - List images = client.getImagesWithKeyValuePair("testKey1", "testValue1"); + String key = "testKey1"; + String val = "testValue1"; + + List images = client.getImagesWithKeyValuePair(key, val); assertEquals(2, images.size()); - List images2 = client.getImagesPairKeyValue("testKey1", "testValue1"); + List images2 = client.getImagesPairKeyValue(key, val); assertEquals(2, images2.size()); } @Test void testGetImagesFromNames() throws Exception { - List images = client.getImages(PROJECT1.name, DATASET1.name, IMAGE1.name); + List images = client.getImages(PROJECT1.name, + DATASET1.name, + IMAGE1.name); assertEquals(2, images.size()); } diff --git a/src/test/java/fr/igred/omero/ConnectionTest.java b/src/test/java/fr/igred/omero/ConnectionTest.java index 0c2daa1d..16b6be4a 100644 --- a/src/test/java/fr/igred/omero/ConnectionTest.java +++ b/src/test/java/fr/igred/omero/ConnectionTest.java @@ -30,10 +30,11 @@ class ConnectionTest extends BasicTest { @Test void testDisconnect() { + String expected = "Client{host=null, groupID=-1, userID=-1, connected=false}"; Client testRoot = new Client(); testRoot.disconnect(); assertFalse(testRoot.isConnected()); - assertEquals("Client{host=null, groupID=-1, userID=-1, connected=false}", testRoot.toString()); + assertEquals(expected, testRoot.toString()); } @@ -52,8 +53,9 @@ void testSessionConnect() throws ServiceException { @Test void testRootConnection() throws ServiceException { + char[] password = "omero".toCharArray(); Client testRoot = new Client(); - testRoot.connect(HOST, PORT, ROOT.name, "omero".toCharArray(), GROUP1.id); + testRoot.connect(HOST, PORT, ROOT.name, password, GROUP1.id); long id = testRoot.getId(); long groupId = testRoot.getCurrentGroupId(); try { @@ -67,8 +69,8 @@ void testRootConnection() throws ServiceException { @Test void testUserConnection() throws ServiceException { - String toString = String.format("Client{host=%s, groupID=%d, userID=%s, connected=true}", - HOST, GROUP1.id, USER1.id); + String template = "Client{host=%s, groupID=%d, userID=%s, connected=true}"; + String toString = String.format(template, HOST, GROUP1.id, USER1.id); Client testUser = new Client(); assertFalse(testUser.isConnected()); diff --git a/src/test/java/fr/igred/omero/LoggingExtension.java b/src/test/java/fr/igred/omero/LoggingExtension.java index 239da804..bad4e460 100644 --- a/src/test/java/fr/igred/omero/LoggingExtension.java +++ b/src/test/java/fr/igred/omero/LoggingExtension.java @@ -27,7 +27,6 @@ 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; @@ -37,6 +36,8 @@ import static fr.igred.omero.BasicTest.ANSI_RED; import static fr.igred.omero.BasicTest.ANSI_RESET; import static fr.igred.omero.BasicTest.ANSI_YELLOW; +import static java.lang.String.format; +import static java.nio.charset.StandardCharsets.UTF_8; public class LoggingExtension implements TestWatcher, BeforeTestExecutionCallback, BeforeAllCallback, AfterAllCallback { @@ -58,6 +59,15 @@ public class LoggingExtension implements TestWatcher, BeforeTestExecutionCallbac private long start = System.currentTimeMillis(); + /** + * Output to console. + */ + private static void showOutputs() { + System.setOut(output); + System.setErr(error); + } + + /** * Callback that is invoked once before all tests in the current container. * @@ -66,14 +76,22 @@ public class LoggingExtension implements TestWatcher, BeforeTestExecutionCallbac @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"); + 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"); + String logPath = "target" + File.separator + + "logs" + File.separator + + klass + ".log"; + + File file = new File(logPath); Files.createDirectories(file.toPath().getParent()); Files.deleteIfExists(file.toPath()); - logFile = new PrintStream(Files.newOutputStream(file.toPath()), false, StandardCharsets.UTF_8.name()); + + logFile = new PrintStream(Files.newOutputStream(file.toPath()), + false, + UTF_8.name()); } @@ -117,7 +135,10 @@ public void beforeTestExecution(ExtensionContext context) { @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); + + String method = context.getRequiredTestMethod().getName(); + String status = "DISABLED"; + logStatus(method, context.getDisplayName(), status, ANSI_BLUE, time); } @@ -132,7 +153,10 @@ public void testDisabled(ExtensionContext context, Optional reason) { @Override public void testSuccessful(ExtensionContext context) { float time = (float) (System.currentTimeMillis() - start) / 1000; - logStatus(context.getRequiredTestMethod().getName(), context.getDisplayName(), "SUCCEEDED", ANSI_GREEN, time); + + String method = context.getRequiredTestMethod().getName(); + String status = "SUCCEEDED"; + logStatus(method, context.getDisplayName(), status, ANSI_GREEN, time); } @@ -148,7 +172,10 @@ public void testSuccessful(ExtensionContext context) { @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); + + String method = context.getRequiredTestMethod().getName(); + String status = "ABORTED"; + logStatus(method, context.getDisplayName(), status, ANSI_YELLOW, time); } @@ -164,7 +191,10 @@ public void testAborted(ExtensionContext context, Throwable cause) { @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); + + String method = context.getRequiredTestMethod().getName(); + String status = "FAILED"; + logStatus(method, context.getDisplayName(), status, ANSI_RED, time); } @@ -179,21 +209,12 @@ public void testFailed(ExtensionContext context, Throwable cause) { 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)); + String name = format("%s %s", methodName, displayName); + logger.info(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. */ diff --git a/src/test/java/fr/igred/omero/RootTest.java b/src/test/java/fr/igred/omero/RootTest.java index 52a428f2..a6c1f412 100644 --- a/src/test/java/fr/igred/omero/RootTest.java +++ b/src/test/java/fr/igred/omero/RootTest.java @@ -22,8 +22,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import java.util.logging.Level; - +import static java.lang.String.format; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeFalse; @@ -37,12 +38,14 @@ public abstract class RootTest extends BasicTest { public void setUp() { boolean failed = false; try { - client.connect(HOST, PORT, ROOT.name, "omero".toCharArray(), GROUP1.id); + char[] password = "omero".toCharArray(); + client.connect(HOST, PORT, ROOT.name, password, GROUP1.id); 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); + String template = "%sConnection failed.%s"; + logger.log(SEVERE, format(template, ANSI_RED, ANSI_RESET), e); } assumeFalse(failed, "Connection failed."); } @@ -53,7 +56,8 @@ public void cleanUp() { try { client.disconnect(); } catch (RuntimeException e) { - logger.log(Level.WARNING, String.format("%sDisconnection failed.%s", ANSI_YELLOW, ANSI_RESET), e); + String template = "%sDisconnection failed.%s"; + logger.log(WARNING, format(template, 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 1034a93f..f1fb30b7 100644 --- a/src/test/java/fr/igred/omero/SudoTest.java +++ b/src/test/java/fr/igred/omero/SudoTest.java @@ -89,9 +89,10 @@ void testSudoTag() throws Exception { @Test void sudoImport() throws Exception { String filename = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=256&sizeY=512.fake"; + char[] password = "password4".toCharArray(); Client client4 = new Client(); - client4.connect(HOST, PORT, "testUser4", "password4".toCharArray(), 6L); + client4.connect(HOST, PORT, "testUser4", password, 6L); assertEquals(5L, client4.getId()); Client client3 = client4.sudoGetUser("testUser3"); @@ -120,6 +121,7 @@ void sudoImport() throws Exception { client3.disconnect(); client4.disconnect(); } catch (RuntimeException ignored) { + // DO NOTHING } } diff --git a/src/test/java/fr/igred/omero/TestObject.java b/src/test/java/fr/igred/omero/TestObject.java index 3cacbf1c..93ef6122 100644 --- a/src/test/java/fr/igred/omero/TestObject.java +++ b/src/test/java/fr/igred/omero/TestObject.java @@ -34,7 +34,8 @@ public class TestObject { @Override public String toString() { - return String.format("TestObject{id=%d, name='%s', description='%s'}", id, name, description); + String template = "TestObject{id=%d, name='%s', description='%s'}"; + return String.format(template, id, name, description); } } diff --git a/src/test/java/fr/igred/omero/UserTest.java b/src/test/java/fr/igred/omero/UserTest.java index 8cdbe7fe..c0a12309 100644 --- a/src/test/java/fr/igred/omero/UserTest.java +++ b/src/test/java/fr/igred/omero/UserTest.java @@ -22,8 +22,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; -import java.util.logging.Level; - +import static java.lang.String.format; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assumptions.assumeFalse; @@ -37,12 +38,14 @@ public abstract class UserTest extends BasicTest { public void setUp() { boolean failed = false; try { - client.connect(HOST, PORT, USER1.name, "password".toCharArray(), GROUP1.id); + char[] password = "password".toCharArray(); + client.connect(HOST, PORT, USER1.name, password, GROUP1.id); 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); + String template = "%sConnection failed.%s"; + logger.log(SEVERE, format(template, ANSI_RED, ANSI_RESET), e); } assumeFalse(failed, "Connection failed."); } @@ -53,7 +56,8 @@ public void cleanUp() { try { client.disconnect(); } catch (RuntimeException e) { - logger.log(Level.WARNING, String.format("%sDisconnection failed.%s", ANSI_YELLOW, ANSI_RESET), e); + String template = "%sDisconnection failed.%s"; + logger.log(WARNING, format(template, ANSI_YELLOW, ANSI_RESET), e); } } diff --git a/src/test/java/fr/igred/omero/annotations/ImageJTableTest.java b/src/test/java/fr/igred/omero/annotations/ImageJTableTest.java index 4ef776dc..1338c94f 100644 --- a/src/test/java/fr/igred/omero/annotations/ImageJTableTest.java +++ b/src/test/java/fr/igred/omero/annotations/ImageJTableTest.java @@ -41,8 +41,9 @@ import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; -import java.util.logging.Level; +import static java.lang.String.format; +import static java.util.logging.Level.SEVERE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -111,9 +112,11 @@ public void setUp() { image = client.getImage(imageId); } catch (AccessException | RuntimeException | ExecutionException | ServiceException e) { failed = true; - logger.log(Level.SEVERE, String.format("%sCould not retrieve image.%s", ANSI_RED, ANSI_RESET), e); + String msg = "%sCould not retrieve image.%s"; + logger.log(SEVERE, format(msg, ANSI_RED, ANSI_RESET), e); } - assumeFalse(failed, String.format("Could not retrieve image with ID=%d.", IMAGE1.id)); + String error = "Could not retrieve image with ID=%d."; + assumeFalse(failed, format(error, IMAGE1.id)); } @@ -128,12 +131,13 @@ public void cleanUp() { } int nRois = image.getROIs(client).size(); if (nRois != 0) { - logger.log(Level.SEVERE, - String.format("%sROIs were not properly deleted.%s", ANSI_RED, ANSI_RESET)); + String msg = "%sROIs were not properly deleted.%s"; + logger.log(SEVERE, format(msg, ANSI_RED, ANSI_RESET)); } } catch (AccessException | ServiceException | OMEROServerError | ExecutionException | InterruptedException e) { - logger.log(Level.SEVERE, String.format("%sROIs were not properly deleted.%s", ANSI_RED, ANSI_RESET), e); + String msg = "%sROIs were not properly deleted.%s"; + logger.log(SEVERE, format(msg, ANSI_RED, ANSI_RESET), e); } } super.cleanUp(); @@ -471,14 +475,17 @@ void testCreateTableWithROINamesFromIJResults1() throws Exception { List newROIs = image.saveROIs(client, rois); List ijRois = ROIWrapper.toImageJ(newROIs); - String label1 = image.getName() + ":" + newROIs.get(0).getShapes().get(0).getText() + ":4"; - String label2 = image.getName() + ":" + newROIs.get(1).getShapes().get(0).getText() + ":10"; + String name1 = newROIs.get(0).getShapes().get(0).getText(); + String name2 = newROIs.get(1).getShapes().get(0).getText(); - ResultsTable results1 = createOneRowResultsTable(label1, volume1, unit1); - ResultsTable results2 = createOneRowResultsTable(label2, volume2, unit2); + String label1 = image.getName() + ":" + name1 + ":4"; + String label2 = image.getName() + ":" + name2 + ":10"; - TableWrapper table = new TableWrapper(client, results1, IMAGE1.id, ijRois); - table.addRows(client, results2, IMAGE1.id, ijRois); + ResultsTable res1 = createOneRowResultsTable(label1, volume1, unit1); + ResultsTable res2 = createOneRowResultsTable(label2, volume2, unit2); + + TableWrapper table = new TableWrapper(client, res1, IMAGE1.id, ijRois); + table.addRows(client, res2, IMAGE1.id, ijRois); image.addTable(client, table); int rowCount = table.getRowCount(); @@ -537,11 +544,11 @@ void testCreateTableWithROINamesFromIJResults2() throws Exception { String label1 = rois.get(0).getShapes().get(0).getText(); String label2 = rois.get(1).getShapes().get(0).getText(); - ResultsTable results1 = createOneRowResultsTable(label1, volume1, unit1); - ResultsTable results2 = createOneRowResultsTable(label2, volume2, unit2); + ResultsTable res1 = createOneRowResultsTable(label1, volume1, unit1); + ResultsTable res2 = createOneRowResultsTable(label2, volume2, unit2); - TableWrapper table = new TableWrapper(client, results1, IMAGE1.id, ijRois); - table.addRows(client, results2, IMAGE1.id, ijRois); + TableWrapper table = new TableWrapper(client, res1, IMAGE1.id, ijRois); + table.addRows(client, res2, IMAGE1.id, ijRois); image.addTable(client, table); int rowCount = table.getRowCount(); @@ -721,9 +728,10 @@ void testSaveTableAs() throws Exception { String vol1 = formatter.format(volume1); String vol2 = formatter.format(volume2); + String line = "\"%d\"\t\"%d\"\t\"%s\"\t\"%s\"\t\"%s\""; String line1 = "\"Image\"\t\"ROI\"\t\"Label\"\t\"Volume\"\t\"Volume_Unit\""; - String line2 = String.format("\"%d\"\t\"%d\"\t\"%s\"\t\"%s\"\t\"%s\"", imageId, roiId, label, vol1, unit1); - String line3 = String.format("\"%d\"\t\"%d\"\t\"%s\"\t\"%s\"\t\"%s\"", imageId, roiId, label, vol2, unit2); + String line2 = format(line, imageId, roiId, label, vol1, unit1); + String line3 = format(line, imageId, roiId, label, vol2, unit2); List expected = Arrays.asList(line1, line2, line3); @@ -764,16 +772,19 @@ void testAddRowsWithMismatch() throws Exception { List newROIs = image.saveROIs(client, rois); List ijRois = ROIWrapper.toImageJ(newROIs); - String label1 = image.getName() + ":" + newROIs.get(0).getShapes().get(0).getText() + ":4"; - String label2 = image.getName() + ":" + newROIs.get(1).getShapes().get(0).getText() + ":10"; + String name1 = newROIs.get(0).getShapes().get(0).getText(); + String name2 = newROIs.get(1).getShapes().get(0).getText(); - ResultsTable results1 = createOneRowResultsTable(label1, volume1, unit1); - ResultsTable results2 = createOneRowResultsTable(label2, volume2, unit2); + String label1 = image.getName() + ":" + name1 + ":4"; + String label2 = image.getName() + ":" + name2 + ":10"; - TableWrapper table = new TableWrapper(client, results1, IMAGE1.id, ijRois); + ResultsTable res1 = createOneRowResultsTable(label1, volume1, unit1); + ResultsTable res2 = createOneRowResultsTable(label2, volume2, unit2); + + TableWrapper table = new TableWrapper(client, res1, IMAGE1.id, ijRois); assertThrows(IllegalArgumentException.class, - () -> table.addRows(client, results2, null, ijRois)); + () -> table.addRows(client, res2, null, ijRois)); } } \ No newline at end of file diff --git a/src/test/java/fr/igred/omero/annotations/MapAnnotationTest.java b/src/test/java/fr/igred/omero/annotations/MapAnnotationTest.java index 1f064d80..df328610 100644 --- a/src/test/java/fr/igred/omero/annotations/MapAnnotationTest.java +++ b/src/test/java/fr/igred/omero/annotations/MapAnnotationTest.java @@ -54,7 +54,10 @@ void testGetSingleMapAnnotationByKey() throws Exception { @Test void testGetSingleMapAnnotationByKeyAndValue() throws Exception { - List maps = client.getMapAnnotations("testKey1", "testValue1"); + String key = "testKey1"; + String val = "testValue1"; + + List maps = client.getMapAnnotations(key, val); assertEquals(1, maps.size()); } diff --git a/src/test/java/fr/igred/omero/annotations/TableTest.java b/src/test/java/fr/igred/omero/annotations/TableTest.java index 14983c2e..c00a0b02 100644 --- a/src/test/java/fr/igred/omero/annotations/TableTest.java +++ b/src/test/java/fr/igred/omero/annotations/TableTest.java @@ -166,7 +166,8 @@ void testErrorTableFull() throws Exception { table.setRowCount(images.size() - 1); assertThrows(IndexOutOfBoundsException.class, - () -> images.forEach(img -> table.addRow(img.asDataObject(), img.getName()))); + () -> images.forEach(i -> table.addRow(i.asDataObject(), + i.getName()))); } @@ -175,7 +176,8 @@ void testErrorTableColumn() { TableWrapper table = new TableWrapper(2, "TableTest"); table.setColumn(0, "Image", ImageData.class); table.setColumn(1, "Name", String.class); - assertThrows(IndexOutOfBoundsException.class, () -> table.setColumn(2, "Id", Long.class)); + assertThrows(IndexOutOfBoundsException.class, + () -> table.setColumn(2, "Id", Long.class)); } @@ -189,7 +191,8 @@ void testErrorTableUninitialized() throws Exception { table.setColumn(0, "Image", ImageData.class); table.setColumn(1, "Name", String.class); assertThrows(IndexOutOfBoundsException.class, - () -> images.forEach(img -> table.addRow(img.asDataObject(), img.getName()))); + () -> images.forEach(i -> table.addRow(i.asDataObject(), + i.getName()))); } @@ -204,7 +207,7 @@ void testErrorTableNotEnoughArgs() throws Exception { table.setColumn(1, "Name", String.class); table.setRowCount(images.size()); assertThrows(IllegalArgumentException.class, - () -> images.forEach(img -> table.addRow(img.asImageData()))); + () -> images.forEach(i -> table.addRow(i.asImageData()))); } } \ No newline at end of file diff --git a/src/test/java/fr/igred/omero/annotations/TagSetTest.java b/src/test/java/fr/igred/omero/annotations/TagSetTest.java index d060ed6c..e35c233c 100644 --- a/src/test/java/fr/igred/omero/annotations/TagSetTest.java +++ b/src/test/java/fr/igred/omero/annotations/TagSetTest.java @@ -30,7 +30,10 @@ class TagSetTest extends UserTest { @Test void testCreateTagSet() throws Exception { - TagAnnotationWrapper tagSet = new TagSetWrapper(client, "tagset", "tagset description"); + String name = "tagset"; + String desc = "tagset description"; + + TagAnnotationWrapper tagSet = new TagSetWrapper(client, name, desc); client.delete(tagSet); assertTrue(tagSet.isTagSet()); } @@ -38,7 +41,10 @@ void testCreateTagSet() throws Exception { @Test void testLinkTagSet() throws Exception { - TagSetWrapper tagSet = new TagSetWrapper(client, "tagset", "LinkTagSet"); + String name = "tagset"; + String desc = "LinkTagSet"; + + TagSetWrapper tagSet = new TagSetWrapper(client, name, desc); tagSet.link(client, client.getTag(1L), client.getTag(2L)); int nTags = tagSet.getTags(client).size(); client.delete(tagSet); diff --git a/src/test/java/fr/igred/omero/annotations/TagTest.java b/src/test/java/fr/igred/omero/annotations/TagTest.java index 167764ae..001cbfc3 100644 --- a/src/test/java/fr/igred/omero/annotations/TagTest.java +++ b/src/test/java/fr/igred/omero/annotations/TagTest.java @@ -153,7 +153,10 @@ void testSetDescription() throws Exception { @Test void testIsTagSet() throws Exception { - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "tagset", "isTagSet"); + String name = "tagset"; + String desc = "isTagSet"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); tag.setNameSpace(TagAnnotationWrapper.NS_TAGSET); client.delete(tag); assertTrue(tag.isTagSet()); @@ -162,8 +165,12 @@ void testIsTagSet() throws Exception { @Test void testToTagSet() throws Exception { - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "tagset", "toTagSet"); - TagSetWrapper tagSet = tag.toTagSet(); + String name = "tagset"; + String desc = "toTagSet"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); + + TagSetWrapper tagSet = tag.toTagSet(); client.delete(tagSet); assertTrue(tag.isTagSet()); } @@ -171,9 +178,13 @@ void testToTagSet() throws Exception { @Test void testLinkTagSetToProject() throws Exception { - TagAnnotationWrapper tagSet = new TagSetWrapper(client, "tagset", "LinkTagSet"); + String name = "tagset"; + String desc = "LinkTagSet"; + + TagAnnotationWrapper tagSet = new TagSetWrapper(client, name, desc); ProjectWrapper project = client.getProject(PROJECT1.id); - assertThrows(IllegalArgumentException.class, () -> project.link(client, tagSet)); + assertThrows(IllegalArgumentException.class, + () -> project.link(client, tagSet)); client.delete(tagSet); } diff --git a/src/test/java/fr/igred/omero/exception/AccessExceptionTest.java b/src/test/java/fr/igred/omero/exception/AccessExceptionTest.java index eef9712d..4f36cbdf 100644 --- a/src/test/java/fr/igred/omero/exception/AccessExceptionTest.java +++ b/src/test/java/fr/igred/omero/exception/AccessExceptionTest.java @@ -38,8 +38,10 @@ import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; -import java.util.logging.Level; +import static java.lang.String.format; +import static java.util.logging.Level.SEVERE; +import static java.util.logging.Level.WARNING; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -58,14 +60,16 @@ void setUp() { boolean failed = false; client = new Client(); try { - client.connect(HOST, PORT, USER1.name, "password".toCharArray(), GROUP1.id); + char[] password = "password".toCharArray(); + client.connect(HOST, PORT, USER1.name, password, GROUP1.id); 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); + String template = "%sConnection failed.%s"; + logger.log(SEVERE, format(template, ANSI_RED, ANSI_RESET), e); } assumeFalse(failed, "Connection failed"); } @@ -76,7 +80,8 @@ void cleanUp() { try { client.disconnect(); } catch (RuntimeException e) { - logger.log(Level.WARNING, String.format("%sDisconnection failed.%s", ANSI_YELLOW, ANSI_RESET), e); + String template = "%sDisconnection failed.%s"; + logger.log(WARNING, format(template, ANSI_YELLOW, ANSI_RESET), e); } } @@ -96,7 +101,10 @@ void testAddTagToImageWrongUser() throws Exception { assertTrue(image.canChgrp()); assertTrue(image.canChown()); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "image tag", "tag attached to an image"); + String name = "image tag"; + String desc = "tag attached to an image"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); try { image.link(client, tag); @@ -120,7 +128,8 @@ void testFolderAddROIWithoutImage() throws Exception { roi.addShape(rectangle); roi.saveROI(client); - assertThrows(AccessException.class, () -> folder.addROIs(client, -1L, roi)); + assertThrows(AccessException.class, + () -> folder.addROIs(client, -1L, roi)); client.delete(folder); } @@ -139,7 +148,8 @@ void testSudoFailGetSingleProject() { @Test void testSudoFailGetProjectByName() { - assertThrows(AccessException.class, () -> sudo.getProjects("TestProject")); + assertThrows(AccessException.class, + () -> sudo.getProjects(PROJECT1.name)); } @@ -181,7 +191,8 @@ void testSudoFailGetSingleDataset() { @Test void testSudoFailGetDatasetByName() { - assertThrows(AccessException.class, () -> sudo.getDatasets("TestDataset")); + assertThrows(AccessException.class, + () -> sudo.getDatasets(DATASET1.name)); } @@ -199,7 +210,7 @@ void testSudoFailGetImage() { @Test void testSudoFailGetImagesName() { - assertThrows(AccessException.class, () -> sudo.getImages("image1.fake")); + assertThrows(AccessException.class, () -> sudo.getImages(IMAGE1.name)); } @@ -244,7 +255,8 @@ void testSudoFailAddKVPair() throws Exception { result1.add(new NamedValue("Test2 result1", "Value Test2")); MapAnnotationWrapper mapAnnotation1 = new MapAnnotationWrapper(result1); - assertThrows(AccessException.class, () -> image.addMapAnnotation(sudo, mapAnnotation1)); + assertThrows(AccessException.class, + () -> image.addMapAnnotation(sudo, mapAnnotation1)); } diff --git a/src/test/java/fr/igred/omero/meta/ExperimenterTest.java b/src/test/java/fr/igred/omero/meta/ExperimenterTest.java index 029b13d9..06925f4d 100644 --- a/src/test/java/fr/igred/omero/meta/ExperimenterTest.java +++ b/src/test/java/fr/igred/omero/meta/ExperimenterTest.java @@ -35,7 +35,8 @@ class ExperimenterTest extends RootTest { @Test void testGetWrongUser() { - assertThrows(NoSuchElementException.class, () -> client.getUser("nonexistent")); + String user = "nonexistent"; + assertThrows(NoSuchElementException.class, () -> client.getUser(user)); } @@ -53,7 +54,8 @@ void testGetUserById() throws Exception { @Test void testSudoWrongUser() { - assertThrows(NoSuchElementException.class, () -> client.sudoGetUser("nonexistent")); + String user = "nonexistent"; + assertThrows(NoSuchElementException.class, () -> client.sudoGetUser(user)); } diff --git a/src/test/java/fr/igred/omero/meta/GroupTest.java b/src/test/java/fr/igred/omero/meta/GroupTest.java index 9784c0f6..dedf628b 100644 --- a/src/test/java/fr/igred/omero/meta/GroupTest.java +++ b/src/test/java/fr/igred/omero/meta/GroupTest.java @@ -25,6 +25,7 @@ import java.util.List; import java.util.NoSuchElementException; +import static fr.igred.omero.meta.GroupWrapper.PERMISSIONS_GROUP_READ; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -33,7 +34,8 @@ class GroupTest extends RootTest { @Test void testGetWrongGroup() { - assertThrows(NoSuchElementException.class, () -> client.getGroup("nonexistent")); + String name = "nonexistent"; + assertThrows(NoSuchElementException.class, () -> client.getGroup(name)); } @@ -65,7 +67,7 @@ void testSetGroupName() throws Exception { @Test void testSetDescription() throws Exception { GroupWrapper group = client.getGroup("testGroup1"); - assertEquals(GroupWrapper.PERMISSIONS_GROUP_READ, group.getPermissionsLevel()); + assertEquals(PERMISSIONS_GROUP_READ, group.getPermissionsLevel()); group.setDescription("Test"); group.saveAndUpdate(client); assertEquals("Test", client.getGroup("testGroup1").getDescription()); diff --git a/src/test/java/fr/igred/omero/meta/PlaneInfoWrapperTest.java b/src/test/java/fr/igred/omero/meta/PlaneInfoWrapperTest.java index a5aea1dc..efa4c8af 100644 --- a/src/test/java/fr/igred/omero/meta/PlaneInfoWrapperTest.java +++ b/src/test/java/fr/igred/omero/meta/PlaneInfoWrapperTest.java @@ -67,7 +67,9 @@ void testGetMinPosition() throws Exception { pixels.loadPlanesInfo(client); List planes = pixels.getPlanesInfo(); - Length positionX = getMinPosition(planes, PlaneInfoWrapper::getPositionX, UNITS.NANOMETER); + Length positionX = getMinPosition(planes, + PlaneInfoWrapper::getPositionX, + UNITS.NANOMETER); assertEquals(100000, positionX.getValue()); assertEquals("nm", positionX.getSymbol()); } diff --git a/src/test/java/fr/igred/omero/repository/DatasetTest.java b/src/test/java/fr/igred/omero/repository/DatasetTest.java index 9fe5a9d7..a9af8a49 100644 --- a/src/test/java/fr/igred/omero/repository/DatasetTest.java +++ b/src/test/java/fr/igred/omero/repository/DatasetTest.java @@ -39,10 +39,11 @@ class DatasetTest extends UserTest { @Test void testCreateDatasetAndDeleteIt1() throws Exception { String name = "To delete"; + String desc = "Dataset which will be deleted"; ProjectWrapper project = client.getProject(PROJECT1.id); - Long id = project.addDataset(client, name, "Dataset which will be deleted").getId(); + Long id = project.addDataset(client, name, desc).getId(); DatasetWrapper dataset = client.getDataset(id); @@ -86,8 +87,9 @@ void testCopyDataset() throws Exception { ProjectWrapper project = client.getProject(2L); String name = "Will be deleted"; + String desc = "Dataset which will be deleted"; - Long id = project.addDataset(client, name, "Dataset which will be deleted").getId(); + Long id = project.addDataset(client, name, desc).getId(); DatasetWrapper newDataset = client.getDataset(id); @@ -124,7 +126,10 @@ void testDatasetBasic() throws Exception { void testAddTagToDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); + String name = "Dataset tag"; + String desc = "tag attached to a dataset"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); dataset.link(client, tag); @@ -141,7 +146,10 @@ void testAddTagToDataset() throws Exception { void testAddTagToDataset2() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - dataset.addTag(client, "Dataset tag", "tag attached to a dataset"); + String name = "Dataset tag"; + String desc = "tag attached to a dataset"; + + dataset.addTag(client, name, desc); List tags = client.getTags("Dataset tag"); assertEquals(1, tags.size()); @@ -157,7 +165,10 @@ void testAddTagToDataset2() throws Exception { void testAddTagIdToDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); + String name = "Dataset tag"; + String desc = "tag attached to a dataset"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); long tagId = tag.getId(); dataset.addTag(client, tagId); @@ -172,10 +183,14 @@ void testAddTagIdToDataset() throws Exception { void testAddTagsToDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); + String name = "Image tag"; + String[] names = {name + " 1", name + " 2", name + " 3", name + " 4"}; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, names[0], desc); + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, names[1], desc); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, names[2], desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, names[3], desc); dataset.addTags(client, tag1.getId(), tag2.getId(), tag3.getId(), tag4.getId()); @@ -195,10 +210,13 @@ void testAddTagsToDataset() throws Exception { void testAddTagsToDataset2() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); + String name = "Dataset tag"; + String desc = "tag attached to a dataset"; + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, name, desc); + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, name, desc); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, name, desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, name, desc); dataset.linkIfNotLinked(client, tag1, tag2, tag3, tag4); @@ -218,7 +236,10 @@ void testAddTagsToDataset2() throws Exception { void testAddAndRemoveTagFromDataset() throws Exception { DatasetWrapper dataset = client.getDataset(DATASET1.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a dataset"); + String name = "Dataset tag"; + String desc = "tag attached to a dataset"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); dataset.link(client, tag); @@ -234,7 +255,10 @@ void testAddAndRemoveTagFromDataset() throws Exception { @Test void testGetProjects() throws Exception { - assertEquals(PROJECT1.id, client.getImage(DATASET1.id).getProjects(client).get(0).getId()); + assertEquals(PROJECT1.id, client.getImage(DATASET1.id) + .getProjects(client) + .get(0) + .getId()); } @@ -365,8 +389,9 @@ void testSetDescription() throws Exception { @Test void testCreateOrphanedDatasetAndDeleteIt() throws Exception { String name = "To delete"; + String desc = "Dataset which will be deleted"; - DatasetWrapper dataset = new DatasetWrapper(name, "Dataset which will be deleted"); + DatasetWrapper dataset = new DatasetWrapper(name, desc); dataset.saveAndUpdate(client); long id = dataset.getId(); diff --git a/src/test/java/fr/igred/omero/repository/FolderTest.java b/src/test/java/fr/igred/omero/repository/FolderTest.java index 77573572..5deea768 100644 --- a/src/test/java/fr/igred/omero/repository/FolderTest.java +++ b/src/test/java/fr/igred/omero/repository/FolderTest.java @@ -263,7 +263,10 @@ void testFolder3() throws Exception { void testAddAndRemoveTagFromFolder() throws Exception { FolderWrapper folder = new FolderWrapper(client, "Test1"); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to a folder"); + String name = "Folder tag"; + String desc = "tag attached to a folder"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); folder.link(client, tag); diff --git a/src/test/java/fr/igred/omero/repository/ImageTest.java b/src/test/java/fr/igred/omero/repository/ImageTest.java index 3dc62f16..4d0211d7 100644 --- a/src/test/java/fr/igred/omero/repository/ImageTest.java +++ b/src/test/java/fr/igred/omero/repository/ImageTest.java @@ -66,33 +66,43 @@ class ImageTest extends UserTest { @Test void testGetProjects() throws Exception { - assertEquals(PROJECT1.id, client.getImage(IMAGE1.id).getProjects(client).get(0).getId()); + assertEquals(PROJECT1.id, client.getImage(IMAGE1.id) + .getProjects(client) + .get(0) + .getId()); } @Test void testGetDatasets() throws Exception { - assertEquals(DATASET1.id, client.getImage(IMAGE1.id).getDatasets(client).get(0).getId()); + assertEquals(DATASET1.id, client.getImage(IMAGE1.id) + .getDatasets(client) + .get(0) + .getId()); } @Test void testGetScreens() throws Exception { final long id = 5L; - assertEquals(SCREEN1.id, client.getImage(id).getScreens(client).get(0).getId()); + assertEquals(SCREEN1.id, + client.getImage(id).getScreens(client).get(0).getId()); } @Test void testGetPlates() throws Exception { final long id = 5L; - assertEquals(PLATE1.id, client.getImage(id).getPlates(client).get(0).getId()); + assertEquals(PLATE1.id, + client.getImage(id).getPlates(client).get(0).getId()); } @Test void testGetPlateAcquisitions() throws Exception { - PlateAcquisitionWrapper pa = client.getPlate(PLATE1.id).getPlateAcquisitions().get(0); + PlateAcquisitionWrapper pa = client.getPlate(PLATE1.id) + .getPlateAcquisitions() + .get(0); String name = pa.getName(); ImageWrapper image = pa.getImages(client).get(0); @@ -108,14 +118,17 @@ void testGetWells() throws Exception { WellWrapper well = client.getWell(wellId); long imageId = well.getWellSamples().get(0).getImage().getId(); - assertEquals(wellId, client.getImage(imageId).getWells(client).get(0).getId()); + assertEquals(wellId, + client.getImage(imageId).getWells(client).get(0).getId()); } @Test void testGetWellSamples() throws Exception { - final long wellId = 1L; - WellSampleWrapper sample = client.getWell(wellId).getWellSamples().get(0); + final long wellId = 1L; + WellSampleWrapper sample = client.getWell(wellId) + .getWellSamples() + .get(0); ImageWrapper image = sample.getImage(); image.reload(client); @@ -159,7 +172,8 @@ void testGetValue() throws Exception { @Test void testGetValueWrongKey() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); - assertThrows(NoSuchElementException.class, () -> image.getValue(client, "testKey")); + assertThrows(NoSuchElementException.class, + () -> image.getValue(client, "testKey")); } @@ -273,9 +287,11 @@ void testAddKeyValuePair4() throws Exception { String value = image.getValue(client, key1); client.delete(maps); + long diff = (maps.get(0).getLastModified().getTime() - ts.getTime()) / 1000; + assertEquals(2, maps.size()); assertEquals(NSCLIENTMAPANNOTATION.value, maps.get(0).getNameSpace()); - assertEquals(0, (maps.get(0).getLastModified().getTime() - ts.getTime()) / 1000); + assertEquals(0, diff); assertEquals(value1, value); } @@ -376,7 +392,8 @@ void testToImagePlus() throws Exception { ImageStatistics stats = difference.getStatistics(); assertEquals(0, (int) stats.max); - assertEquals(String.valueOf(IMAGE2.id), imp.getProp(ImageWrapper.IJ_ID_PROPERTY)); + assertEquals(String.valueOf(IMAGE2.id), + imp.getProp(ImageWrapper.IJ_ID_PROPERTY)); } @@ -390,7 +407,8 @@ void testGetImageChannel() throws Exception { @Test void testGetImageChannelError() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); - assertThrows(IndexOutOfBoundsException.class, () -> image.getChannelName(client, 6)); + assertThrows(IndexOutOfBoundsException.class, + () -> image.getChannelName(client, 6)); } @@ -398,7 +416,10 @@ void testGetImageChannelError() throws Exception { void testAddTagToImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "image tag", "tag attached to an image"); + String name = "Image tag"; + String desc = "tag attached to an image"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); image.link(client, tag); @@ -415,11 +436,14 @@ void testAddTagToImage() throws Exception { void testAddTagToImage2() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); - image.addTag(client, "image tag", "tag attached to an image"); + String name = "Image tag"; + String desc = "tag attached to an image"; - List tags = client.getTags("image tag"); + image.addTag(client, name, desc); + + List tags = client.getTags(name); client.delete(tags.get(0)); - List endTags = client.getTags("image tag"); + List endTags = client.getTags(name); assertEquals(1, tags.size()); assertEquals(0, endTags.size()); @@ -430,7 +454,10 @@ void testAddTagToImage2() throws Exception { void testAddTagIdToImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "image tag", "tag attached to an image"); + String name = "image tag"; + String desc = "tag attached to an image"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); image.addTag(client, tag.getId()); @@ -447,10 +474,14 @@ void testAddTagIdToImage() 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"); - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "Image tag 2", "tag attached to an image"); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Image tag 3", "tag attached to an image"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Image tag 4", "tag attached to an image"); + String name = "Image tag"; + String[] names = {name + " 1", name + " 2", name + " 3", name + " 4"}; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, names[0], desc); + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, names[1], desc); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, names[2], desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, names[3], desc); image.addTags(client, tag1.getId(), tag2.getId(), tag3.getId(), tag4.getId()); List tags = image.getTags(client); @@ -469,10 +500,14 @@ void testAddTagsToImage() 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"); - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "Image tag 2", "tag attached to an image"); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Image tag 3", "tag attached to an image"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Image tag 4", "tag attached to an image"); + String name = "Image tag"; + String[] names = {name + " 1", name + " 2", name + " 3", name + " 4"}; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, names[0], desc); + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, names[1], desc); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, names[2], desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, names[3], desc); image.linkIfNotLinked(client, tag1, tag2, tag3, tag4); List tags = image.getTags(client); @@ -491,10 +526,14 @@ void testAddTagsToImage2() throws Exception { void testAddNewTagsToImage() throws Exception { ImageWrapper image = client.getImage(IMAGE1.id); + String name = "Image tag"; + String[] names = {name + " 1", name + " 2"}; + String desc = "tag attached to a project"; + TagAnnotationWrapper tag1 = client.getTag(TAG1.id); TagAnnotationWrapper tag2 = client.getTag(TAG2.id); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Image tag 1", "tag attached to an image"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Image tag 2", "tag attached to an image"); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, names[0], desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, names[1], desc); image.linkIfNotLinked(client, tag1, tag2, tag3, tag4); List tags = image.getTags(client); @@ -512,7 +551,10 @@ void testAddNewTagsToImage() throws Exception { void testAddAndRemoveTagFromImage() throws Exception { ImageWrapper image = client.getImage(IMAGE2.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Dataset tag", "tag attached to an image"); + String name = "Image tag"; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); image.link(client, tag); @@ -579,8 +621,11 @@ void testAddFileImage() throws Exception { @Test void testGetCreated() throws Exception { - LocalDate created = client.getImage(IMAGE1.id).getCreated().toLocalDateTime().toLocalDate(); - LocalDate now = LocalDate.now(); + LocalDate created = client.getImage(IMAGE1.id) + .getCreated() + .toLocalDateTime() + .toLocalDate(); + LocalDate now = LocalDate.now(); assertEquals(now, created); } @@ -603,7 +648,9 @@ void testGetFormat() throws Exception { @Test void testGetChannel() throws Exception { - ChannelWrapper channel = client.getImage(IMAGE1.id).getChannels(client).get(0); + ChannelWrapper channel = client.getImage(IMAGE1.id) + .getChannels(client) + .get(0); assertEquals(0, channel.getIndex()); channel.setName("Foo channel"); assertEquals("Foo channel", channel.getName()); diff --git a/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java b/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java index 398251ad..4e7e6fec 100644 --- a/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java +++ b/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java @@ -81,7 +81,10 @@ void testAddTagToPlateAcquisition() throws Exception { PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Plate acq. tag", "tag attached to a plate acq."); + String name = "Plate acq. tag"; + String desc = "tag attached to a plate acq."; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); acq.link(client, tag); List taggedAcqs = tag.getPlateAcquisitions(client); @@ -106,11 +109,17 @@ void testSetName() throws Exception { String name2 = "New name"; acq.setName(name2); acq.saveAndUpdate(client); - assertEquals(name2, client.getPlate(PLATE1.id).getPlateAcquisitions().get(0).getName()); + assertEquals(name2, client.getPlate(PLATE1.id) + .getPlateAcquisitions() + .get(0) + .getName()); acq.setName(name); acq.saveAndUpdate(client); - assertEquals(name, client.getPlate(PLATE1.id).getPlateAcquisitions().get(0).getName()); + assertEquals(name, client.getPlate(PLATE1.id) + .getPlateAcquisitions() + .get(0) + .getName()); } @@ -124,11 +133,17 @@ void testSetDescription() throws Exception { String name2 = "New description"; acq.setDescription(name2); acq.saveAndUpdate(client); - assertEquals(name2, client.getPlate(PLATE1.id).getPlateAcquisitions().get(0).getDescription()); + assertEquals(name2, client.getPlate(PLATE1.id) + .getPlateAcquisitions() + .get(0) + .getDescription()); acq.setDescription(name); acq.saveAndUpdate(client); - assertEquals(name, client.getPlate(PLATE1.id).getPlateAcquisitions().get(0).getDescription()); + assertEquals(name, client.getPlate(PLATE1.id) + .getPlateAcquisitions() + .get(0) + .getDescription()); } diff --git a/src/test/java/fr/igred/omero/repository/PlateTest.java b/src/test/java/fr/igred/omero/repository/PlateTest.java index 057af118..4effb7b2 100644 --- a/src/test/java/fr/igred/omero/repository/PlateTest.java +++ b/src/test/java/fr/igred/omero/repository/PlateTest.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.NoSuchElementException; +import static java.lang.Double.MIN_VALUE; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -87,7 +88,10 @@ void testGetPlateAcquisitionsFromPlate() throws Exception { void testAddTagToPlate() throws Exception { PlateWrapper plate = client.getPlate(PLATE2.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Plate tag", "tag attached to a plate"); + String name = "Plate tag"; + String desc = "tag attached to a plate"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); plate.link(client, tag); List tags = plate.getTags(client); client.delete(tag); @@ -173,7 +177,8 @@ void testSetExternalIdentifier() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); plate.setExternalIdentifier(identifier); plate.saveAndUpdate(client); - assertEquals(identifier, client.getPlate(PLATE1.id).getExternalIdentifier()); + assertEquals(identifier, + client.getPlate(PLATE1.id).getExternalIdentifier()); } @@ -205,7 +210,7 @@ void testGetRowSequenceIndex() 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); + assertEquals(origin, plate.getWellOriginX(null).getValue(), MIN_VALUE); } @@ -213,7 +218,7 @@ void testGetWellOriginX() 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); + assertEquals(origin, plate.getWellOriginY(null).getValue(), 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 81332865..958f7488 100644 --- a/src/test/java/fr/igred/omero/repository/ProjectTest.java +++ b/src/test/java/fr/igred/omero/repository/ProjectTest.java @@ -30,6 +30,7 @@ import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE; import static fr.igred.omero.repository.GenericRepositoryObjectWrapper.ReplacePolicy.DELETE_ORPHANED; +import static java.lang.String.format; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -84,7 +85,10 @@ void testAddAndRemoveDataset() throws Exception { void testAddTagToProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); + String name = "Project tag"; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); project.addTag(client, tag); List tags = project.getTags(client); @@ -98,12 +102,12 @@ void testAddTagToProject() throws Exception { @Test void testAddTagToProject2() throws Exception { - final String name = "test"; - final String description = "test"; + String name = "Project tag"; + String desc = "tag attached to a project"; ProjectWrapper project = client.getProject(PROJECT1.id); - project.addTag(client, name, description); + project.addTag(client, name, desc); List tags = client.getTags(name); client.delete(tags.get(0)); List endTags = client.getTags(name); @@ -117,7 +121,10 @@ void testAddTagToProject2() throws Exception { void testAddTagIdToProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); + String name = "Project tag"; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); project.addTag(client, tag.getId()); List tags = project.getTags(client); @@ -133,10 +140,14 @@ void testAddTagIdToProject() 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"); - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "Project tag 2", "tag attached to a project"); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Project tag 3", "tag attached to a project"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Project tag 4", "tag attached to a project"); + String name = "Project tag"; + String[] names = {name + " 1", name + " 2", name + " 3", name + " 4"}; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, names[0], desc); + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, names[1], desc); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, names[2], desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, names[3], desc); project.addTags(client, tag1.getId(), tag2.getId(), tag3.getId(), tag4.getId()); List tags = project.getTags(client); @@ -155,10 +166,14 @@ void testAddTagsToProject() throws Exception { void testAddTagsToProject2() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); - TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); - TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); - TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); - TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); + String name = "Project tag"; + String[] names = {name + " 1", name + " 2", name + " 3", name + " 4"}; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag1 = new TagAnnotationWrapper(client, names[0], desc); + TagAnnotationWrapper tag2 = new TagAnnotationWrapper(client, names[1], desc); + TagAnnotationWrapper tag3 = new TagAnnotationWrapper(client, names[2], desc); + TagAnnotationWrapper tag4 = new TagAnnotationWrapper(client, names[3], desc); project.addTags(client, tag1, tag2, tag3, tag4); List tags = project.getTags(client); @@ -177,7 +192,10 @@ void testAddTagsToProject2() throws Exception { void testAddAndRemoveTagFromProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Project tag", "tag attached to a project"); + String name = "Project tag"; + String desc = "tag attached to a project"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); project.link(client, tag); List tags = project.getTags(client); project.unlink(client, tag); @@ -254,7 +272,10 @@ void testGetImagesKeyInProject() throws Exception { void testGetImagesPairKeyValueInProject() throws Exception { ProjectWrapper project = client.getProject(PROJECT1.id); - List images = project.getImagesPairKeyValue(client, "testKey1", "testValue1"); + String key = "testKey1"; + String val = "testValue1"; + + List images = project.getImagesPairKeyValue(client, key, val); assertEquals(2, images.size()); } @@ -275,7 +296,8 @@ void testSetName() throws Exception { long updated = project.getUpdated().getTime(); long now = System.currentTimeMillis(); - assertTrue(now - updated < 5000, String.format("Updated at: %d. Current time was: %d", updated, now)); + String msg = "Updated at: %d. Current time was: %d"; + assertTrue(now - updated < 5000, format(msg, updated, now)); assertEquals(name2, checkName2); assertEquals(name, client.getProject(PROJECT1.id).getName()); } @@ -290,18 +312,23 @@ void testSetDescription() throws Exception { String description2 = "NewName"; project.setDescription(description2); project.saveAndUpdate(client); - assertEquals(description2, client.getProject(PROJECT1.id).getDescription()); + assertEquals(description2, + client.getProject(PROJECT1.id).getDescription()); project.setDescription(description); project.saveAndUpdate(client); - assertEquals(description, client.getProject(PROJECT1.id).getDescription()); + assertEquals(description, + client.getProject(PROJECT1.id).getDescription()); } @Test void testCopyAnnotations() throws Exception { + String p2name = "CopyTest"; + String p2desc = "Copy annotations"; + ProjectWrapper project1 = client.getProject(PROJECT1.id); - ProjectWrapper project2 = new ProjectWrapper(client, "CopyTest", "Copy annotations"); + ProjectWrapper project2 = new ProjectWrapper(client, p2name, p2desc); File file = createRandomFile("test_project.txt"); @@ -309,7 +336,10 @@ void testCopyAnnotations() throws Exception { removeFile(file); assertNotEquals(0L, fileId); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "CopyTestTag", "Copy annotations"); + String name = "CopyTestTag"; + String desc = "Copy annotations"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); project1.link(client, tag); project1.addPairKeyValue(client, "CopyTest", "Annotation"); @@ -321,10 +351,14 @@ void testCopyAnnotations() throws Exception { project2.copyAnnotationLinks(client, project1); - assertEquals(project1.getTags(client).size(), project2.getTags(client).size()); - assertEquals(project1.getTables(client).size(), project2.getTables(client).size()); - assertEquals(project1.getFileAnnotations(client).size(), project2.getFileAnnotations(client).size()); - assertEquals(project1.getMapAnnotations(client).size(), project2.getMapAnnotations(client).size()); + assertEquals(project1.getTags(client).size(), + project2.getTags(client).size()); + assertEquals(project1.getTables(client).size(), + project2.getTables(client).size()); + assertEquals(project1.getFileAnnotations(client).size(), + project2.getFileAnnotations(client).size()); + assertEquals(project1.getMapAnnotations(client).size(), + project2.getMapAnnotations(client).size()); client.deleteFile(fileId); client.delete(tag); @@ -347,8 +381,11 @@ void testCopyAnnotations() throws Exception { @Test void testCopyFileAnnotation() throws Exception { + String p2name = "CopyTest"; + String p2desc = "Copy annotations"; + ProjectWrapper project1 = client.getProject(PROJECT1.id); - ProjectWrapper project2 = new ProjectWrapper(client, "CopyTest", "Copy file annotation"); + ProjectWrapper project2 = new ProjectWrapper(client, p2name, p2desc); File file = createRandomFile("test_project.txt"); @@ -373,8 +410,11 @@ void testCopyFileAnnotation() throws Exception { @Test void testReplaceAndUnlinkFile() throws Exception { - ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); - ProjectWrapper project2 = new ProjectWrapper(client, "ReplaceTest2", "Replace file annotation"); + String name = "ReplaceTest"; + String desc = "Replace file annotation"; + + ProjectWrapper project1 = new ProjectWrapper(client, name + "1", desc); + ProjectWrapper project2 = new ProjectWrapper(client, name + "2", desc); File file = createRandomFile("test_project.txt"); @@ -396,8 +436,11 @@ void testReplaceAndUnlinkFile() throws Exception { @Test void testReplaceAndDeleteFile() throws Exception { - ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); - ProjectWrapper project2 = new ProjectWrapper(client, "ReplaceTest2", "Replace file annotation"); + String name = "ReplaceTest"; + String desc = "Replace file annotation"; + + ProjectWrapper project1 = new ProjectWrapper(client, name + "1", desc); + ProjectWrapper project2 = new ProjectWrapper(client, name + "2", desc); File file = createRandomFile("test_project.txt"); @@ -418,8 +461,11 @@ void testReplaceAndDeleteFile() throws Exception { @Test void testReplaceAndDeleteOrphanedFile1() throws Exception { - ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); - ProjectWrapper project2 = new ProjectWrapper(client, "ReplaceTest2", "Replace file annotation"); + String name = "ReplaceTest"; + String desc = "Replace file annotation"; + + ProjectWrapper project1 = new ProjectWrapper(client, name + "1", desc); + ProjectWrapper project2 = new ProjectWrapper(client, name + "2", desc); File file = createRandomFile("test_project.txt"); @@ -441,18 +487,21 @@ void testReplaceAndDeleteOrphanedFile1() throws Exception { @Test void testReplaceAndDeleteOrphanedFile2() throws Exception { - ProjectWrapper project1 = new ProjectWrapper(client, "ReplaceTest1", "Replace file annotation"); + String name = "ReplaceTest"; + String desc = "Replace file annotation"; + + ProjectWrapper project = new ProjectWrapper(client, name, desc); File file = createRandomFile("test_project.txt"); - long fileId1 = project1.addFile(client, file); - assertEquals(1, project1.getFileAnnotations(client).size()); - long fileId2 = project1.addAndReplaceFile(client, file, DELETE_ORPHANED); - assertEquals(1, project1.getFileAnnotations(client).size()); + long fileId1 = project.addFile(client, file); + assertEquals(1, project.getFileAnnotations(client).size()); + long fileId2 = project.addAndReplaceFile(client, file, DELETE_ORPHANED); + assertEquals(1, project.getFileAnnotations(client).size()); assertNotEquals(fileId1, fileId2); removeFile(file); - client.delete(project1); + client.delete(project); client.deleteFile(fileId2); } diff --git a/src/test/java/fr/igred/omero/repository/ScreenTest.java b/src/test/java/fr/igred/omero/repository/ScreenTest.java index 0d27d54b..ff8ff609 100644 --- a/src/test/java/fr/igred/omero/repository/ScreenTest.java +++ b/src/test/java/fr/igred/omero/repository/ScreenTest.java @@ -76,7 +76,10 @@ void testGetPlatesFromScreen2() throws Exception { void testAddTagToScreen() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN2.id); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Screen tag", "tag attached to a screen"); + String name = "Screen tag"; + String desc = "tag attached to a screen"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); screen.link(client, tag); List tags = screen.getTags(client); client.delete(tag); @@ -172,7 +175,10 @@ void testImportImages() throws Exception { File f1 = createFile(filename1); File f2 = createFile(filename2); - ScreenWrapper screen = new ScreenWrapper(client, "Import", "test-import"); + String name = "Import"; + String desc = "test-import"; + + ScreenWrapper screen = new ScreenWrapper(client, name, desc); boolean imported = screen.importImages(client, f1.getAbsolutePath(), f2.getAbsolutePath()); screen.refresh(client); @@ -213,7 +219,10 @@ void testImportImage() throws Exception { File file = createFile(filename); - ScreenWrapper screen = new ScreenWrapper(client, "Import", "test-import"); + String name = "Import"; + String desc = "test-import"; + + ScreenWrapper screen = new ScreenWrapper(client, name, desc); List ids = screen.importImage(client, file.getAbsolutePath()); screen.reload(client); diff --git a/src/test/java/fr/igred/omero/repository/WellTest.java b/src/test/java/fr/igred/omero/repository/WellTest.java index 5c5d68af..84d96762 100644 --- a/src/test/java/fr/igred/omero/repository/WellTest.java +++ b/src/test/java/fr/igred/omero/repository/WellTest.java @@ -34,7 +34,10 @@ class WellTest extends UserTest { void testAddTagToWell() throws Exception { WellWrapper well = client.getWell(2L); - TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "Well tag", "tag attached to a well"); + String name = "Well tag"; + String desc = "tag attached to a well"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); well.link(client, tag); List tags = well.getTags(client); client.delete(tag); diff --git a/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java b/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java index 2876a873..747beec0 100644 --- a/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java +++ b/src/test/java/fr/igred/omero/roi/ROI2ImageJTest.java @@ -422,7 +422,10 @@ void convertText() { @ParameterizedTest(name = "{0}") - @ValueSource(ints = {Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD | Font.ITALIC}) + @ValueSource(ints = {Font.PLAIN, + Font.BOLD, + Font.ITALIC, + Font.BOLD | Font.ITALIC}) void convertText(int style) { Font font = new Font("Arial", style, 25); List roiList = new ArrayList<>(1); diff --git a/src/test/java/fr/igred/omero/roi/ROITest.java b/src/test/java/fr/igred/omero/roi/ROITest.java index 4006f0ef..5ed31352 100644 --- a/src/test/java/fr/igred/omero/roi/ROITest.java +++ b/src/test/java/fr/igred/omero/roi/ROITest.java @@ -25,9 +25,9 @@ import java.awt.geom.Point2D; import java.util.ArrayList; -import java.util.Collections; import java.util.List; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -50,7 +50,7 @@ void testAddTagToROI() throws Exception { roiWrapper.addShape(rectangle); } - roiWrapper = image.saveROIs(client, Collections.singletonList(roiWrapper)).get(0); + roiWrapper = image.saveROIs(client, singletonList(roiWrapper)).get(0); roiWrapper.addTag(client, "ROI Tag", "ROI tag test"); List tags = roiWrapper.getTags(client); diff --git a/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java b/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java index fe1c8751..5eb67109 100644 --- a/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java +++ b/src/test/java/fr/igred/omero/roi/ShapeErrorTest.java @@ -30,42 +30,48 @@ class ShapeErrorTest extends BasicTest { @Test void testPointNullCoordinates() { PointWrapper point = new PointWrapper(); - assertThrows(IllegalArgumentException.class, () -> point.setCoordinates(null)); + assertThrows(IllegalArgumentException.class, + () -> point.setCoordinates(null)); } @Test void testTextNullCoordinates() { TextWrapper text = new TextWrapper(); - assertThrows(IllegalArgumentException.class, () -> text.setCoordinates(null)); + assertThrows(IllegalArgumentException.class, + () -> text.setCoordinates(null)); } @Test void testRectangleNullCoordinates() { RectangleWrapper rectangle = new RectangleWrapper(); - assertThrows(IllegalArgumentException.class, () -> rectangle.setCoordinates(null)); + assertThrows(IllegalArgumentException.class, + () -> rectangle.setCoordinates(null)); } @Test void testMaskNullCoordinates() { MaskWrapper mask = new MaskWrapper(); - assertThrows(IllegalArgumentException.class, () -> mask.setCoordinates(null)); + assertThrows(IllegalArgumentException.class, + () -> mask.setCoordinates(null)); } @Test void testEllipseNullCoordinates() { EllipseWrapper ellipse = new EllipseWrapper(); - assertThrows(IllegalArgumentException.class, () -> ellipse.setCoordinates(null)); + assertThrows(IllegalArgumentException.class, + () -> ellipse.setCoordinates(null)); } @Test void testLineNullCoordinates() { LineWrapper line = new LineWrapper(); - assertThrows(IllegalArgumentException.class, () -> line.setCoordinates(null)); + assertThrows(IllegalArgumentException.class, + () -> line.setCoordinates(null)); } @@ -73,7 +79,8 @@ void testLineNullCoordinates() { void testPointWrongCoordinates() { PointWrapper point = new PointWrapper(); double[] coordinates = {2, 2, 4, 4}; - assertThrows(IllegalArgumentException.class, () -> point.setCoordinates(coordinates)); + assertThrows(IllegalArgumentException.class, + () -> point.setCoordinates(coordinates)); } @@ -81,7 +88,8 @@ void testPointWrongCoordinates() { void testTextWrongCoordinates() { TextWrapper text = new TextWrapper(); double[] coordinates = {2, 2, 4, 4}; - assertThrows(IllegalArgumentException.class, () -> text.setCoordinates(coordinates)); + assertThrows(IllegalArgumentException.class, + () -> text.setCoordinates(coordinates)); } @@ -89,7 +97,8 @@ void testTextWrongCoordinates() { void testRectangleWrongCoordinates() { RectangleWrapper rectangle = new RectangleWrapper(); double[] coordinates = {2, 2}; - assertThrows(IllegalArgumentException.class, () -> rectangle.setCoordinates(coordinates)); + assertThrows(IllegalArgumentException.class, + () -> rectangle.setCoordinates(coordinates)); } @@ -97,7 +106,8 @@ void testRectangleWrongCoordinates() { void testMaskWrongCoordinates() { MaskWrapper mask = new MaskWrapper(); double[] coordinates = {2, 2}; - assertThrows(IllegalArgumentException.class, () -> mask.setCoordinates(coordinates)); + assertThrows(IllegalArgumentException.class, + () -> mask.setCoordinates(coordinates)); } @@ -105,7 +115,8 @@ void testMaskWrongCoordinates() { void testEllipseWrongCoordinates() { EllipseWrapper ellipse = new EllipseWrapper(); double[] coordinates = {2, 2}; - assertThrows(IllegalArgumentException.class, () -> ellipse.setCoordinates(coordinates)); + assertThrows(IllegalArgumentException.class, + () -> ellipse.setCoordinates(coordinates)); } @@ -113,7 +124,8 @@ void testEllipseWrongCoordinates() { void testLineWrongCoordinates() { LineWrapper line = new LineWrapper(); double[] coordinates = {2, 2}; - assertThrows(IllegalArgumentException.class, () -> 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 32ffd4b4..0608d6d2 100644 --- a/src/test/java/fr/igred/omero/roi/ShapeTest.java +++ b/src/test/java/fr/igred/omero/roi/ShapeTest.java @@ -38,6 +38,7 @@ import java.util.ArrayList; import java.util.List; +import static java.lang.Math.abs; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -58,7 +59,7 @@ void testPoint() { double differences = 0; for (int i = 0; i < 2; i++) { - differences += Math.abs(checkCoordinates[i] - pointCoordinates[i]); + differences += abs(checkCoordinates[i] - pointCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -84,7 +85,7 @@ void testText() { double differences = 0; for (int i = 0; i < 2; i++) { - differences += Math.abs(checkCoordinates[i] - textCoordinates[i]); + differences += abs(checkCoordinates[i] - textCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -104,7 +105,7 @@ void testRectangle() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(checkCoordinates[i] - rectangleCoordinates[i]); + differences += abs(checkCoordinates[i] - rectangleCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -131,13 +132,13 @@ void testRectangleCZT() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(checkCoordinates[i] - rectangleCoordinates[i]); + differences += abs(checkCoordinates[i] - rectangleCoordinates[i]); } int c2 = rectangle.getC(); int z2 = rectangle.getZ(); int t2 = rectangle.getT(); - differences += Math.abs(c2 - c) + Math.abs(z2 - z) + Math.abs(t2 - t); + differences += abs(c2 - c) + abs(z2 - z) + abs(t2 - t); assertEquals(0, differences, Double.MIN_VALUE); assertEquals(text, rectangle.getText()); @@ -155,7 +156,7 @@ void testMask() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(checkCoordinates[i] - maskCoordinates[i]); + differences += abs(checkCoordinates[i] - maskCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -182,7 +183,7 @@ void testValuesMask() { int differences = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { - differences += Math.abs(maskValues[i][j] - checkValues[i][j]); + differences += abs(maskValues[i][j] - checkValues[i][j]); } } @@ -212,7 +213,7 @@ void testEllipse() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(checkCoordinates[i] - ellipseCoordinates[i]); + differences += abs(checkCoordinates[i] - ellipseCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -238,7 +239,7 @@ void testLine() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(checkCoordinates[i] - lineCoordinates[i]); + differences += abs(checkCoordinates[i] - lineCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -260,7 +261,7 @@ void testPointsLine() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(checkCoordinates[i] - lineCoordinates[i]); + differences += abs(checkCoordinates[i] - lineCoordinates[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -325,7 +326,7 @@ void testPointConstructor() { double differences = 0; for (int i = 0; i < 2; i++) { - differences += Math.abs(coordinates1[i] - coordinates2[i]); + differences += abs(coordinates1[i] - coordinates2[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -345,7 +346,7 @@ void testTextConstructor() { double differences = 0; for (int i = 0; i < 2; i++) { - differences += Math.abs(coordinates1[i] - coordinates2[i]); + differences += abs(coordinates1[i] - coordinates2[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -366,7 +367,7 @@ void testLineConstructor() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(coordinates1[i] - coordinates2[i]); + differences += abs(coordinates1[i] - coordinates2[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -386,7 +387,7 @@ void testRectangleConstructor() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(coordinates1[i] - coordinates2[i]); + differences += abs(coordinates1[i] - coordinates2[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -412,10 +413,10 @@ void testMaskConstructor() { int differences = 0; for (int i = 0; i < 4; i++) { - differences += (int) Math.abs(coordinates1[i] - coordinates2[i]); + differences += (int) abs(coordinates1[i] - coordinates2[i]); } for (int i = 0; i < maskValues.length; i++) { - differences += Math.abs(checkValues2[i] - checkValues1[i]); + differences += abs(checkValues2[i] - checkValues1[i]); } assertEquals(0, differences, Double.MIN_VALUE); @@ -435,7 +436,7 @@ void testEllipseConstructor() { double differences = 0; for (int i = 0; i < 4; i++) { - differences += Math.abs(coordinates1[i] - coordinates2[i]); + differences += abs(coordinates1[i] - coordinates2[i]); } assertEquals(0, differences, Double.MIN_VALUE); diff --git a/src/test/java/fr/igred/omero/util/WrapperTest.java b/src/test/java/fr/igred/omero/util/WrapperTest.java index ca5aa2b7..cb360cb5 100644 --- a/src/test/java/fr/igred/omero/util/WrapperTest.java +++ b/src/test/java/fr/igred/omero/util/WrapperTest.java @@ -91,6 +91,7 @@ import java.util.stream.Stream; +import static fr.igred.omero.util.Wrapper.wrap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -142,7 +143,7 @@ private static Stream classes() { > void testWrap(Class input, Class output) throws Exception { T object = input.getConstructor().newInstance(); - U result = Wrapper.wrap(object); + U result = wrap(object); assertSame(output, result.getClass()); } @@ -150,49 +151,51 @@ > void testWra @Test void testWrapChannelData() { ChannelData object = new ChannelData(0); - assertSame(ChannelWrapper.class, Wrapper.wrap(object).getClass()); + assertSame(ChannelWrapper.class, wrap(object).getClass()); } @Test void testWrapFileAnnotationData() { - FileAnnotationData object = new FileAnnotationData(new FileAnnotationI()); - assertSame(FileAnnotationWrapper.class, Wrapper.wrap(object).getClass()); + FileAnnotationI fileAnn = new FileAnnotationI(); + FileAnnotationData object = new FileAnnotationData(fileAnn); + assertSame(FileAnnotationWrapper.class, wrap(object).getClass()); } @Test void testWrapTagAnnotationData() { TagAnnotationData object = new TagAnnotationData(new TagAnnotationI()); - assertSame(TagAnnotationWrapper.class, Wrapper.wrap(object).getClass()); + assertSame(TagAnnotationWrapper.class, wrap(object).getClass()); } @Test void testWrapTextualAnnotationData() { - TextualAnnotationData object = new TextualAnnotationData(new CommentAnnotationI()); - assertSame(TextualAnnotationWrapper.class, Wrapper.wrap(object).getClass()); + CommentAnnotationI comment = new CommentAnnotationI(); + TextualAnnotationData object = new TextualAnnotationData(comment); + assertSame(TextualAnnotationWrapper.class, wrap(object).getClass()); } @Test void testWrapWrongDataObject() { DataObject object = new WrongDataObject(); - assertThrows(IllegalArgumentException.class, () -> Wrapper.wrap(object)); + assertThrows(IllegalArgumentException.class, () -> wrap(object)); } @Test void testWrapWrongShapeData() { ShapeData object = new WrongShapeData(); - assertThrows(IllegalArgumentException.class, () -> Wrapper.wrap(object)); + assertThrows(IllegalArgumentException.class, () -> wrap(object)); } @Test void testWrapWrongAnnotationData() { AnnotationData object = new WrongAnnotationData(); - assertThrows(IllegalArgumentException.class, () -> Wrapper.wrap(object)); + assertThrows(IllegalArgumentException.class, () -> wrap(object)); } From fb2070314ec199cf412e15f18c26a9f08cb9ba11 Mon Sep 17 00:00:00 2001 From: Pierre Pouchin Date: Fri, 22 Mar 2024 16:54:55 +0100 Subject: [PATCH 10/10] Add tests and improve code coverage --- .../repository/PlateAcquisitionTest.java | 21 ++++++++++++++++++ .../fr/igred/omero/repository/PlateTest.java | 19 ++++++++++++++++ .../fr/igred/omero/repository/ScreenTest.java | 22 ++++++++++++++++++- .../fr/igred/omero/repository/WellTest.java | 19 ++++++++++++++++ 4 files changed, 80 insertions(+), 1 deletion(-) diff --git a/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java b/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java index 4e7e6fec..7c1ad123 100644 --- a/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java +++ b/src/test/java/fr/igred/omero/repository/PlateAcquisitionTest.java @@ -99,6 +99,27 @@ void testAddTagToPlateAcquisition() throws Exception { } + @Test + void testAddAndRemoveTagFromPlateAcquisition() throws Exception { + PlateWrapper plate = client.getPlate(PLATE1.id); + + PlateAcquisitionWrapper acq = plate.getPlateAcquisitions().get(0); + + String name = "Plate acq. tag"; + String desc = "tag attached to a plate acq."; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); + acq.link(client, tag); + List tags = acq.getTags(client); + acq.unlink(client, tag); + List removedTags = acq.getTags(client); + client.delete(tag); + + assertEquals(1, tags.size()); + assertEquals(0, removedTags.size()); + } + + @Test void testSetName() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); diff --git a/src/test/java/fr/igred/omero/repository/PlateTest.java b/src/test/java/fr/igred/omero/repository/PlateTest.java index 4effb7b2..6be47b4b 100644 --- a/src/test/java/fr/igred/omero/repository/PlateTest.java +++ b/src/test/java/fr/igred/omero/repository/PlateTest.java @@ -102,6 +102,25 @@ void testAddTagToPlate() throws Exception { } + @Test + void testAddAndRemoveTagFromPlate() throws Exception { + PlateWrapper plate = client.getPlate(PLATE2.id); + + String name = "Plate tag"; + String desc = "tag attached to a plate"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); + plate.link(client, tag); + List tags = plate.getTags(client); + plate.unlink(client, tag); + List removedTags = plate.getTags(client); + client.delete(tag); + + assertEquals(1, tags.size()); + assertEquals(0, removedTags.size()); + } + + @Test void testSetName() throws Exception { PlateWrapper plate = client.getPlate(PLATE1.id); diff --git a/src/test/java/fr/igred/omero/repository/ScreenTest.java b/src/test/java/fr/igred/omero/repository/ScreenTest.java index ff8ff609..d1c3fb8f 100644 --- a/src/test/java/fr/igred/omero/repository/ScreenTest.java +++ b/src/test/java/fr/igred/omero/repository/ScreenTest.java @@ -18,6 +18,7 @@ package fr.igred.omero.repository; +import fr.igred.omero.GatewayWrapper; import fr.igred.omero.UserTest; import fr.igred.omero.annotations.TagAnnotationWrapper; import org.junit.jupiter.api.Test; @@ -90,6 +91,25 @@ void testAddTagToScreen() throws Exception { } + @Test + void testAddAndRemoveTagFromScreen() throws Exception { + ScreenWrapper screen = client.getScreen(SCREEN2.id); + + String name = "Screen tag"; + String desc = "tag attached to a screen"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); + screen.link(client, tag); + List tags = screen.getTags(client); + screen.unlink(client, tag); + List removedTags = screen.getTags(client); + client.delete(tag); + + assertEquals(1, tags.size()); + assertEquals(0, removedTags.size()); + } + + @Test void testSetName() throws Exception { ScreenWrapper screen = client.getScreen(SCREEN1.id); @@ -248,7 +268,7 @@ void testImportImage() throws Exception { client.delete(wells); client.delete(plates); - screen.refresh(client); + screen.refresh((GatewayWrapper) client); List endPlates = screen.getPlates(); client.delete(screen); diff --git a/src/test/java/fr/igred/omero/repository/WellTest.java b/src/test/java/fr/igred/omero/repository/WellTest.java index 84d96762..5c5f8592 100644 --- a/src/test/java/fr/igred/omero/repository/WellTest.java +++ b/src/test/java/fr/igred/omero/repository/WellTest.java @@ -48,6 +48,25 @@ void testAddTagToWell() throws Exception { } + @Test + void testAddAndRemoveTagFromWell() throws Exception { + WellWrapper well = client.getWell(2L); + + String name = "Well tag"; + String desc = "tag attached to a well"; + + TagAnnotationWrapper tag = new TagAnnotationWrapper(client, name, desc); + well.link(client, tag); + List tags = well.getTags(client); + well.unlink(client, tag); + List removedTags = well.getTags(client); + client.delete(tag); + + assertEquals(1, tags.size()); + assertEquals(0, removedTags.size()); + } + + @Test void testGetWellSamples() throws Exception { WellWrapper well = client.getWell(1L);