diff --git a/src/main/java/org/genesys2/client/oauth/GenesysClient.java b/src/main/java/org/genesys2/client/oauth/GenesysClient.java index 785e3c76cb22719ea6c47c2f109435cf59504c5c..fccf52fb1c53a785fb8c3fe391de8d334fd7e5a3 100644 --- a/src/main/java/org/genesys2/client/oauth/GenesysClient.java +++ b/src/main/java/org/genesys2/client/oauth/GenesysClient.java @@ -16,32 +16,20 @@ package org.genesys2.client.oauth; -import java.io.File; import java.io.IOException; import java.io.Serializable; -import java.net.URI; -import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.UUID; import java.util.concurrent.ExecutionException; import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.databind.node.ArrayNode; -import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.exceptions.OAuthException; import com.github.scribejava.core.model.OAuth2AccessToken; @@ -50,11 +38,9 @@ import com.github.scribejava.core.model.Response; import com.github.scribejava.core.model.Verb; import com.github.scribejava.core.oauth.OAuth20Service; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.genesys2.client.oauth.api.GenesysApi; import org.genesys2.client.oauth.api.accession.AccessionJson; -import org.genesys2.client.oauth.api.images.RepositoryImage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -228,8 +214,8 @@ public class GenesysClient { final OAuthRequest request = new OAuthRequest(method, getApiUrl(url)); if (queryString != null && queryString.size() > 0) { - for (final String key : queryString.keySet()) { - request.addQuerystringParameter(key, queryString.get(key)); + for (var entry : queryString.entrySet()) { + request.addQuerystringParameter(entry.getKey(), entry.getValue()); } } @@ -244,7 +230,7 @@ public class GenesysClient { if (postBody != null) { // System.err.println("Adding data: " + data); if (LOG.isTraceEnabled()) { - LOG.trace("Body: {}", new String(postBody)); + LOG.trace("Body: {}", new String(postBody, StandardCharsets.UTF_8)); } request.setPayload(postBody); } @@ -278,7 +264,7 @@ public class GenesysClient { } } else { LOG.error("{} {}", method, request.getCompleteUrl()); - LOG.error(new String(postBody)); + LOG.error(new String(postBody, StandardCharsets.UTF_8)); LOG.error("HTTP response code: {}", response.getCode()); LOG.error("Response: {}", responseBody); if (response.getCode() == 504 || responseBody.contains("Deadlock found when trying to get lock; try restarting transaction") @@ -331,44 +317,6 @@ public class GenesysClient { } } - /** - * Accession exists. - * - * @param instituteCode the inst code - * @param accessionNumber the acce numb - * @param genus the genus - * @return the string - * @throws GenesysApiException the Genesys API exception - */ - public String accessionExists(final String instituteCode, final String accessionNumber, final String genus) throws GenesysApiException { - - try { - final HashMap queryString = new HashMap(); - queryString.put("accessionNumber", accessionNumber); - - return query(Verb.GET, new URI(null, null, "/acn/exists/" + instituteCode + "/" + genus, null).toString(), queryString, null); - } catch (final URISyntaxException e) { - e.printStackTrace(); - return null; - } - } - - /** - * Make aid3. - * - * @param instituteCode the inst code - * @param genus the genus - * @param accessionNumber the acce numb - * @return the object node - */ - public static ObjectNode makeAid3(final String instituteCode, final String genus, final String accessionNumber) { - final ObjectNode json = objectMapper.createObjectNode(); - json.put("instituteCode", instituteCode); - json.put("accessionNumber", accessionNumber); - json.put("genus", genus); - return json; - } - /** * Update accessions. * @@ -515,537 +463,4 @@ public class GenesysClient { return query("/me/profile"); } - /** - * Gets the crop. - * - * @param shortName the short name - * @return the crop - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getCrop(final String shortName) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - if (!shortName.matches("^\\w+$")) { - throw new GenesysApiException("Crop shortname can only contain characters"); - } - return query("/crops/" + shortName); - } - - /** - * List parameters. - * - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listParameters() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/kpi/parameter/list"); - } - - /** - * Put parameter. - * - * @param node the node - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String putParameter(final ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/kpi/parameter", null, node.toString()); - } - - /** - * Gets the parameter. - * - * @param name the name - * @return the parameter - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getParameter(final String name) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/kpi/parameter/" + name); - } - - /** - * List dimensions. - * - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listDimensions() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/kpi/dimension/list"); - } - - /** - * Gets the dimension. - * - * @param id the id - * @return the dimension - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getDimension(final long id) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/kpi/dimension/" + id); - } - - /** - * Put dimension. - * - * @param node the node - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String putDimension(final ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/kpi/dimension", null, node.toString()); - } - - /** - * List executions. - * - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listExecutions() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/kpi/execution/list"); - } - - /** - * Gets the execution. - * - * @param name the name - * @return the execution - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getExecution(final String name) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/kpi/execution/" + name); - } - - /** - * Put execution. - * - * @param node the node - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String putExecution(final ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/kpi/execution", null, node.toString()); - } - - /** - * Kpi execute. - * - * @param name the name - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String kpiExecute(final String name) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/kpi/execution/" + name + "/execute", null, null); - } - - /** - * Delete dimension. - * - * @param id the id - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String deleteDimension(final long id) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.DELETE, "/kpi/dimension/" + id, null, null); - } - - /** - * Delete execution. - * - * @param name the name - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String deleteExecution(final String name) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.DELETE, "/kpi/execution/" + name, null, null); - } - - /** - * Delete parameter. - * - * @param name the name - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String deleteParameter(final String name) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.DELETE, "/kpi/parameter/" + name, null, null); - } - - /** - * List crops. - * - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listCrops() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/crops"); - } - - /** - * Put crop. - * - * @param node the node - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String putCrop(final ObjectNode node) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/crops", null, node.toString()); - } - - /** - * Delete crop. - * - * @param shortName the short name - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String deleteCrop(final String shortName) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.DELETE, "/crops/" + shortName, null, null); - } - - /** - * Gets the crop rules. - * - * @param shortName the short name - * @return the crop rules - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getCropRules(final String shortName) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/crops/" + shortName + "/rules"); - } - - /** - * Put crop rules. - * - * @param shortName the short name - * @param currentCropRules the current crop rules - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String putCropRules(final String shortName, final ArrayNode currentCropRules) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.PUT, "/crops/" + shortName + "/rules", null, currentCropRules.toString()); - } - - /** - * Rebuild crop taxa. - * - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String rebuildCropTaxa() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/crops/rebuild", null, null); - } - - /** - * Rebuild crop taxa. - * - * @param shortName the short name - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String rebuildCropTaxa(final String shortName) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/crops/" + shortName + "/rebuild", null, null); - } - - /** - * List organizations. - * - * @param page the page - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listOrganizations(final int page) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - final Map qs = new HashMap(); - qs.put("page", String.valueOf(page)); - return query(Verb.GET, "/org", qs, null); - } - - /** - * Gets the organization. - * - * @param slug the slug - * @return the organization - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getOrganization(final String slug) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/org/" + slug); - } - - /** - * Update organization. - * - * @param org the org - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String updateOrganization(final ObjectNode org) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.POST, "/org", null, org.toString()); - } - - /** - * Delete organization. - * - * @param slug the slug - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String deleteOrganization(final String slug) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.DELETE, "/org/" + slug, null, null); - } - - /** - * Gets the organization members. - * - * @param slug the slug - * @return the organization members - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getOrganizationMembers(final String slug) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/org/" + slug + "/institutes"); - } - - /** - * Put organization members. - * - * @param slug the slug - * @param currentMembers the current members - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String putOrganizationMembers(final String slug, final ArrayNode currentMembers) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.PUT, "/org/" + slug + "/set-institutes", null, currentMembers.toString()); - } - - /** - * Gets the organization blurp. - * - * @param slug the slug - * @param language the language - * @return the organization blurp - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String getOrganizationBlurp(final String slug, final String language) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query("/org/" + slug + "/blurp/" + language); - } - - /** - * Update organization blurp. - * - * @param slug the slug - * @param blurp the blurp - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String updateOrganizationBlurp(final String slug, final ObjectNode blurp) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - return query(Verb.PUT, "/org/" + slug + "/blurp", null, blurp.toString()); - } - - /** - * List observations. - * - * @param executionName the execution name - * @param dimensionFilter the dimension filter - * @param page the page - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listObservations(final String executionName, final String dimensionFilter, final int page) - throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - final Map qs = new HashMap(); - qs.put("page", String.valueOf(page)); - return query(Verb.POST, "/kpi/observation/" + executionName + "/", qs, StringUtils.defaultIfBlank(dimensionFilter, "")); - } - - /** - * List accessions. - * - * @param instituteCode the inst code - * @param page the page - * @param query the query - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public String listAccessions(final String instituteCode, final int page, final String query) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - final Map params = new HashMap(); - params.put("page", String.valueOf(page)); - params.put("query", query); - return query(Verb.GET, "/acn/" + instituteCode + "/list", params, null); - } - - /** - * List existing image galleries for INSTCODE. The response is paginated, provide page - * argument to request a specific page. - * - * @param instituteCode institute code (MCPD INSTCODE) - * @param page 1 for first page - * @return the string - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws HttpRedirectException the http redirect exception - * @throws GenesysApiException the Genesys API exception - */ - public String listGalleries(final String instituteCode, final int page) throws OAuthAuthenticationException, PleaseRetryException, HttpRedirectException, GenesysApiException { - return query(Verb.GET, String.format("/img/%1$s/_galleries", instituteCode), Collections.singletonMap("page", Integer.toString(page)), null); - } - - /** - * List UUIDs of images in an existing accession gallery. - * - * @param instituteCode institute code (MCPD INSTCODE) - * @param accessionNumber the acce numb - * @return the list - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - * @throws JsonParseException the json parse exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public List listGalleryImages(final String instituteCode, final String accessionNumber) - throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException, JsonParseException, JsonMappingException, IOException { - - final String json = query(Verb.GET, String.format("/img/%1$s/acn/%2$s", instituteCode)); - return objectMapper.readValue(json, new TypeReference>() { - }); - } - - /** - * Add image to accession. - * - * @param instituteCode institute code (MCPD INSTCODE) - * @param accessionNumber accession number (MCPD ACCENUMB) - * @param file image to upload - * @param contentType the content type - * @return the repository image - * @throws GenesysApiException the Genesys API exception - * @throws IOException if file cannot be read - */ - public RepositoryImage uploadImage(final String instituteCode, final String accessionNumber, final File file, final String contentType) throws GenesysApiException, IOException { - if (StringUtils.isBlank(contentType)) { - throw new GenesysApiException("Content-Type must be provided for the file " + file.getAbsolutePath()); - } - - LOG.debug("Image content type: {}", contentType); - - // PUT file on server - final String json = query(Verb.PUT, String.format("/img/%1$s/acn/%2$s/", instituteCode, accessionNumber), Collections.singletonMap("originalFilename", file.getName()), contentType, - FileUtils.readFileToByteArray(file)); - - System.err.println(json); - // Deserialize JSON - return objectMapper.readValue(json, RepositoryImage.class); - } - - /** - * Remove image from accession gallery by UUID. URL template: - * /img/{instituteCode}/acn/{accessionNumber:.+}/{uuid}/_metadata - * - * @param instituteCode institute code (MCPD INSTCODE) - * @param accessionNumber accession number (MCPD ACCENUMB) - * @param uuid Repository image UUID as assigned by Genesys - * @throws OAuthAuthenticationException authentication exception - * @throws PleaseRetryException exception indicating the call shold be re-attempted - * @throws GenesysApiException the Genesys API exception - */ - public void deleteImage(final String instituteCode, final String accessionNumber, final UUID uuid) throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException { - query(Verb.DELETE, String.format("/img/%1$s/acn/%2$s/%3$s", instituteCode, accessionNumber, uuid)); - } - - /** - * Get image metadata from Genesys. - * - * @param instituteCode institute code (MCPD INSTCODE) - * @param accessionNumber accession number (MCPD ACCENUMB) - * @param uuid Repository image UUID as assigned by Genesys - * @return the metadata - * @throws GenesysApiException the Genesys API exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public RepositoryImage getImageMetadata(final String instituteCode, final String accessionNumber, final UUID uuid) throws GenesysApiException, IOException { - // PUT file on server - final String json = query(Verb.GET, String.format("/img/%1$s/acn/%2$s/%3$s/_metadata", instituteCode, accessionNumber, uuid)); - - // Deserialize JSON - return objectMapper.readValue(json, RepositoryImage.class); - } - - /** - * Set image metadata. Endpoint PUT - * /img/{instituteCode}/acn/{accessionNumber:.+}/{uuid}/_metadata - * - * @param instituteCode institute code (MCPD INSTCODE) - * @param accessionNumber accession number (MCPD ACCENUMB) - * @param uuid Repository image UUID as assigned by Genesys - * @param imageData the image data - * @return the metadata - * @throws GenesysApiException the Genesys API exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public RepositoryImage putImageMetadata(final String instituteCode, final String accessionNumber, final UUID uuid, final RepositoryImage imageData) - throws GenesysApiException, IOException { - final String json = query(Verb.PUT, String.format("/img/%1$s/acn/%2$s/%3$s/_metadata", instituteCode, accessionNumber, uuid), null, imageData); - - // Deserialize JSON - return objectMapper.readValue(json, RepositoryImage.class); - } } diff --git a/src/test/java/org/geneys2/client/oauth/AccessionApiTest.java b/src/test/java/org/geneys2/client/oauth/AccessionApiTest.java deleted file mode 100644 index 75c9bedefac1440ef803a7e5c181e556a47dd713..0000000000000000000000000000000000000000 --- a/src/test/java/org/geneys2/client/oauth/AccessionApiTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2019 Global Crop Diversity Trust - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.geneys2.client.oauth; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.genesys2.client.oauth.GenesysApiException; -import org.genesys2.client.oauth.GenesysClient; -import org.genesys2.client.oauth.OAuthAuthenticationException; -import org.genesys2.client.oauth.PleaseRetryException; -import org.genesys2.client.oauth.api.accession.AccessionJson; -import org.hamcrest.CoreMatchers; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Matchers; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -/** - * Accession API v1 test - */ -@RunWith(MockitoJUnitRunner.class) -public class AccessionApiTest { - - /** The object mapper. */ - private static final ObjectMapper objectMapper; - - /** The genesys client. */ - @Mock - protected GenesysClient genesysClient; - - /** The inst code. */ - private final String instituteCode = "INS000"; - - /** The mock server. */ - private final MockGenesysServer mockServer = new MockGenesysServer(); - - static { - objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); - objectMapper.setSerializationInclusion(Include.NON_EMPTY); - objectMapper.setSerializationInclusion(Include.NON_NULL); - } - - /** - * Inits the mocks. - * - * @throws OAuthAuthenticationException the o auth authentication exception - * @throws PleaseRetryException the please retry exception - * @throws GenesysApiException the genesys api exception - * @throws InterruptedException the interrupted exception - * @throws JsonProcessingException the json processing exception - */ - @Before - public void initMocks() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException, InterruptedException, JsonProcessingException { - System.err.println("Initializing mocks"); - when(genesysClient.listAccessions(anyString(), anyInt(), Matchers.isNull(String.class))).then(mockServer.listAccessions()); - when(genesysClient.updateAccessions(anyString(), anyCollectionOf(AccessionJson.class))).then(mockServer.updateAccessions()); - } - - /** - * Test accessions0. - * - * @throws OAuthAuthenticationException the o auth authentication exception - * @throws PleaseRetryException the please retry exception - * @throws GenesysApiException the genesys api exception - * @throws JsonProcessingException the json processing exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testAccessions0() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException, JsonProcessingException, IOException { - - final List results = objectMapper.readValue(genesysClient.listAccessions(instituteCode, 1, null), new TypeReference>() { - }); - - assertThat("Expected empty list", results.size(), is(0)); - } - - /** - * Test accessions1. - * - * @throws OAuthAuthenticationException the o auth authentication exception - * @throws PleaseRetryException the please retry exception - * @throws GenesysApiException the genesys api exception - * @throws JsonProcessingException the json processing exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testAccessions1() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException, JsonProcessingException, IOException { - - when(genesysClient.listAccessions(instituteCode, 1, null)).thenReturn("[{\"instituteCode\":\"INS000\",\"accessionNumber\":\"ACC-1\"}]"); - - final List results = objectMapper.readValue(genesysClient.listAccessions(instituteCode, 1, null), new TypeReference>() { - }); - - assertThat("Expected empty list", results.size(), is(1)); - final AccessionJson acc1 = results.get(0); - assertThat("INSTCODE doesn't match", acc1.getInstituteCode(), is(instituteCode)); - - acc1.setHistoric(true); - - } - - /** - * Test upsert accessions1. - * - * @throws OAuthAuthenticationException the o auth authentication exception - * @throws PleaseRetryException the please retry exception - * @throws GenesysApiException the genesys api exception - * @throws JsonProcessingException the json processing exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException the interrupted exception - */ - @Test - public void testUpsertAccessions1() throws OAuthAuthenticationException, PleaseRetryException, GenesysApiException, JsonProcessingException, IOException, InterruptedException { - - String result = genesysClient.listAccessions(instituteCode, 1, null); - assertThat("Non-null result expected from genesysClient", result, notNullValue()); - List results = objectMapper.readValue(result, new TypeReference>() { - }); - - assertThat("Expected empty list", results.size(), is(0)); - - final List ajList = new ArrayList(); - - for (int i = 0; i < 4; i++) { - final AccessionJson aj = new AccessionJson(); - aj.setInstituteCode(instituteCode); - aj.setAccessionNumber("ACC-" + (i + 1)); - aj.getTaxonomy().setGenus("Genus"); - ajList.add(aj); - } - - result = genesysClient.updateAccessions(instituteCode, ajList); - System.err.println(result); - - results = objectMapper.readValue(genesysClient.listAccessions(instituteCode, 1, null), new TypeReference>() { - }); - - assertThat("Expected list with 4 entries", results.size(), is(4)); - - for (final AccessionJson aj1 : results) { - assertThat("Expected matching INSTCODE", aj1.getInstituteCode(), is(instituteCode)); - assertThat("Expected ACCENUMB starting with", aj1.getAccessionNumber(), CoreMatchers.startsWith("ACC-")); - assertThat("Expected GENUS=Genus", aj1.getTaxonomy().getGenus(), is("Genus")); - assertThat("Expected SPECIES=null", aj1.getTaxonomy().getSpecies(), nullValue()); - } - - } - -} diff --git a/src/test/java/org/geneys2/client/oauth/AccessionImagesTest.java b/src/test/java/org/geneys2/client/oauth/AccessionImagesTest.java index 3191a41862069e63c867235991b330f1e31ac32f..71002583bf8338b03c802b5f5d489e7862aebf0a 100644 --- a/src/test/java/org/geneys2/client/oauth/AccessionImagesTest.java +++ b/src/test/java/org/geneys2/client/oauth/AccessionImagesTest.java @@ -29,7 +29,7 @@ import org.junit.Test; public class AccessionImagesTest { /** The mapper. */ - private static ObjectMapper objectMapper; + private static final ObjectMapper objectMapper; static { objectMapper = new ObjectMapper(); diff --git a/src/test/java/org/geneys2/client/oauth/MockGenesysServer.java b/src/test/java/org/geneys2/client/oauth/MockGenesysServer.java deleted file mode 100644 index f77b7e6a65d8660d262806465050f6b3f5b64232..0000000000000000000000000000000000000000 --- a/src/test/java/org/geneys2/client/oauth/MockGenesysServer.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright 2019 Global Crop Diversity Trust - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.geneys2.client.oauth; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -import org.genesys2.client.oauth.GenesysApiException; -import org.genesys2.client.oauth.api.accession.AccessionJson; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -// TODO: Auto-generated Javadoc -/** - * Mock Genesys server. - * - * @author mobreza - */ -public class MockGenesysServer { - - /** The Constant BLANK_LIST. */ - private static final ArrayList BLANK_LIST = new ArrayList(); - - /** The inst acc. */ - private final Map> instAcc = new HashMap>(); - - /** The object mapper. */ - private static final ObjectMapper objectMapper; - - static { - objectMapper = new ObjectMapper(); - objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); - objectMapper.setSerializationInclusion(Include.NON_EMPTY); - objectMapper.setSerializationInclusion(Include.NON_NULL); - } - - /** - * List accessions. - * - * @return the answer - */ - public Answer listAccessions() { - return new Answer() { - @Override - public String answer(final InvocationOnMock invocation) throws Throwable { - final Object[] args = invocation.getArguments(); - if (args[2] != null) { - throw new MockGenesysException("Querying is not supported."); - } - final String instituteCode = (String) args[0]; - final int page = (Integer) args[1]; - - System.err.println("Listing accessions instituteCode=" + instituteCode + " page=" + page); - - return objectMapper.writeValueAsString(getAccessionsPage(instituteCode, page)); - } - }; - } - - /** - * Update accessions. - * - * @return the answer - */ - public Answer updateAccessions() { - return new Answer() { - @Override - public String answer(final InvocationOnMock invocation) throws Throwable { - final Object[] args = invocation.getArguments(); - final String instituteCode = (String) args[0]; - final List arrayNode = (List) args[1]; - - final String res = objectMapper.writeValueAsString(upsertAccessions(instituteCode, arrayNode)); - System.err.println("Result: " + res); - return res; - } - }; - } - - /** - * Upsert accessions. - * - * @param instituteCode the inst code - * @param nodeList the node list - * @return the string - * @throws JsonParseException the json parse exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws GenesysApiException the genesys api exception - */ - protected String upsertAccessions(final String instituteCode, final List nodeList) throws JsonParseException, JsonMappingException, IOException, GenesysApiException { - List accList = instAcc.get(instituteCode); - if (accList == null) { - instAcc.put(instituteCode, accList = new ArrayList()); - } - for (int i = 0; i < nodeList.size(); i++) { - final AccessionJson aj = (AccessionJson) nodeList.get(i); - final AccessionJson existing = findMatch(accList, aj); - merge(accList, existing, aj); - } - return "OK"; - - } - - /** - * Merge. - * - * @param accList the acc list - * @param existing the existing - * @param aj the aj - * @throws MockGenesysException the mock genesys exception - */ - private void merge(final List accList, final AccessionJson existing, final AccessionJson aj) throws MockGenesysException { - if (existing == null) { - accList.add(aj); - } else { - if (aj.getAvailable() != null) { - existing.setAvailable(aj.getAvailable()); - } - if (aj.getHistoric() != null) { - existing.setHistoric(aj.getHistoric()); - } - if (aj.getInTrust() != null) { - existing.setInTrust(aj.getInTrust()); - } - if (aj.getMlsStat() != null) { - existing.setMlsStat(aj.getMlsStat()); - } - if (aj.getAegis() != null) { - existing.setAegis(aj.getAegis()); - } - if (aj.getAccessionNumber() != null) { - existing.setAccessionNumber(aj.getAccessionNumber()); - } - if (aj.getAcquisitionDate() != null) { - existing.setAcquisitionDate(aj.getAcquisitionDate()); - } - if (aj.getAncest() != null) { - existing.setAncest(aj.getAncest()); - } - if (aj.getBredCode() != null) { - existing.setBredCode(aj.getBredCode()); - } - if (aj.getColl() != null) { - - } - if (aj.getDonorCode() != null) { - existing.setDonorCode(aj.getDonorCode()); - } - if (aj.getDonorName() != null) { - existing.setDonorName(aj.getDonorName()); - } - if (aj.getDonorNumb() != null) { - existing.setDonorNumb(aj.getDonorNumb()); - } - if (aj.getDuplSite() != null) { - existing.setDuplSite(aj.getDuplSite()); - } - if (aj.getGeo() != null) { - - } - if (aj.getOrgCty() != null) { - existing.setOrgCty(aj.getOrgCty()); - } - if (aj.getRemarks() != null) { - existing.setRemarks(aj.getRemarks()); - } - if (aj.getSampStat() != null) { - existing.setSampStat(aj.getSampStat()); - } - if (aj.getTaxonomy() != null) { - - } - if (aj.getUuid() != null) { - if (existing.getUuid() == null) { - existing.setUuid(aj.getUuid()); - } else if (!existing.getUuid().equals(aj.getUuid())) { - // Can this happen? - throw new MockGenesysException("UUID mismatch"); - } - } - if (aj.getAvailable() != null) { - existing.setAvailable(aj.getAvailable()); - } - } - } - - /** - * Find match. - * - * @param accList the acc list - * @param aj the aj - * @return the accession json - */ - private AccessionJson findMatch(final List accList, final AccessionJson aj) { - if (aj.getUuid() != null) { - return findMatch(accList, aj.getUuid()); - } else { - for (final AccessionJson m : accList) { - if (m.getInstituteCode().equals(aj.getInstituteCode()) && m.getAccessionNumber().equals(aj.getAccessionNumber()) && m.getTaxonomy().getGenus().equals(aj.getTaxonomy().getGenus())) { - return m; - } - } - } - return null; - } - - /** - * Find match. - * - * @param accList the acc list - * @param uuid the uuid - * @return the accession json - */ - private AccessionJson findMatch(final List accList, final String uuid) { - for (final AccessionJson m : accList) { - if (m.getUuid().equals(uuid)) { - return m; - } - } - return null; - } - - /** - * Gets the accessions page. - * - * @param instituteCode the inst code - * @param page the page - * @return the accessions page - * @throws MockGenesysException the mock genesys exception - */ - protected List getAccessionsPage(final String instituteCode, final int page) throws MockGenesysException { - final List accList = instAcc.get(instituteCode); - if (accList == null || accList.isEmpty()) { - System.err.println("Returning blank list"); - return BLANK_LIST; - } - if (page != 1) { - throw new MockGenesysException("page argument is not suported"); - } - - return accList; - } - -}