diff --git a/.gitignore b/.gitignore index 83e0b5aade13f5d439275e4e40c5d8eec3643cc9..cc703377d56b9dd50a9cda603411eea239609001 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,4 @@ target/ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* +*local.properties diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6a24a6a828014c949379657fa13265970178e53a..40bac5b4d43478150f4da8c5ee5f79e1dabb6d5e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -8,6 +8,9 @@ variables: GCP_DEPLOY_ENV: p4d GCP_DOMAIN: cloud.slb-ds.com + IBM_BUILD_SUBDIR: provider/schema-ibm + #IBM_INT_TEST_SUBDIR: testing/schema-test-ibm + include: - project: "osdu/platform/ci-cd-pipelines" file: "standard-setup.yml" @@ -15,9 +18,20 @@ include: - project: "osdu/platform/ci-cd-pipelines" file: "build/maven.yml" - - project: "osdu/platform/ci-cd-pipelines" - file: "scanners/fossa.yml" + # - project: "osdu/platform/ci-cd-pipelines" + # file: "scanners/fossa.yml" + + # - project: "osdu/platform/ci-cd-pipelines" + # file: "cloud-providers/gcp.yml" + + # - project: 'osdu/platform/ci-cd-pipelines' + # file: 'cloud-providers/aws.yml' - project: "osdu/platform/ci-cd-pipelines" - file: "scanners/gitlab-ultimate.yml" - \ No newline at end of file + file: "cloud-providers/ibm.yml" + + # - project: "osdu/platform/ci-cd-pipelines" + # file: "scanners/gitlab-ultimate.yml" + + # - project: "osdu/platform/ci-cd-pipelines" + # file: "cloud-providers/azure.yml" diff --git a/pom.xml b/pom.xml index 42345eb704d9fbc78a70be13cc27d649d5b96126..fa3594246cda072447230018358dc835f65b5e5a 100644 --- a/pom.xml +++ b/pom.xml @@ -41,6 +41,7 @@ schema-core provider/schema-gcp + provider/schema-ibm diff --git a/provider/schema-ibm/pom.xml b/provider/schema-ibm/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..f05d39338c7b4b0e5a3a6c7be9b8ad4fe795e2e0 --- /dev/null +++ b/provider/schema-ibm/pom.xml @@ -0,0 +1,124 @@ + + 4.0.0 + + org.opengroup.osdu + os-schema + 0.0.1 + ../../ + + os-schema-ibm + IBM cloud related implementation staff. + jar + + + org.opengroup.osdu.schema.provider.ibm.app.SchemaIBMApplication + 0.0.19-SNAPSHOT + + + + + + + org.opengroup.osdu + os-schema-core + 0.0.1 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.mockito + mockito-all + 1.10.19 + test + + + + org.opengroup.osdu + os-core-lib-ibm + ${os-core-lib-ibm.version} + + + + io.cucumber + cucumber-java8 + 5.4.0 + test + + + + io.cucumber + cucumber-junit + 5.4.0 + test + + + + + + + + ${gitlab-server} + https://community.opengroup.org/api/v4/groups/17/-/packages/maven + + + + + + ${gitlab-server} + https://community.opengroup.org/api/v4/projects/26/packages/maven + + + ${gitlab-server} + https://community.opengroup.org/api/v4/projects/26/packages/maven + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + spring-boot + ${start-class} + + + + + + + maven-war-plugin + + false + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + ${skipUnitTests} + 3 + true + -Xmx1024m -XX:MaxPermSize=256m + + + + + + + + \ No newline at end of file diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmAuthorityStore.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmAuthorityStore.java new file mode 100644 index 0000000000000000000000000000000000000000..8517cb8f5ac199b18b052b030ceeefee37d6887c --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmAuthorityStore.java @@ -0,0 +1,62 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import java.net.MalformedURLException; +import java.text.MessageFormat; + +import javax.annotation.PostConstruct; + +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.impl.schemainfostore.util.IbmDocumentStore; +import org.opengroup.osdu.schema.model.Authority; +import org.opengroup.osdu.schema.provider.ibm.AuthorityDoc; +import org.opengroup.osdu.schema.provider.interfaces.schemainfostore.IAuthorityStore; +import org.springframework.stereotype.Repository; +import org.springframework.web.context.annotation.RequestScope; + +/** + * Repository class to to register authority in IBM store. + * + */ +@Repository +@RequestScope +public class IbmAuthorityStore extends IbmDocumentStore implements IAuthorityStore { + + @PostConstruct + public void init() throws MalformedURLException { + initFactory(SchemaConstants.AUTHORITY); + } + + @Override + public Authority get(String authorityId) throws NotFoundException, ApplicationException { + + if (db.contains(authorityId)) { + AuthorityDoc sd = db.find(AuthorityDoc.class, authorityId); + return sd.getAuthority(); + } else { + throw new NotFoundException(SchemaConstants.INVALID_INPUT); + } + } + + @Override + public Authority create(Authority authority) throws ApplicationException, BadRequestException { + + if (db.contains(authority.getAuthorityId())) { + logger.warning(SchemaConstants.AUTHORITY_EXISTS_ALREADY_REGISTERED); + throw new BadRequestException( + MessageFormat.format(SchemaConstants.AUTHORITY_EXISTS_EXCEPTION, authority.getAuthorityId())); + } + AuthorityDoc sd = new AuthorityDoc(authority); + try { + db.save(sd); + } catch (Exception ex) { + logger.error(SchemaConstants.OBJECT_INVALID, ex); + throw new ApplicationException(SchemaConstants.INVALID_INPUT); + } + logger.info(SchemaConstants.AUTHORITY_CREATED); + return sd.getAuthority(); + } + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmEntityTypeStore.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmEntityTypeStore.java new file mode 100644 index 0000000000000000000000000000000000000000..8f0b2dda7045a4195552a6062c193a00fb048913 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmEntityTypeStore.java @@ -0,0 +1,64 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import java.net.MalformedURLException; +import java.text.MessageFormat; + +import javax.annotation.PostConstruct; + +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.impl.schemainfostore.util.IbmDocumentStore; +import org.opengroup.osdu.schema.model.EntityType; +import org.opengroup.osdu.schema.provider.ibm.EntityTypeDoc; +import org.opengroup.osdu.schema.provider.interfaces.schemainfostore.IEntityTypeStore; +import org.springframework.stereotype.Repository; +import org.springframework.web.context.annotation.RequestScope; + +/** + * Repository class to register Entity type in IBM store. + * + * + */ +@Repository +@RequestScope +public class IbmEntityTypeStore extends IbmDocumentStore implements IEntityTypeStore { + + @PostConstruct + public void init() throws MalformedURLException { + initFactory(SchemaConstants.ENTITYTYPE_KIND); + } + + @Override + public EntityType get(String entityTypeId) throws NotFoundException, ApplicationException { + if (db.contains(entityTypeId)) { + EntityTypeDoc sd = db.find(EntityTypeDoc.class, entityTypeId); + return sd.getEntityType(); + } else { + throw new NotFoundException(SchemaConstants.INVALID_INPUT); + } + } + + @Override + public EntityType create(EntityType entityType) throws BadRequestException, ApplicationException { + + if (db.contains(entityType.getEntityTypeId())) { + logger.warning(SchemaConstants.ENTITY_TYPE_EXISTS); + throw new BadRequestException( + MessageFormat.format(SchemaConstants.ENTITY_TYPE_EXISTS_EXCEPTION, entityType.getEntityTypeId())); + } + EntityTypeDoc sd = new EntityTypeDoc(entityType); + + try { + db.save(sd); + } catch (Exception ex) { + logger.error(SchemaConstants.OBJECT_INVALID, ex); + throw new ApplicationException(SchemaConstants.INVALID_INPUT); + } + logger.info(SchemaConstants.ENTITY_TYPE_CREATED); + return sd.getEntityType(); + } + + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSchemaInfoStore.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSchemaInfoStore.java new file mode 100644 index 0000000000000000000000000000000000000000..88e01ba2bec2994d4fab1f89f3b96073b60384c9 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSchemaInfoStore.java @@ -0,0 +1,392 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import static com.cloudant.client.api.query.Expression.eq; +import static com.cloudant.client.api.query.Operation.and; + +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; + +import javax.annotation.PostConstruct; +import javax.inject.Inject; + +import org.opengroup.osdu.core.common.model.tenant.TenantInfo; +import org.opengroup.osdu.core.ibm.multitenancy.TenantFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.impl.schemainfostore.util.IbmDocumentStore; +import org.opengroup.osdu.schema.model.QueryParams; +import org.opengroup.osdu.schema.model.SchemaIdentity; +import org.opengroup.osdu.schema.model.SchemaInfo; +import org.opengroup.osdu.schema.model.SchemaRequest; +import org.opengroup.osdu.schema.provider.ibm.SchemaDoc; +import org.opengroup.osdu.schema.provider.interfaces.schemainfostore.ISchemaInfoStore; +import org.opengroup.osdu.schema.provider.interfaces.schemastore.ISchemaStore; +import org.opengroup.osdu.schema.util.VersionHierarchyUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.web.context.annotation.RequestScope; + +import com.cloudant.client.api.Database; +import com.cloudant.client.api.query.Expression; +import com.cloudant.client.api.query.QueryBuilder; +import com.cloudant.client.api.query.QueryResult; +import com.cloudant.client.api.query.Selector; +import com.google.gson.Gson; + +/** + * Repository class to to register Schema in IBM Document Store. + * + */ +@Repository +@RequestScope +public class IbmSchemaInfoStore extends IbmDocumentStore implements ISchemaInfoStore { + + private final static String AUTHORITY = "schemaIdentity.authority"; + private final static String SOURCE = "schemaIdentity.source"; + private final static String ENTITY_TYPE = "schemaIdentity.entityType"; + private final static String SCHEMA_VERSION_MAJOR = "schemaIdentity.schemaVersionMajor"; + private final static String SCHEMA_VERSION_MINOR = "schemaIdentity.schemaVersionMinor"; + private final static String SCHEMA_VERSION_PATCH = "schemaIdentity.schemaVersionPatch"; + private final static String SCOPE = "scope"; + private final static String STATUS = "status"; + + @Inject + private TenantFactory tenantFactory; + + @Autowired + private ISchemaStore schemaStore; + + + @PostConstruct + public void init() throws MalformedURLException { + initFactory(SCHEMA_DATABASE); + } + + + @Override + public boolean isUnique(String schemaId, String tenantId) throws ApplicationException { + Set tenantList = new HashSet<>(); + tenantList.add(SchemaConstants.ACCOUNT_ID_COMMON_PROJECT); + tenantList.add(tenantId); + + // code to call check uniqueness + if (tenantId.equalsIgnoreCase(SchemaConstants.ACCOUNT_ID_COMMON_PROJECT)) { + List privateTenantList = tenantFactory.listTenantInfo().stream().map(TenantInfo::getDataPartitionId) + .collect(Collectors.toList()); + tenantList.addAll(privateTenantList); + + } + + for (String tenant : tenantList) { + try { + if (getDatabaseForTenant(tenant, SCHEMA_DATABASE).contains(schemaId)) { + return false; // DB exists and contains schemaId, so is not unique + } + } catch (MalformedURLException e) { + // DB doesn't exist, so its unique + throw new ApplicationException("Unable to find database for tenant " + tenant); + } + } + + return true; + } + + + /** + * Method to get schemaInfo from IBM store + * + * @param schemaId + * @return schemaInfo object + * @throws ApplicationException + * @throws NotFoundException + */ + @Override + public SchemaInfo getSchemaInfo(String schemaId) throws ApplicationException, NotFoundException { + if (db.contains(schemaId)) { + SchemaDoc sd = db.find(SchemaDoc.class, schemaId); + return sd.getSchemaInfo(); + } else { + throw new NotFoundException(SchemaConstants.SCHEMA_NOT_PRESENT); + } + + } + + /** + * Method to Create schema in IBM store + * + * @param schemaRequest + * @return schemaInfo object + * @throws ApplicationException + * @throws BadRequestException + */ + @Override + public SchemaInfo createSchemaInfo(SchemaRequest schemaRequest) throws ApplicationException, BadRequestException { + + String schemaId = schemaRequest.getSchemaInfo().getSchemaIdentity().getId(); + + if (db.contains(schemaId)) { + logger.warning("Schema " + schemaId + " already exist. Can't create again."); + throw new BadRequestException("Schema " + schemaId + " already exist. Can't create again."); + } + validateSupercededBy(schemaRequest); + SchemaDoc sd = new SchemaDoc(schemaRequest.getSchemaInfo()); + try { + Date date = new Date(); + long now = date.getTime(); + sd.setCreatedDate(now); + db.save(sd); + } catch (Exception ex) { + logger.error(SchemaConstants.OBJECT_INVALID); + throw new ApplicationException(SchemaConstants.SCHEMA_CREATION_FAILED_INVALID_OBJECT); + } + logger.info(SchemaConstants.SCHEMA_CREATED); + return sd.getSchemaInfo(); + } + + /** + * Method to update schema in IBM store + * + * @param schemaRequest + * @return schemaInfo object + * @throws ApplicationException + * @throws BadRequestException + */ + @Override + public SchemaInfo updateSchemaInfo(SchemaRequest schemaRequest) throws ApplicationException, BadRequestException { + String schemaId = schemaRequest.getSchemaInfo().getSchemaIdentity().getId(); + validateSupercededBy(schemaRequest); + SchemaDoc sdStored = db.find(SchemaDoc.class, schemaId); + SchemaDoc sd = new SchemaDoc(schemaRequest.getSchemaInfo()); + sd.setRev(sdStored.getRev()); + + try { + db.update(sd); + } catch (Exception ex) { + logger.error(SchemaConstants.OBJECT_INVALID, ex); + throw new ApplicationException("Invalid object, updation failed"); + } + return sd.getSchemaInfo(); + } + + /** + * Method to clean schemaInfo in IBM datastore of tenantId + * + * @param schemaId + * @return status + * @throws ApplicationException + */ + @Override + public boolean cleanSchema(String schemaId) throws ApplicationException { + + try { + if (db.contains(schemaId)) { + SchemaDoc sd = db.find(SchemaDoc.class, schemaId); + db.remove(sd); + return true; + } + return false; + + } catch (Exception ex) { + logger.error(SchemaConstants.OBJECT_INVALID, ex); + return false; + } + + } + + @Override + public String getLatestMinorVerSchema(SchemaInfo schemaInfo) throws ApplicationException { + + QueryResult results = db.query(new QueryBuilder(getSelectorForMinorVerSchema(schemaInfo)).build(), + SchemaDoc.class); + TreeMap sortedMap = new TreeMap<>(Collections.reverseOrder()); + + for (SchemaDoc doc : results.getDocs()) { + sortedMap.put(doc.getSchemaInfo().getSchemaIdentity().getSchemaVersionMinor(), doc); + } + + if (sortedMap.size() != 0) { + Entry sd = sortedMap.firstEntry(); + + SchemaDoc doc = sd.getValue(); + try { + return schemaStore.getSchema(null, doc.getId()); + } catch (NotFoundException e) { + return new String(); + } + } + + return new String(); + } + + + private void validateSupercededBy(SchemaRequest schemaRequest) throws BadRequestException{ + if (schemaRequest.getSchemaInfo().getSupersededBy() != null) { + if (schemaRequest.getSchemaInfo().getSupersededBy().getId() == null + || !db.contains(schemaRequest.getSchemaInfo().getSupersededBy().getId())) { + logger.error(SchemaConstants.INVALID_SUPERSEDEDBY_ID); + throw new BadRequestException(SchemaConstants.INVALID_SUPERSEDEDBY_ID); + } + + } + } + + private Selector getSelectorForMinorVerSchema(SchemaInfo schemaInfo) { + return and( + eq(AUTHORITY, schemaInfo.getSchemaIdentity().getAuthority()), + eq(ENTITY_TYPE, schemaInfo.getSchemaIdentity().getEntityType()), + eq(SCHEMA_VERSION_MAJOR, schemaInfo.getSchemaIdentity().getSchemaVersionMajor()), + eq(SOURCE, schemaInfo.getSchemaIdentity().getSource()) + ); + } + + @Override + public List getSchemaInfoList(QueryParams queryParams, String tenantId) throws ApplicationException { + + long numRecords = LIMIT_SIZE; + if (Long.valueOf(queryParams.getLimit()) != null) { + numRecords = Long.valueOf(queryParams.getLimit()); + } + + String selectorWithoutFilter = "{ \"selector\": {} }"; + String finalQuery = null; + Selector selector = getSelector(queryParams); + + if(selector == null) + finalQuery = selectorWithoutFilter; + else + finalQuery = new QueryBuilder(getSelector(queryParams)).limit(numRecords).build(); + Database dbWithTenant = null; + try { + dbWithTenant = getDatabaseForTenant(tenantId, SCHEMA_DATABASE); + } catch (MalformedURLException e) { + throw new ApplicationException("Unable to find database for tenant " + tenantId); + } + + QueryResult results = dbWithTenant.query(finalQuery, SchemaDoc.class); + List schemaList = new LinkedList<>(); + + for (SchemaDoc doc : results.getDocs()) { + schemaList.add(doc.getSchemaInfo()); + } + + if (queryParams.getLatestVersion() != null && queryParams.getLatestVersion()) { + return getLatestVersionSchemaList(schemaList); + } + + return schemaList; + } + + private Selector getSelector(QueryParams queryParams) throws ApplicationException { + + HashMap filterHashMap = getFilters(queryParams); + + List expressionList = new ArrayList(); + + for (String filter : filterHashMap.keySet()) { + try { + expressionList.add(eq(filter, (Long) filterHashMap.get(filter))); + } catch (ClassCastException e) { + expressionList.add(eq(filter, filterHashMap.get(filter))); + } + } + + Selector finalSelector = null; + if (expressionList.size() == 1) + finalSelector = expressionList.get(0); + else if (expressionList.size() > 1) { + Expression[] expressionArray = expressionList.toArray(new Expression[0]); + finalSelector = and(expressionArray); + } + return finalSelector; + + } + + private HashMap getFilters(QueryParams queryParams) { + HashMap filterHashMap = new HashMap(); + if (queryParams.getAuthority() != null) { + filterHashMap.put(AUTHORITY, queryParams.getAuthority()); + } + if (queryParams.getSource() != null) { + filterHashMap.put(SOURCE, queryParams.getSource()); + } + if (queryParams.getEntityType() != null) { + filterHashMap.put(ENTITY_TYPE, queryParams.getEntityType()); + } + if (queryParams.getSchemaVersionMajor() != null) { + filterHashMap.put(SCHEMA_VERSION_MAJOR, + queryParams.getSchemaVersionMajor()); + } + if (queryParams.getSchemaVersionMinor() != null) { + filterHashMap.put(SCHEMA_VERSION_MINOR, + queryParams.getSchemaVersionMinor()); + } + if (queryParams.getSchemaVersionPatch() != null) { + filterHashMap.put(SCHEMA_VERSION_PATCH, queryParams.getSchemaVersionPatch()); + } + if (queryParams.getScope() != null) { + filterHashMap.put(SCOPE, queryParams.getScope()); + } + if (queryParams.getStatus() != null) { + filterHashMap.put(STATUS, queryParams.getStatus()); + } + return filterHashMap; + } + + private List getLatestVersionSchemaList(List filteredSchemaList) { + List latestSchemaList = new LinkedList<>(); + SchemaInfo previousSchemaInfo = null; + TreeMap sortedMap = new TreeMap<>( + new VersionHierarchyUtil.SortingVersionComparator()); + + for (SchemaInfo schemaInfoObject : filteredSchemaList) { + if ((previousSchemaInfo != null) && !(checkAuthorityMatch(previousSchemaInfo, schemaInfoObject) + && checkSourceMatch(previousSchemaInfo, schemaInfoObject) + && checkEntityMatch(previousSchemaInfo, schemaInfoObject))) { + Entry latestVersionEntry = sortedMap.firstEntry(); + latestSchemaList.add(latestVersionEntry.getValue()); + sortedMap.clear(); + } + previousSchemaInfo = schemaInfoObject; + SchemaIdentity schemaIdentity = schemaInfoObject.getSchemaIdentity(); + VersionHierarchyUtil version = new VersionHierarchyUtil(schemaIdentity.getSchemaVersionMajor(), + schemaIdentity.getSchemaVersionMinor(), schemaIdentity.getSchemaVersionPatch()); + sortedMap.put(version, schemaInfoObject); + } + if (sortedMap.size() != 0) { + Entry latestVersionEntry = sortedMap.firstEntry(); + latestSchemaList.add(latestVersionEntry.getValue()); + } + + return latestSchemaList; + } + + private boolean checkEntityMatch(SchemaInfo previousSchemaInfo, SchemaInfo schemaInfoObject) { + return schemaInfoObject.getSchemaIdentity().getEntityType() + .equalsIgnoreCase(previousSchemaInfo.getSchemaIdentity().getEntityType()); + } + + private boolean checkSourceMatch(SchemaInfo previousSchemaInfo, SchemaInfo schemaInfoObject) { + return schemaInfoObject.getSchemaIdentity().getSource() + .equalsIgnoreCase(previousSchemaInfo.getSchemaIdentity().getSource()); + } + + private boolean checkAuthorityMatch(SchemaInfo previousSchemaInfo, SchemaInfo schemaInfoObject) { + return schemaInfoObject.getSchemaIdentity().getAuthority() + .equalsIgnoreCase(previousSchemaInfo.getSchemaIdentity().getAuthority()); + } + + + +} \ No newline at end of file diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSourceStore.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSourceStore.java new file mode 100644 index 0000000000000000000000000000000000000000..31d24a03df959515eb922496eaf7cf35bec03a95 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSourceStore.java @@ -0,0 +1,65 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import java.net.MalformedURLException; +import java.text.MessageFormat; + +import javax.annotation.PostConstruct; + +import org.opengroup.osdu.schema.constants.SchemaConstants; +//import org.opengroup.osdu.schema.credentials.DatastoreFactory; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.impl.schemainfostore.util.IbmDocumentStore; +import org.opengroup.osdu.schema.model.Source; +import org.opengroup.osdu.schema.provider.ibm.SourceDoc; +import org.opengroup.osdu.schema.provider.interfaces.schemainfostore.ISourceStore; +import org.springframework.stereotype.Repository; +import org.springframework.web.context.annotation.RequestScope; + +/** + * Repository class to to register Source in Google store. + * + * + */ +@Repository +@RequestScope +public class IbmSourceStore extends IbmDocumentStore implements ISourceStore { + + @PostConstruct + public void init() throws MalformedURLException { + initFactory(SchemaConstants.SOURCE_KIND); + } + + @Override + public Source get(String sourceId) throws NotFoundException, ApplicationException { + if (db.contains(sourceId)) { + SourceDoc sd = db.find(SourceDoc.class, sourceId); + return sd.getSource(); + } else { + throw new NotFoundException(SchemaConstants.INVALID_INPUT); + } + } + + @Override + public Source create(Source source) throws BadRequestException, ApplicationException { + + if (db.contains(source.getSourceId())) { + logger.warning(SchemaConstants.SOURCE_EXISTS); + throw new BadRequestException( + MessageFormat.format(SchemaConstants.SOURCE_EXISTS_EXCEPTION, source.getSourceId())); + } + SourceDoc sd = new SourceDoc(source); + + try { + db.save(sd); + } catch (Exception ex) { + logger.error(SchemaConstants.OBJECT_INVALID, ex); + throw new ApplicationException(SchemaConstants.INVALID_INPUT); + } + logger.info(SchemaConstants.SOURCE_CREATED); + return sd.getSource(); + } + + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/util/IbmDocumentStore.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/util/IbmDocumentStore.java new file mode 100644 index 0000000000000000000000000000000000000000..2711e289895ba24a26e6d13dcdbe34874c6652b1 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemainfostore/util/IbmDocumentStore.java @@ -0,0 +1,52 @@ +package org.opengroup.osdu.schema.impl.schemainfostore.util; + +import java.net.MalformedURLException; + +import javax.inject.Inject; + +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.ibm.auth.ServiceCredentials; +import org.opengroup.osdu.core.ibm.cloudant.IBMCloudantClientFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.springframework.beans.factory.annotation.Value; + +import com.cloudant.client.api.Database; + +/** + * Repository class to to register authority in IBM store. + * + */ +public class IbmDocumentStore { + + public static final String SCHEMA_DATABASE = "schema2"; + public static final long LIMIT_SIZE = 25; + + @Value("${ibm.db.url}") + private String dbUrl; + @Value("${ibm.db.user:#{null}}") + private String dbUser; + @Value("${ibm.db.password:#{null}}") + private String dbPassword; + @Value("${ibm.env.prefix:local-dev}") + private String dbNamePrefix; + + @Inject + private DpsHeaders headers; + + @Inject + protected JaxRsDpsLog logger; + + private IBMCloudantClientFactory cloudantFactory; + protected Database db = null; + + public void initFactory(String dbName) throws MalformedURLException { + cloudantFactory = new IBMCloudantClientFactory(new ServiceCredentials(dbUrl, dbUser, dbPassword)); + db = cloudantFactory.getDatabase(dbNamePrefix, SchemaConstants.NAMESPACE + "-" + headers.getPartitionIdWithFallbackToAccountId() + "-" + dbName); + } + + public Database getDatabaseForTenant(String tenantId, String dbName) throws MalformedURLException { + return cloudantFactory.getDatabase(dbNamePrefix, SchemaConstants.NAMESPACE + "-" + tenantId + "-" + dbName); + } + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemastore/IBMSchemaStore.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemastore/IBMSchemaStore.java new file mode 100644 index 0000000000000000000000000000000000000000..54485f674e1b85575bbc07dbc90ee424ef0b6770 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/impl/schemastore/IBMSchemaStore.java @@ -0,0 +1,143 @@ +package org.opengroup.osdu.schema.impl.schemastore; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +import javax.annotation.PostConstruct; +import javax.inject.Inject; + +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.ibm.objectstorage.CloudObjectStorageFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.provider.interfaces.schemastore.ISchemaStore; +import org.springframework.stereotype.Repository; +import org.springframework.web.context.annotation.RequestScope; + +import com.ibm.cloud.objectstorage.services.s3.AmazonS3; +import com.ibm.cloud.objectstorage.services.s3.model.ObjectMetadata; +import com.ibm.cloud.objectstorage.services.s3.model.PutObjectRequest; + +/** + * Repository class to to register resolved Schema in IBM storage. + * + * + */ +@Repository +@RequestScope +public class IBMSchemaStore implements ISchemaStore { + + @Inject + private DpsHeaders headers; + + @Inject + private CloudObjectStorageFactory cosFactory; + + @Inject + private JaxRsDpsLog logger; + + AmazonS3 s3Client; + + @PostConstruct + public void init() { + s3Client = cosFactory.getClient(); + logger.info("COS client initialized"); + } + + /** + * Method to get schema from IBM Storage given Tenant ProjectInfo + * + * @param dataPartitionId + * @param schemaId + * @throws NotFoundException + * @return schema object + * @throws ApplicationException + * @throws NotFoundException + */ + @Override + public String getSchema(String dataPartitionId, String schemaId) throws ApplicationException, NotFoundException { + // dataPartitionId not used b/c getting from header + + String content; + try { + content = getObjectAsString(schemaId); + } catch (Exception e) { + throw new ApplicationException(SchemaConstants.INTERNAL_SERVER_ERROR); + } + if (content != null) + return content; + throw new NotFoundException(SchemaConstants.SCHEMA_NOT_PRESENT); + + } + + /** + * Method to write schema to IBM Storage given Tenant ProjectInfo + * + * @param schemaId + * @param content + * @return schema object + * @throws ApplicationException + */ + + @Override + public String createSchema(String schemaId, String content) throws ApplicationException { + + byte[] bytes = content.getBytes(StandardCharsets.UTF_8); + int bytesSize = bytes.length; + + InputStream newStream = new ByteArrayInputStream(bytes); + + ObjectMetadata metadata = new ObjectMetadata(); + metadata.setContentLength(bytesSize); + + String bucket; + try { + bucket = getSchemaBucketName(); + PutObjectRequest req = new PutObjectRequest(bucket, schemaId, newStream, metadata); + s3Client.putObject(req); + + } catch (Exception e) { + throw new ApplicationException(SchemaConstants.INTERNAL_SERVER_ERROR); + } + + return s3Client.getUrl(bucket, schemaId).toString(); + } + + private String getObjectAsString(String objectName) throws Exception { + return s3Client.getObjectAsString(getSchemaBucketName(), objectName); + } + + private String getSchemaBucketName() throws Exception { + return getSchemaBucketName(headers.getPartitionIdWithFallbackToAccountId()); + } + + private String getSchemaBucketName(String dataPartitionId) throws Exception { + return cosFactory.getBucketName(dataPartitionId, "schema"); + } + + + /** + * Method to clean schema object from IBM Storage given schemaId + * + * @param schemaId + * @return boolean + * @throws ApplicationException + */ + + @Override + public boolean cleanSchemaProject(String schemaId) throws ApplicationException { + logger.info("Delete schema: " + schemaId); + try { + s3Client.deleteObject(getSchemaBucketName(), schemaId); + logger.info("Scehma deleted: " + schemaId); + return true; + } catch (Exception e) { + logger.error("Failed to delete schema " +schemaId); + return false; + } + } + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/AuthorityDoc.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/AuthorityDoc.java new file mode 100644 index 0000000000000000000000000000000000000000..724c9d017b6abeaae7191756b937ba146ee1e663 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/AuthorityDoc.java @@ -0,0 +1,56 @@ +/** + * Copyright 2020 IBM Corp. All Rights Reserved. + * + * 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.opengroup.osdu.schema.provider.ibm; + +import org.opengroup.osdu.schema.model.Authority; + +public class AuthorityDoc { + + private String _id; + private String _rev; + private Authority authority; + + public AuthorityDoc(Authority authority) { + this.setId(authority.getAuthorityId()); + this.setAuthority(authority); + } + + public String getId() { + return _id; + } + + public void setId(String _id) { + this._id = _id; + } + + public String getRev() { + return _rev; + } + + public void setRev(String _rev) { + this._rev = _rev; + } + + public Authority getAuthority() { + return authority; + } + + public void setAuthority(Authority authority) { + this.authority = authority; + } + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/EntityTypeDoc.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/EntityTypeDoc.java new file mode 100644 index 0000000000000000000000000000000000000000..ac546ef94599e5dbfcb832c4e7422d220a1dea33 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/EntityTypeDoc.java @@ -0,0 +1,56 @@ +/** + * Copyright 2020 IBM Corp. All Rights Reserved. + * + * 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.opengroup.osdu.schema.provider.ibm; + +import org.opengroup.osdu.schema.model.EntityType; + +public class EntityTypeDoc { + + private String _id; + private String _rev; + private EntityType entityType; + + public EntityTypeDoc(EntityType entityType) { + this.setId(entityType.getEntityTypeId()); + this.setEntityType(entityType); + } + + public String getId() { + return _id; + } + + public void setId(String _id) { + this._id = _id; + } + + public String getRev() { + return _rev; + } + + public void setRev(String _rev) { + this._rev = _rev; + } + + public EntityType getEntityType() { + return entityType; + } + + public void setEntityType(EntityType entityType) { + this.entityType = entityType; + } + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/SchemaDoc.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/SchemaDoc.java new file mode 100644 index 0000000000000000000000000000000000000000..3848221797ac57279e813d6cb45c838ca86f739c --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/SchemaDoc.java @@ -0,0 +1,88 @@ +/** + * Copyright 2020 IBM Corp. All Rights Reserved. + * + * 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.opengroup.osdu.schema.provider.ibm; + +import java.util.Date; + +import org.opengroup.osdu.schema.model.SchemaIdentity; +import org.opengroup.osdu.schema.model.SchemaInfo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class SchemaDoc extends SchemaInfo { + + private String _id; + private String _rev; + private long createdDate; + + public SchemaDoc(SchemaInfo schemaInfo) { + this.set_id(schemaInfo.getSchemaIdentity().getId()); + super.setCreatedBy(schemaInfo.getCreatedBy()); + if (schemaInfo.getDateCreated() != null) { + this.setCreatedDate(schemaInfo.getDateCreated().getTime()); + super.setDateCreated(null); + } + // sub objects + super.setStatus(schemaInfo.getStatus()); + schemaInfo.getSchemaIdentity().setId(null); + super.setSchemaIdentity(schemaInfo.getSchemaIdentity()); + super.setScope(schemaInfo.getScope()); + super.setSupersededBy(schemaInfo.getSupersededBy()); + } + + public SchemaInfo getSchemaInfo() { + SchemaIdentity schemaIdentity = super.getSchemaIdentity(); + schemaIdentity.setId(this._id); + + SchemaInfo info = new SchemaInfo(); + info.setSchemaIdentity(schemaIdentity); + info.setCreatedBy(super.getCreatedBy()); + info.setDateCreated(new Date(this.createdDate)); + info.setStatus(super.getStatus()); + info.setScope(super.getScope()); + info.setSupersededBy(super.getSupersededBy()); + return info; + + // return SchemaInfo(schemaIdentity, super.getCreatedBy(), (new Date(this.createdDate)), + // super.getStatus(), super.getScope(), super.getSupersededBy()); + } + + public String getRev() { + return this._rev; + } + + public void setRev(String rev) { + this._rev = rev; + } + + public String getId() { + return _id; + } + public String getKind() { + return _id; + } + + + + + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/SourceDoc.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/SourceDoc.java new file mode 100644 index 0000000000000000000000000000000000000000..0fe0886032abfcb52950066494022e23fbc001cb --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/SourceDoc.java @@ -0,0 +1,56 @@ +/** + * Copyright 2020 IBM Corp. All Rights Reserved. + * + * 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.opengroup.osdu.schema.provider.ibm; + +import org.opengroup.osdu.schema.model.Source; + +public class SourceDoc { + + private String _id; + private String _rev; + private Source source; + + public SourceDoc(Source source) { + this.setId(source.getSourceId()); + this.setSource(source); + } + + public String getId() { + return _id; + } + + public void setId(String _id) { + this._id = _id; + } + + public String getRev() { + return _rev; + } + + public void setRev(String _rev) { + this._rev = _rev; + } + + public Source getSource() { + return source; + } + + public void setSource(Source source) { + this.source = source; + } + +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/app/SchemaIBMApplication.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/app/SchemaIBMApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..9d283a94de499b25fd19875ced8c8a16ddf7bef0 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/app/SchemaIBMApplication.java @@ -0,0 +1,36 @@ +// Copyright 2020 IBM Corp. All Rights Reserved. +// +// 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.opengroup.osdu.schema.provider.ibm.app; + +import javax.annotation.PostConstruct; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan({ "org.opengroup.osdu" }) +public class SchemaIBMApplication { + + @PostConstruct + void f() { + + } + + public static void main(String[] args) { + + SpringApplication.run(SchemaIBMApplication.class, args); + } +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/security/SecurityConfig.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/security/SecurityConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..6f724df0d87d76083cadaa43aae946ca51c08fe1 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/security/SecurityConfig.java @@ -0,0 +1,26 @@ +package org.opengroup.osdu.schema.provider.ibm.security; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +@Order(Ordered.HIGHEST_PRECEDENCE) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .authorizeRequests() + .antMatchers("/v1/api-docs", + "/configuration/ui", + "/swagger-resources/**", + "/configuration/security", + "/swagger-ui.html", + "/webjars/**").permitAll() + .anyRequest().authenticated().and().oauth2ResourceServer().jwt(); + } +} diff --git a/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/security/WhoamiController.java b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/security/WhoamiController.java new file mode 100644 index 0000000000000000000000000000000000000000..569b1a490e467d24d32a6ef9c4335d31b711d355 --- /dev/null +++ b/provider/schema-ibm/src/main/java/org/opengroup/osdu/schema/provider/ibm/security/WhoamiController.java @@ -0,0 +1,40 @@ +package org.opengroup.osdu.schema.provider.ibm.security; +/** + * Copyright 2020 IBM Corp. All Rights Reserved. + * + * 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. + */ + + +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class WhoamiController { + @RequestMapping(value = {"/", "/whoami"}) + @ResponseBody + public String whoami() { + final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + + String userName = auth.getName(); + String roles = String.valueOf(auth.getAuthorities()); + String details = String.valueOf(auth.getPrincipal()); + + return "user: " + userName + "
" + + "roles: " + roles + "
" + + "details: " + details; + } +} diff --git a/provider/schema-ibm/src/main/resources/application.properties b/provider/schema-ibm/src/main/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..83acee06f4268bd493eddafa7230547859583082 --- /dev/null +++ b/provider/schema-ibm/src/main/resources/application.properties @@ -0,0 +1,22 @@ +LOG_PREFIX=schema +server.servlet.context-path=/api/schema-service/v1 +logging.level.org.springframework.web=DEBUG +spring.security.oauth2.resourceserver.jwt.jwk-set-uri=TBD +AUTHORIZE_API=TBD +AUTHORIZE_API_KEY= + +ibm.env.prefix= +ibm.cos.endpoint_url=TODO +ibm.cos.access_key=TODO +ibm.cos.secret_key=TODO + +#couch db for dev cluster +ibm.db.url=TODO +ibm.db.user=TODO +ibm.db.password=TODO +ibm.tenant.db.url=TODO +ibm.tenant.db.user=TODO +ibm.tenant.db.password=TODO +ibm.tenant.db.name=TODO + +spring.main.allow-bean-definition-overriding=true diff --git a/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmAuthorityStoreTest.java b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmAuthorityStoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..83e47cf551b35eb202842d2aec4e49b848dd79c2 --- /dev/null +++ b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmAuthorityStoreTest.java @@ -0,0 +1,137 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import static org.mockito.ArgumentMatchers.*; + +import java.net.MalformedURLException; + +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.ibm.cloudant.IBMCloudantClientFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.model.Authority; +import org.opengroup.osdu.schema.provider.ibm.AuthorityDoc; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.cloudant.client.api.Database; +import com.cloudant.client.org.lightcouch.DocumentConflictException; + +@RunWith(SpringJUnit4ClassRunner.class) +public class IbmAuthorityStoreTest { + + @InjectMocks + IbmAuthorityStore mockIbmAuthorityStore; + + @Mock + protected JaxRsDpsLog logger; + + @Mock + IBMCloudantClientFactory cloudantFactory; + + @Mock + Database db; + + @Mock + Authority mockAuthority; + + @Mock + AuthorityDoc mockAuthorityDoc; + + @Mock + DpsHeaders headers; + + private static final String dataPartitionId = "testPartitionId"; + + @Test + public void testGetAuthority() throws NotFoundException, ApplicationException, MalformedURLException { + String authorityId = "testAuthorityId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(authorityId)).thenReturn(true); + Mockito.when(db.find(AuthorityDoc.class, authorityId)).thenReturn(mockAuthorityDoc); + Mockito.when(mockAuthorityDoc.getAuthority()).thenReturn(mockAuthority); + assertNotNull(mockIbmAuthorityStore.get(authorityId)); + } + + @Test + public void testGetAuthority_NotFoundException() { + String authorityId = "testAuthorityId"; + try { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(authorityId)).thenReturn(false); + + mockIbmAuthorityStore.get(authorityId); + fail("Should not succeed"); + } catch (NotFoundException e) { + assertEquals(SchemaConstants.INVALID_INPUT, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreateAuthority() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(mockAuthorityDoc.getAuthority()).thenReturn(mockAuthority); + + assertNotNull(mockIbmAuthorityStore.create(mockAuthority)); + } + + @Test + public void testCreateAuthority_BadRequestException() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + String authorityId = "testAuthorityId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + mockIbmAuthorityStore = Mockito.spy(mockIbmAuthorityStore); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(true); + + Mockito.when(mockAuthority.getAuthorityId()).thenReturn(authorityId); + try { + mockIbmAuthorityStore.create(mockAuthority); + fail("Should not succeed"); + } catch (BadRequestException e) { + assertEquals("Authority already registered with Id: "+authorityId, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreateAuthority_ApplicationException() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + String authorityId = "testAuthorityId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + mockIbmAuthorityStore = Mockito.spy(mockIbmAuthorityStore); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(db.save(any(AuthorityDoc.class))).thenThrow(DocumentConflictException.class); + Mockito.when(mockAuthority.getAuthorityId()).thenReturn(authorityId); + try { + mockIbmAuthorityStore.create(mockAuthority); + fail("Should not succeed"); + } catch (ApplicationException e) { + assertEquals(SchemaConstants.INVALID_INPUT, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + +} diff --git a/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmEntityTypeStoreTest.java b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmEntityTypeStoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fb78ff75cde433e1a6e92e67ded69533d63cb3a6 --- /dev/null +++ b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmEntityTypeStoreTest.java @@ -0,0 +1,144 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +//import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; + +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.mockito.Mock; +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +//import org.mockito.Mockito; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.ibm.cloudant.IBMCloudantClientFactory; +import org.opengroup.osdu.schema.model.EntityType; +import org.opengroup.osdu.schema.provider.ibm.EntityTypeDoc; +import org.opengroup.osdu.schema.constants.SchemaConstants; +//import org.opengroup.osdu.core.common.model.tenant.TenantInfo; +//import org.opengroup.osdu.core.ibm.multitenancy.TenantFactory; +//import org.opengroup.osdu.schema.constants.SchemaConstants; +//import org.opengroup.osdu.schema.credentials.DatastoreFactory; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.model.Authority; +import org.opengroup.osdu.schema.provider.ibm.AuthorityDoc; + +import java.net.MalformedURLException; +//import org.opengroup.osdu.schema.model.EntityType; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.cloudant.client.api.Database; +import com.cloudant.client.org.lightcouch.DocumentConflictException; + +@RunWith(SpringJUnit4ClassRunner.class) +public class IbmEntityTypeStoreTest { +// + @InjectMocks + IbmEntityTypeStore mockIbmEntityStore; + + @Mock + IBMCloudantClientFactory cloudantFactory; + + @Mock + Database db; + + @Mock + EntityType mockEntityType; + + @Mock + EntityTypeDoc mockEntityTypeDoc; + + @Mock + DpsHeaders headers; + + @Mock + protected JaxRsDpsLog logger; + + private static final String dataPartitionId = "testPartitionId"; + + @Test + public void testGet() throws NotFoundException, ApplicationException, MalformedURLException { + String entityId = "testEntityId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(entityId)).thenReturn(true); + Mockito.when(db.find(EntityTypeDoc.class, entityId)).thenReturn(mockEntityTypeDoc); + Mockito.when(mockEntityTypeDoc.getEntityType()).thenReturn(mockEntityType); + assertNotNull(mockIbmEntityStore.get(entityId)); + } + + @Test + public void testGet_NotFoundException() { + String entityId = "testEntityId"; + try { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(entityId)).thenReturn(false); + mockIbmEntityStore.get(entityId); + fail("Should not succeed"); + } catch (NotFoundException e) { + assertEquals(SchemaConstants.INVALID_INPUT, e.getMessage()); + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreateEntityType() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(mockEntityTypeDoc.getEntityType()).thenReturn(mockEntityType); + + assertNotNull(mockIbmEntityStore.create(mockEntityType)); + } + + @Test + public void testCreate_BadRequestException() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + String entityId = "testEntityId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + mockIbmEntityStore = Mockito.spy(mockIbmEntityStore); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(true); + Mockito.when(mockEntityType.getEntityTypeId()).thenReturn(entityId); + + try { + mockIbmEntityStore.create(mockEntityType); + fail("Should not succeed"); + } catch (BadRequestException e) { + assertEquals("EntityType already registered with Id: "+entityId, e.getMessage()); + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreate_ApplicationException() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + String entityId = "testEntityId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + mockIbmEntityStore = Mockito.spy(mockIbmEntityStore); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(db.save(any(EntityTypeDoc.class))).thenThrow(DocumentConflictException.class); + Mockito.when(mockEntityType.getEntityTypeId()).thenReturn(entityId); + + try { + mockIbmEntityStore.create(mockEntityType); + fail("Should not succeed"); + } catch (ApplicationException e) { + assertEquals(SchemaConstants.INVALID_INPUT, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + +} diff --git a/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSchemaInfoStoreTest.java b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSchemaInfoStoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..65a786fe932896f3ec1e7d416572db3503b13d1a --- /dev/null +++ b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSchemaInfoStoreTest.java @@ -0,0 +1,528 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import java.net.MalformedURLException; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import static org.mockito.ArgumentMatchers.*; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.common.model.tenant.TenantInfo; +import org.opengroup.osdu.core.ibm.cloudant.IBMCloudantClientFactory; +import org.opengroup.osdu.core.ibm.multitenancy.TenantFactory; +import org.opengroup.osdu.core.ibm.objectstorage.CloudObjectStorageFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.enums.SchemaScope; +import org.opengroup.osdu.schema.enums.SchemaStatus; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.opengroup.osdu.schema.impl.schemastore.IBMSchemaStore; +import org.opengroup.osdu.schema.model.QueryParams; +import org.opengroup.osdu.schema.model.SchemaIdentity; +import org.opengroup.osdu.schema.model.SchemaInfo; +import org.opengroup.osdu.schema.model.SchemaRequest; +import org.opengroup.osdu.schema.provider.ibm.SchemaDoc; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.cloudant.client.api.Database; +import com.cloudant.client.api.query.QueryResult; +import com.cloudant.client.org.lightcouch.DocumentConflictException; +import com.ibm.cloud.objectstorage.services.s3.AmazonS3; + + +@RunWith(SpringJUnit4ClassRunner.class) +public class IbmSchemaInfoStoreTest { + + @InjectMocks + IbmSchemaInfoStore schemaInfoStore; + + @Mock + JaxRsDpsLog logger; + + @Mock + IBMCloudantClientFactory cloudantFactory; + + @Mock + Database db; + + @Mock + SchemaDoc schemaDoc; + + @Mock + SchemaInfo schemaInfo; + + @Mock + SchemaRequest schemaRequest; + + @Mock + TenantInfo tenantInfo; + + @Mock + TenantInfo tenantInfoCommon; + + @Mock + TenantFactory tenantFactory; + + @Mock + DpsHeaders headers; + + @Mock + QueryResult queryResults; + + @Mock + QueryResult queryResult; + + @Mock + IBMSchemaStore schemaStore; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private static final String dataPartitionId = "testPartitionId"; + + + @Test + public void testGetLatestMinorVersion_ReturnNull() throws NotFoundException, ApplicationException, MalformedURLException { + String query = "{\"selector\": {\"$and\": [{\"schemaIdentity.authority\": {\"$eq\": \"os\"}}, {\"schemaIdentity.entityType\": {\"$eq\": \"well\"}}, {\"schemaIdentity.schemaVersionMajor\": {\"$eq\": 1}}, {\"schemaIdentity.source\": {\"$eq\": \"wks\"}}]}}"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + + Mockito.when(db.query(query, SchemaDoc.class)).thenReturn(queryResults); + assertEquals("", schemaInfoStore.getLatestMinorVerSchema(getMockSchemaInfo())); + } + + @Test + public void testGetSchemaInfo_NotEmpty() throws NotFoundException, ApplicationException { + String schemaId = "schemaId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(db.contains(schemaId)).thenReturn(true); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + + SchemaInfo schemaInfo = schemaInfoStore.getSchemaInfo(schemaId); + assertNotNull(schemaInfo); + } + + @Test + public void testGetSchemaInfo_Empty() throws NotFoundException, ApplicationException { + + expectedException.expect(NotFoundException.class); + expectedException.expectMessage(SchemaConstants.SCHEMA_NOT_PRESENT); + String schemaId = "schemaId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(db.contains(schemaId)).thenReturn(false); + schemaInfoStore.getSchemaInfo(schemaId); + } + + + + @Test + public void testCreateSchemaInfo_Positive() throws ApplicationException, BadRequestException { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + assertNotNull(schemaInfoStore.createSchemaInfo(getMockSchemaObject_Published())); + } + + + @Test + public void testIsUnique_True() throws ApplicationException, MalformedURLException { + + String schemaId = "schemaId"; + String tenantId = "tenant"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + assertTrue(schemaInfoStore.isUnique(schemaId, tenantId)); + } + + @Test + public void testIsUnique_False() throws ApplicationException, MalformedURLException { + String schemaId = "schemaId"; + String tenantId = "tenant"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(true); + assertFalse(schemaInfoStore.isUnique(schemaId, tenantId)); + } + + @Test + public void testIsUnique_False_CommomTenant() throws ApplicationException, MalformedURLException { + String schemaId = "schemaId"; + String tenantId = "common"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(tenantFactory.getTenantInfo("tenant")).thenReturn(tenantInfo); + Mockito.when(tenantFactory.getTenantInfo("common")).thenReturn(tenantInfoCommon); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(true); + assertFalse(schemaInfoStore.isUnique(schemaId, tenantId)); + } + + + @Test + public void testUpdateSchemaInfo() throws NotFoundException, ApplicationException, BadRequestException { + String schemaId = "os:wks:well.1.1.1"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(tenantFactory.getTenantInfo("test")).thenReturn(tenantInfo); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + assertNotNull(schemaInfoStore.updateSchemaInfo(getMockSchemaObject_Published())); + } + + @Test + public void testCreateSchemaInfo_WithSupersededBy() + throws NotFoundException, ApplicationException, BadRequestException { + String schemaId = "os:wks:well.1.1.1"; + String superSededId = "os:wks:well.1.2.1"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(tenantFactory.getTenantInfo("test")).thenReturn(tenantInfo); + Mockito.when(db.contains(schemaId)).thenReturn(false); + Mockito.when(db.contains(superSededId)).thenReturn(true); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + assertNotNull(schemaInfoStore.createSchemaInfo(getMockSchemaObject_SuperSededBy())); + } + + @Test + public void testUpdateSchemaInfo_SupersededByException() + throws NotFoundException, ApplicationException, BadRequestException { + try { + + String schemaId = "os:wks:well.1.1.1"; + String superSededId = "os:wks:well.1.2.1"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(tenantFactory.getTenantInfo("test")).thenReturn(tenantInfo); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + Mockito.when(db.contains(superSededId)).thenReturn(false); + + schemaInfoStore.updateSchemaInfo(getMockSchemaObject_SuperSededBy()); + fail("Should not succeed"); + } catch (BadRequestException e) { + assertEquals("Invalid SuperSededBy id", e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testUpdateInfo_SupersededByWithoutIdException() + throws NotFoundException, ApplicationException, BadRequestException { + String schemaId = "os:wks:well.1.1.1"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(tenantFactory.getTenantInfo("test")).thenReturn(tenantInfo); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + + SchemaRequest schemaRequest = getMockSchemaObject_SuperSededByWithoutId(); + expectedException.expect(BadRequestException.class); + expectedException.expectMessage(SchemaConstants.INVALID_SUPERSEDEDBY_ID); + schemaInfoStore.updateSchemaInfo(schemaRequest); + } + + @Test + public void testCreateSchemaInfo_BadRequestException() + throws NotFoundException, ApplicationException, BadRequestException { + + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(db.contains(anyString())).thenReturn(true); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + + try { + schemaInfoStore.createSchemaInfo(getMockSchemaObject_Published()); + fail("Should not succeed"); + } catch (BadRequestException e) { + assertEquals("Schema os:wks:well.1.1.1 already exist. Can't create again.", e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreateSchemaInfo_ApplicationException() + throws NotFoundException, ApplicationException, BadRequestException { + + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + Mockito.when(db.save(any(SchemaDoc.class))).thenThrow(DocumentConflictException.class); + + try { + schemaInfoStore.createSchemaInfo(getMockSchemaObject_Published()); + fail("Should not succeed"); + } catch (ApplicationException e) { + assertEquals(SchemaConstants.SCHEMA_CREATION_FAILED_INVALID_OBJECT, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testUpdateSchemaInfo_ApplicationException() + throws NotFoundException, ApplicationException, BadRequestException { + + String schemaId = "os:wks:well.1.1.1"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(tenantFactory.getTenantInfo("test")).thenReturn(tenantInfo); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + Mockito.when(schemaDoc.getSchemaInfo()).thenReturn(schemaInfo); + Mockito.when(db.update(any(SchemaDoc.class))).thenThrow(DocumentConflictException.class); + + try { + schemaInfoStore.updateSchemaInfo(getMockSchemaObject_Published()); + fail("Should not succeed"); + } catch (ApplicationException e) { + assertEquals("Invalid object, updation failed", e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testGetLatestMinorVersion_Entity() throws NotFoundException, ApplicationException { + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(getMockSchemaDocObject()); + Mockito.when(db.query(Mockito.any(), Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + Mockito.when(schemaStore.getSchema(any(), anyString())).thenReturn("{}"); + assertEquals("{}", schemaInfoStore.getLatestMinorVerSchema(getMockSchemaInfo())); + } + + @Test + public void testGetSchemaInfoList_withoutqueryparam() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(getMockSchemaDocObject()); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + assertEquals(1, + schemaInfoStore.getSchemaInfoList(QueryParams.builder().limit(100).offset(0).build(), "test").size()); + } + + @Test + public void testGetSchemaInfoList_withqueryparam() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(getMockSchemaDocObject()); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + assertEquals(1, + schemaInfoStore.getSchemaInfoList(QueryParams.builder().authority("test").source("test").entityType("test") + .schemaVersionMajor(1l).schemaVersionMinor(1l).scope("test").status("test").latestVersion(false) + .limit(100).offset(0).build(), "test").size()); + } + + @Test + public void testGetSchemaInfoList_latestVersionTrue_NoSchemaMatchScenario() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + assertEquals(0, + schemaInfoStore + .getSchemaInfoList(QueryParams.builder().authority("test").source("test").entityType("test") + .scope("test").status("test").latestVersion(true).limit(100).offset(0).build(), "test") + .size()); + } + + @Test + public void testGetSchemaInfoList_LatestVersionFunctionalityTest_SchemasWithDifferentMajorVersion() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + + SchemaIdentity schemaIdentity = new SchemaIdentity("authority","source","entityType",2L,11L,111L,"id"); + SchemaInfo schemaInfo = new SchemaInfo(schemaIdentity,"createdBy", new Date(), SchemaStatus.DEVELOPMENT, SchemaScope.INTERNAL, schemaIdentity); + SchemaRequest schemaRequest = new SchemaRequest(schemaInfo, new Object()); + SchemaDoc schemaDoc = new SchemaDoc(schemaRequest.getSchemaInfo()); + SchemaDoc latestSchemaDoc = getMockSchemaDocObject(); + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(schemaDoc); + schemaDocsList.add(latestSchemaDoc); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + assertEquals(1, schemaInfoStore.getSchemaInfoList( + QueryParams.builder().scope("test").status("test").latestVersion(true).limit(100).offset(0).build(), + "test").size()); + } + + @Test + public void testGetSchemaInfoList_LatestVersionFunctionalityTest_SchemasWithDifferentMinorVersion() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + SchemaIdentity schemaIdentity = new SchemaIdentity("authority","source","entityType",1L,22L,111L,"id"); + SchemaInfo schemaInfo = new SchemaInfo(schemaIdentity,"createdBy", new Date(), SchemaStatus.DEVELOPMENT, SchemaScope.INTERNAL, schemaIdentity); + SchemaRequest schemaRequest = new SchemaRequest(schemaInfo, new Object()); + SchemaDoc schemaDoc = new SchemaDoc(schemaRequest.getSchemaInfo()); + SchemaDoc latestSchemaDoc = getMockSchemaDocObject(); + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(schemaDoc); + schemaDocsList.add(latestSchemaDoc); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + assertEquals(1, schemaInfoStore.getSchemaInfoList( + QueryParams.builder().scope("test").status("test").latestVersion(true).limit(100).offset(0).build(), + "test").size()); + } + + @Test + public void testGetSchemaInfoList_LatestVersionFunctionalityTest_SchemasWithDifferentSource() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + + SchemaIdentity schemaIdentity = new SchemaIdentity("authority","sourceChanged","entityType",1L,11L,111L,"id"); + SchemaInfo schemaInfo = new SchemaInfo(schemaIdentity,"createdBy", new Date(), SchemaStatus.DEVELOPMENT, SchemaScope.INTERNAL, schemaIdentity); + SchemaRequest schemaRequest = new SchemaRequest(schemaInfo, new Object()); + SchemaDoc schemaDoc = new SchemaDoc(schemaRequest.getSchemaInfo()); + SchemaDoc latestSchemaDoc = getMockSchemaDocObject(); + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(schemaDoc); + schemaDocsList.add(latestSchemaDoc); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + + assertEquals(2, schemaInfoStore.getSchemaInfoList( + QueryParams.builder().scope("test").status("test").latestVersion(true).limit(100).offset(0).build(), + "test").size()); + } + + @Test + public void testGetSchemaInfoList_LatestVersionFunctionalityTest_SchemasWithDifferentAuthority() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + + SchemaIdentity schemaIdentity = new SchemaIdentity("authorityChanged","source","entityType",1L,11L,111L,"id"); + SchemaInfo schemaInfo = new SchemaInfo(schemaIdentity,"createdBy", new Date(), SchemaStatus.DEVELOPMENT, SchemaScope.INTERNAL, schemaIdentity); + SchemaRequest schemaRequest = new SchemaRequest(schemaInfo, new Object()); + SchemaDoc schemaDoc = new SchemaDoc(schemaRequest.getSchemaInfo()); + SchemaDoc latestSchemaDoc = getMockSchemaDocObject(); + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(schemaDoc); + schemaDocsList.add(latestSchemaDoc); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + + assertEquals(2, schemaInfoStore.getSchemaInfoList( + QueryParams.builder().scope("test").status("test").latestVersion(true).limit(100).offset(0).build(), + "test").size()); + } + + @Test + public void testGetSchemaInfoList_LatestVersionFunctionalityTest_SchemasWithDifferentEntity() + throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + SchemaIdentity schemaIdentity = new SchemaIdentity("authority","source","entityTypeChanged",1L,11L,111L,"id"); + SchemaInfo schemaInfo = new SchemaInfo(schemaIdentity,"createdBy", new Date(), SchemaStatus.DEVELOPMENT, SchemaScope.INTERNAL, schemaIdentity); + SchemaRequest schemaRequest = new SchemaRequest(schemaInfo, new Object()); + + + SchemaDoc schemaDoc = new SchemaDoc(schemaRequest.getSchemaInfo()); + SchemaDoc latestSchemaDoc = getMockSchemaDocObject(); + List schemaDocsList = new LinkedList<>(); + schemaDocsList.add(schemaDoc); + schemaDocsList.add(latestSchemaDoc); + Mockito.when(cloudantFactory.getDatabase(any(),anyString())).thenReturn(db); + Mockito.when(db.query(Mockito.any(),Mockito.any())).thenReturn(queryResult); + Mockito.when(queryResult.getDocs()).thenReturn(schemaDocsList); + + assertEquals(2, schemaInfoStore.getSchemaInfoList( + QueryParams.builder().scope("test").status("test").latestVersion(true).limit(100).offset(0).build(), + "test").size()); + } + + + @Test + public void testCleanSchema_Success() throws ApplicationException, MalformedURLException { + String schemaId = "schemaId"; + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(schemaId)).thenReturn(true); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + assertEquals(true, schemaInfoStore.cleanSchema(schemaId)); + } + + @Test + public void testCleanSchema_Failure() throws ApplicationException, MalformedURLException { + String schemaId = "schemaId"; + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(schemaId)).thenReturn(false); + Mockito.when(db.find(SchemaDoc.class, schemaId)).thenReturn(schemaDoc); + assertEquals(false, schemaInfoStore.cleanSchema(schemaId)); + } + + private SchemaRequest getMockSchemaObject_Published() { + return SchemaRequest.builder().schema("{}") + .schemaInfo(SchemaInfo.builder() + .schemaIdentity(SchemaIdentity.builder().authority("os").source("wks").entityType("well") + .schemaVersionMajor(1L).schemaVersionMinor(1L).schemaVersionPatch(1L) + .id("os:wks:well.1.1.1").build()) + .scope(SchemaScope.SHARED).status(SchemaStatus.PUBLISHED).createdBy("ibm").build()) + .build(); + + } + + private SchemaInfo getMockSchemaInfo() { + return SchemaInfo.builder().schemaIdentity(SchemaIdentity.builder().authority("os").source("wks").entityType("well") + .schemaVersionMajor(1L).schemaVersionMinor(1L).schemaVersionPatch(1L).id("os:wks:well.1.1.1").build()) + .scope(SchemaScope.SHARED).status(SchemaStatus.PUBLISHED).createdBy("ibm") + + .build(); + + } + + private SchemaRequest getMockSchemaObject_SuperSededBy() { + return SchemaRequest.builder().schema("{}") + .schemaInfo(SchemaInfo.builder() + .schemaIdentity(SchemaIdentity.builder().authority("os").source("wks").entityType("well") + .schemaVersionMajor(1L).schemaVersionMinor(1L).schemaVersionPatch(1L) + .id("os:wks:well.1.1.1").build()) + .scope(SchemaScope.SHARED).status(SchemaStatus.PUBLISHED).createdBy("ibm") + .supersededBy(SchemaIdentity.builder().authority("os").source("wks").entityType("well") + .schemaVersionMajor(1L).schemaVersionMinor(1L).schemaVersionPatch(2L) + .id("os:wks:well.1.2.1").build()) + .build()) + .build(); + + } + + private SchemaRequest getMockSchemaObject_SuperSededByWithoutId() { + return SchemaRequest.builder().schema("{}") + .schemaInfo(SchemaInfo.builder() + .schemaIdentity(SchemaIdentity.builder().authority("os").source("wks").entityType("well") + .schemaVersionMajor(1L).schemaVersionMinor(1L).schemaVersionPatch(1L) + .id("os:wks:well.1.1.1").build()) + .scope(SchemaScope.SHARED).status(SchemaStatus.DEVELOPMENT).createdBy("ibm") + .supersededBy(SchemaIdentity.builder().authority("os").source("wks").entityType("well") + .schemaVersionMajor(1L).schemaVersionMinor(1L).schemaVersionPatch(1L).build()) + .build()) + .build(); + + } + + private SchemaDoc getMockSchemaDocObject() + { + SchemaIdentity schemaIdentity = new SchemaIdentity("authority","source","entityType",1L,11L,111L,"id"); + SchemaInfo schemaInfo = new SchemaInfo(schemaIdentity,"createdBy", new Date(), SchemaStatus.DEVELOPMENT, SchemaScope.INTERNAL, schemaIdentity); + SchemaRequest schemaRequest = new SchemaRequest(schemaInfo, new Object()); + SchemaDoc schemaDoc = new SchemaDoc(schemaRequest.getSchemaInfo()); + + return schemaDoc; + } + +} diff --git a/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSourceStoreTest.java b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSourceStoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dd9a67c100919784e9da3883127db884556d2b80 --- /dev/null +++ b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemainfostore/IbmSourceStoreTest.java @@ -0,0 +1,134 @@ +package org.opengroup.osdu.schema.impl.schemainfostore; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.opengroup.osdu.core.common.logging.JaxRsDpsLog; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; +import org.opengroup.osdu.core.ibm.cloudant.IBMCloudantClientFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.BadRequestException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import java.net.MalformedURLException; +import org.opengroup.osdu.schema.model.Source; +import org.opengroup.osdu.schema.provider.ibm.SourceDoc; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + + +import com.cloudant.client.api.Database; +import com.cloudant.client.org.lightcouch.DocumentConflictException; + +@RunWith(SpringJUnit4ClassRunner.class) +public class IbmSourceStoreTest { + + @InjectMocks + IbmSourceStore sourceStore; + + @Mock + IBMCloudantClientFactory cloudantFactory; + + @Mock + Database db; + + @Mock + Source mockSource; + + @Mock + SourceDoc mockSourceDoc; + + + @Mock + DpsHeaders headers; + + @Mock + protected JaxRsDpsLog logger; + + private static final String dataPartitionId = "testPartitionId"; + + @Test + public void testGet() throws NotFoundException, ApplicationException, MalformedURLException { + String sourceId = "testSourceId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(sourceId)).thenReturn(true); + Mockito.when(db.find(SourceDoc.class, sourceId)).thenReturn(mockSourceDoc); + Mockito.when(mockSourceDoc.getSource()).thenReturn(mockSource); + assertNotNull(sourceStore.get(sourceId)); + } + + @Test + public void testGet_NotFoundException() { + String sourceId = "testSourceId"; + try { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(sourceId)).thenReturn(false); + sourceStore.get(sourceId); + fail("Should not succeed"); + } catch (NotFoundException e) { + assertEquals(SchemaConstants.INVALID_INPUT, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreateSource() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(mockSourceDoc.getSource()).thenReturn(mockSource); + assertNotNull(sourceStore.create(mockSource)); + } + + @Test + public void testCreate_BadRequestException() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + String sourceId = "testSourceId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + sourceStore = Mockito.spy(sourceStore); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(true); + Mockito.when(mockSource.getSourceId()).thenReturn(sourceId); + + try { + sourceStore.create(mockSource); + fail("Should not succeed"); + } catch (BadRequestException e) { + assertEquals("Source already registered with Id: "+sourceId, e.getMessage()); + } catch (Exception e) { + fail("Should not get different exception"); + } + } + + @Test + public void testCreate_ApplicationException() throws NotFoundException, ApplicationException, BadRequestException, MalformedURLException { + String sourceId = "testSourceId"; + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + sourceStore = Mockito.spy(sourceStore); + Mockito.when(cloudantFactory.getDatabase(anyString(),anyString())).thenReturn(db); + Mockito.when(db.contains(anyString())).thenReturn(false); + Mockito.when(db.save(any(SourceDoc.class))).thenThrow(DocumentConflictException.class); + Mockito.when(mockSource.getSourceId()).thenReturn(sourceId); + + try { + sourceStore.create(mockSource); + fail("Should not succeed"); + } catch (ApplicationException e) { + assertEquals(SchemaConstants.INVALID_INPUT, e.getMessage()); + + } catch (Exception e) { + fail("Should not get different exception"); + } + } + +} diff --git a/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemastore/IBMSchemaStoreTest.java b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemastore/IBMSchemaStoreTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3ff75701b877f87a39b857fa1f1e4eb811608f60 --- /dev/null +++ b/provider/schema-ibm/src/test/java/org/opengroup/osdu/schema/impl/schemastore/IBMSchemaStoreTest.java @@ -0,0 +1,101 @@ +package org.opengroup.osdu.schema.impl.schemastore; + + +import static org.mockito.ArgumentMatchers.*; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.opengroup.osdu.core.common.model.http.DpsHeaders; + +import org.opengroup.osdu.core.ibm.objectstorage.CloudObjectStorageFactory; +import org.opengroup.osdu.schema.constants.SchemaConstants; +import org.opengroup.osdu.schema.exceptions.ApplicationException; +import org.opengroup.osdu.schema.exceptions.NotFoundException; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.ibm.cloud.objectstorage.AmazonServiceException; +import com.ibm.cloud.objectstorage.services.s3.AmazonS3; + +import java.net.MalformedURLException; +import java.net.URL; + +@RunWith(SpringJUnit4ClassRunner.class) +public class IBMSchemaStoreTest { + + @InjectMocks + IBMSchemaStore schemaStore; + + @Mock + DpsHeaders headers; + + @Mock + CloudObjectStorageFactory cosFactory; + + @Mock + AmazonS3 s3Client; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + private static final String BUCKET = "schema"; + private static final String dataPartitionId = "testPartitionId"; + private static final String SCHEMA_ID = "test-schema-id"; + private static final String BUCKET_NAME_PREFIX = "sandy-local-dev"; + + private static final String CONTENT = "Hello World"; + + @Test + public void testCreateSchema() throws ApplicationException, MalformedURLException { + String bucketName = String.format("%s-dataecosystem-%s-%s", BUCKET_NAME_PREFIX, dataPartitionId, BUCKET); + URL url = new URL("http://schema/" + SCHEMA_ID); + + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cosFactory.getClient()).thenReturn(s3Client); + Mockito.when(cosFactory.getBucketName(dataPartitionId, BUCKET)).thenReturn(bucketName); + Mockito.when(s3Client.getUrl(bucketName, SCHEMA_ID)).thenReturn(url); + + String objectURL = schemaStore.createSchema(SCHEMA_ID, CONTENT); + Assert.assertEquals(("http://schema/" + SCHEMA_ID), objectURL); + } + + @Test + public void testCreateSchema_Failure() throws ApplicationException, MalformedURLException { + expectedException.expect(ApplicationException.class); + expectedException.expectMessage(SchemaConstants.INTERNAL_SERVER_ERROR); + + String bucketName = String.format("%s-dataecosystem-%s-%s", BUCKET_NAME_PREFIX, dataPartitionId, BUCKET); + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cosFactory.getClient()).thenReturn(s3Client); + Mockito.when(cosFactory.getBucketName(dataPartitionId, BUCKET)).thenReturn(bucketName); + Mockito.when(s3Client.putObject(any())).thenThrow(AmazonServiceException.class); + schemaStore.createSchema(SCHEMA_ID, CONTENT); + } + + @Test + public void testGetSchema() throws ApplicationException, NotFoundException { + String bucketName = String.format("%s-dataecosystem-%s-%s", BUCKET_NAME_PREFIX, dataPartitionId, BUCKET); + + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(cosFactory.getClient()).thenReturn(s3Client); + Mockito.when(cosFactory.getBucketName(dataPartitionId, BUCKET)).thenReturn(bucketName); + Mockito.when(s3Client.getObjectAsString(bucketName, SCHEMA_ID)).thenReturn(CONTENT); + + Assert.assertEquals(CONTENT, schemaStore.getSchema(dataPartitionId, SCHEMA_ID)); + } + + @Test + public void testGetSchema_NotFound() throws ApplicationException, NotFoundException { + expectedException.expect(NotFoundException.class); + expectedException.expectMessage(SchemaConstants.SCHEMA_NOT_PRESENT); + Mockito.when(headers.getPartitionIdWithFallbackToAccountId()).thenReturn(dataPartitionId); + Mockito.when(s3Client.getObjectAsString(dataPartitionId, SCHEMA_ID)).thenReturn(null); + schemaStore.getSchema(dataPartitionId, SCHEMA_ID); + } + +} diff --git a/provider/schema-ibm/src/test/resources/application.properties b/provider/schema-ibm/src/test/resources/application.properties new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/provider/schema-ibm/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/provider/schema-ibm/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000000000000000000000000000000000000..ca6ee9cea8ec189a088d50559325d4e84ff8ad09 --- /dev/null +++ b/provider/schema-ibm/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file diff --git a/schema-core/pom.xml b/schema-core/pom.xml index a1215945de89c1ecbe2ce8c4b9900350293eb713..82beefbaeba47ef9f203a790c8c0590cc97fc8d8 100644 --- a/schema-core/pom.xml +++ b/schema-core/pom.xml @@ -15,6 +15,7 @@ 2.7.0 + 0.0.18 @@ -89,7 +90,7 @@ org.opengroup.osdu os-core-common - 0.0.11 + ${os-core-common.version}