diff --git a/pom.xml b/pom.xml index 30e47c8..6bdacab 100755 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ 1.1.7 2.5 4.8.1 - 2.8.6 + 2.8.9 2.9.4.wso2v1 4.3.1 @@ -93,9 +93,26 @@ test - com.cloudant - cloudant-client - 2.19.1 + javax.json.bind + javax.json.bind-api + 1.0 + + + jakarta.json.bind + jakarta.json.bind-api + 1.0.2 + + + + org.eclipse + yasson + 1.0.7 + runtime + + + com.ibm.cloud + cloudant + 0.0.36 io.swagger diff --git a/src/main/java/application/model/AttorneyModel.java b/src/main/java/application/model/AttorneyModel.java index a43533d..bc4a407 100644 --- a/src/main/java/application/model/AttorneyModel.java +++ b/src/main/java/application/model/AttorneyModel.java @@ -1,98 +1,132 @@ package application.model; -import com.cloudant.client.api.ClientBuilder; -import com.cloudant.client.api.CloudantClient; -import com.cloudant.client.api.Database; -import com.cloudant.client.api.model.Response; -import com.cloudant.client.api.query.QueryBuilder; -import com.cloudant.client.api.query.QueryResult; +import java.util.*; +import java.util.stream.Collectors; +import com.google.gson.Gson; +import com.ibm.cloud.cloudant.v1.Cloudant; +import com.ibm.cloud.cloudant.v1.model.*; +import com.ibm.cloud.sdk.core.service.exception.NotFoundException; import com.google.common.collect.Iterables; import io.swagger.model.Attorney; import io.swagger.model.ModelCase; - -import java.net.MalformedURLException; -import java.net.URL; import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; - -import static com.cloudant.client.api.query.Expression.ne; public class AttorneyModel { - private CloudantClient client = null; - private final Database db; + private String database = null; + private Cloudant service = null; + private ModelHelper modelHelper = null; - public AttorneyModel(String url, String apiKey, String database) { - System.out.println(url); + public AttorneyModel(String serviceName, String database) { + this.database = database; + this.modelHelper = new ModelHelper(); try { - client = ClientBuilder.url(new URL(url)).iamApiKey(apiKey).build(); - } catch (MalformedURLException e) { + service = Cloudant.newInstance(serviceName); + } catch (Exception e) { e.printStackTrace(); } - - System.out.println("Server Version: " + client.serverVersion()); - db = client.database(database, false); } - // New Constructor added to run Unit tests - public AttorneyModel(Database db) { - this.db = db; + public AttorneyModel(Cloudant service, ModelHelper modelHelper) { + this.service = service; + this.modelHelper = modelHelper; } - public Response save(Attorney attorney) { - Response resp = db.save(attorney); + public DocumentResult save(Attorney attorney) { + Gson gson = new Gson(); + DocumentResult resp = null; + if(attorney != null) { + Document attorneyDocument = new Document(); + attorneyDocument.setProperties(gson.fromJson(gson.toJson(attorney), Map.class)); + PostDocumentOptions createDocumentOptions = modelHelper.getPostDocumentOptions(attorneyDocument, database); + resp = service + .postDocument(createDocumentOptions) + .execute() + .getResult(); + } return resp; } - public Response delete(String id) { - Attorney attorney = db.find(Attorney.class, id); - Response resp = db.remove(attorney); - return resp; + public DocumentResult delete(String id) { + DocumentResult deleteDocumentResponse = null; + try { + // Set the options to get the document out of the database if it exists + GetDocumentOptions documentInfoOptions = modelHelper.getGetDocumentOptions(id,database); + // Try to get the document if it previously existed in the database + Document document = service + .getDocument(documentInfoOptions) + .execute() + .getResult(); + // Delete the document from the database + DeleteDocumentOptions deleteDocumentOptions = + modelHelper.getDeleteDocumentOptions(id, document.getRev(), database); + deleteDocumentResponse = service + .deleteDocument(deleteDocumentOptions) + .execute() + .getResult(); + if (deleteDocumentResponse.isOk()) { + System.out.println("You have deleted the document."); + } + } catch (NotFoundException nfe) { + System.out.println("Cannot delete because document was not found " + nfe); + } + return deleteDocumentResponse; } - public Attorney read(String id) { - Attorney attorney = db.find(Attorney.class, id); + public Attorney getAttorney(String id) { + Gson gson = new Gson(); + GetDocumentOptions getDocOptions = modelHelper.getGetDocumentOptions(id, database); + Document attorneyDocument = service + .getDocument(getDocOptions) + .execute() + .getResult(); + Attorney attorney = attorneyDocument != null ? gson.fromJson(attorneyDocument.toString(),Attorney.class): null; + return attorney; } public String getUuid() { - return Iterables.getOnlyElement(client.uuids(1)); + return Iterables.getOnlyElement(service.getUuids().execute().getResult().getUuids()); } - public Response addCaseToAttorney(String id, ModelCase modelCase) { - Attorney attorney = db.find(Attorney.class, id); - + public DocumentResult addCaseToAttorney(String id, ModelCase modelCase) { + Attorney attorney = getAttorney(id); if (attorney.getCases() == null) attorney.setCases(new ArrayList<>()); attorney.getCases().add(modelCase); - Response response = db.update(attorney); + DocumentResult response = save(attorney); return response; } - public Response deleteCaseFromAttorney(String id, String caseId) { - Attorney attorney = db.find(Attorney.class, id); + public DocumentResult deleteCaseFromAttorney(String id, String caseId) { + Attorney attorney = getAttorney(id); attorney.getCases().removeIf(i -> i.getId().equalsIgnoreCase(caseId)); - Response response = db.update(attorney); + DocumentResult response = save(attorney); return response; } public List getCasesForAttorney(String id) { - Attorney attorney = db.find(Attorney.class, id); + Attorney attorney = getAttorney(id); return attorney.getCases(); } public List getCasesByIdForAttorney(String attroneyId, String caseId) { - Attorney attorney = db.find(Attorney.class, attroneyId); + Attorney attorney = getAttorney(attroneyId); return attorney.getCases().stream().filter(i -> i.getId() .equalsIgnoreCase(caseId)).collect(Collectors.toList()); } - public QueryResult getAll() { - QueryResult qr = db.query(new QueryBuilder(ne("_id", "")).fields("username", "_id", "_rev").build(), - Attorney.class); - return qr; + public FindResult getAll() { + Map selector = Collections.singletonMap( + "_id", Collections.singletonMap("$ne", "")); + PostFindOptions findOptions = modelHelper.getFindOptions(selector, database); + FindResult response = + service.postFind(findOptions).execute() + .getResult(); + + System.out.println(response); + + return response; } - - } diff --git a/src/main/java/application/model/ClientModel.java b/src/main/java/application/model/ClientModel.java index eec8a8d..fb6626b 100644 --- a/src/main/java/application/model/ClientModel.java +++ b/src/main/java/application/model/ClientModel.java @@ -1,56 +1,93 @@ package application.model; -import java.net.MalformedURLException; -import java.net.URL; - -import com.cloudant.client.api.ClientBuilder; -import com.cloudant.client.api.CloudantClient; -import com.cloudant.client.api.Database; -import com.cloudant.client.api.model.Response; -import com.cloudant.client.api.query.QueryBuilder; -import com.cloudant.client.api.query.QueryResult; - -import static com.cloudant.client.api.query.EmptyExpression.empty; -import static com.cloudant.client.api.query.Expression.eq; -import static com.cloudant.client.api.query.Expression.gt; -import static com.cloudant.client.api.query.Operation.and; - +import java.util.Collections; +import java.util.Map; +import com.google.gson.Gson; +import com.ibm.cloud.cloudant.v1.Cloudant; +import com.ibm.cloud.cloudant.v1.model.*; +import com.ibm.cloud.sdk.core.service.exception.NotFoundException; import io.swagger.model.Client; public class ClientModel { - private Database db = null; + private String database = null; + private Cloudant service = null; + private ModelHelper modelHelper = null; - public ClientModel(String url, String apiKey, String database) { - System.out.println(url); - CloudantClient client = null; + public ClientModel(String serviceName, String database) { + this.database = database; + modelHelper = new ModelHelper(); try { - client = ClientBuilder.url(new URL(url)).iamApiKey(apiKey).build(); - } catch (MalformedURLException e) { + service = Cloudant.newInstance(serviceName); + } catch (Exception e) { e.printStackTrace(); } - - System.out.println("Server Version: " + client.serverVersion()); - db = client.database(database, false); } - public Response save(Client client) { - Response resp = db.save(client); + public DocumentResult save(Client client) { + Gson gson = new Gson(); + Document clientDocument = new Document(); + clientDocument.setProperties(gson.fromJson(gson.toJson(client), Map.class)); + PostDocumentOptions createDocumentOptions = modelHelper.getPostDocumentOptions(clientDocument, database); + DocumentResult resp = service + .postDocument(createDocumentOptions) + .execute() + .getResult(); + return resp; } - public Response delete(String id) { - Client client = db.find(Client.class, id); - Response resp = db.remove(client); - return resp; + public DocumentResult delete(String id) { + DocumentResult deleteDocumentResponse = null; + try { + // Set the options to get the document out of the database if it exists + GetDocumentOptions documentInfoOptions = modelHelper.getGetDocumentOptions(id,database); + // Try to get the document if it previously existed in the database + Document document = service + .getDocument(documentInfoOptions) + .execute() + .getResult(); + + // Delete the document from the database + DeleteDocumentOptions deleteDocumentOptions = + modelHelper.getDeleteDocumentOptions(id, document.getRev(), database); + + deleteDocumentResponse = service + .deleteDocument(deleteDocumentOptions) + .execute() + .getResult(); + if (deleteDocumentResponse.isOk()) { + System.out.println("You have deleted the document."); + } + } catch (NotFoundException nfe) { + System.out.println("Cannot delete because document was not found " + nfe); + } + return deleteDocumentResponse; } public Client read(String id) { - Client client = db.find(Client.class, id); + Gson gson = new Gson(); + GetDocumentOptions getDocOptions = modelHelper.getGetDocumentOptions(id, database); + Document clientDocument = service + .getDocument(getDocOptions) + .execute() + .getResult(); + Client client = clientDocument != null ? gson.fromJson(clientDocument.toString(),Client.class): null; + return client; } - public QueryResult getAllClientsOfAttorney(String attorneyId) { - QueryResult qr = db.query(new QueryBuilder(eq("attorneyId", attorneyId)).build(), Client.class); - return qr; + public FindResult getAllClientsOfAttorney(String attorneyId) { + Map selector = Collections.singletonMap( + "_id", Collections.singletonMap("$eq", attorneyId)); + + PostFindOptions findOptions = modelHelper.getFindOptions(selector,database); + + FindResult response = + service.postFind(findOptions).execute() + .getResult(); + System.out.println(response); + + return response; } + } diff --git a/src/main/java/application/model/ModelHelper.java b/src/main/java/application/model/ModelHelper.java new file mode 100644 index 0000000..cdb0b97 --- /dev/null +++ b/src/main/java/application/model/ModelHelper.java @@ -0,0 +1,42 @@ +package application.model; + +import com.ibm.cloud.cloudant.v1.model.*; +import java.util.Map; + +public class ModelHelper { + + public PostFindOptions getFindOptions(Map selector, String database) { + PostFindOptions findOptions = new PostFindOptions.Builder() + .db(database) + .selector(selector) + .build(); + return findOptions; + } + + public DeleteDocumentOptions getDeleteDocumentOptions(String id, String revId, String database) { + DeleteDocumentOptions deleteDocumentOptions = + new DeleteDocumentOptions.Builder() + .db(database) + .rev(revId) + .docId(id) + .build(); + return deleteDocumentOptions; + } + + public GetDocumentOptions getGetDocumentOptions(String id, String database) { + GetDocumentOptions getDocOptions = new GetDocumentOptions.Builder() + .db(database) + .docId(id) + .build(); + return getDocOptions; + } + + public PostDocumentOptions getPostDocumentOptions(Document document, String database) { + PostDocumentOptions documentOptions = + new PostDocumentOptions.Builder() + .db(database) + .document(document) + .build(); + return documentOptions; + } +} diff --git a/src/main/java/io/swagger/api/impl/AttorneyApiServiceImpl.java b/src/main/java/io/swagger/api/impl/AttorneyApiServiceImpl.java index 43ae2bd..6c87d49 100644 --- a/src/main/java/io/swagger/api/impl/AttorneyApiServiceImpl.java +++ b/src/main/java/io/swagger/api/impl/AttorneyApiServiceImpl.java @@ -1,71 +1,71 @@ package io.swagger.api.impl; +import com.google.gson.Gson; +import com.ibm.cloud.cloudant.v1.model.DocumentResult; +import com.ibm.cloud.cloudant.v1.model.FindResult; import io.swagger.api.*; import io.swagger.model.*; - import io.swagger.model.Attorney; import io.swagger.model.AttorneyResponse; - -import java.util.List; +import java.util.*; import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - +import java.util.stream.Collectors; import application.model.AttorneyModel; - import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -import com.cloudant.client.api.query.QueryResult; - import javax.validation.constraints.*; @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaJerseyServerCodegen", date = "2020-08-11T08:44:06.780+02:00") public class AttorneyApiServiceImpl extends AttorneyApiService { private AttorneyModel am = null; public AttorneyApiServiceImpl() { - String databaseUrl = System.getenv("AGGREGATOR_DB_URL"); - String databaseIamKey = System.getenv("AGGREGATOR_DB_IAM_KEY"); - am = new AttorneyModel(databaseUrl, databaseIamKey, "outcarcerate-attorney"); + String serviceName = "AGGREGATOR_DB"; + am = new AttorneyModel(serviceName, "outcarcerate-attorney"); } @Override public Response addAttorney(Attorney body, SecurityContext securityContext) throws NotFoundException { System.out.println("addAttorney"); - com.cloudant.client.api.model.Response resp = am.save(body); + DocumentResult resp = am.save(body); if(resp.getError() == null) { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); } else { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, resp.getError())).build(); } } + @Override public Response getAllAttorneys(SecurityContext securityContext) throws NotFoundException { System.out.println("getAllAttorneys"); - QueryResult qr = am.getAll(); + FindResult findResponse = am.getAll(); + Gson gson = new Gson(); + List attorneys = findResponse.getDocs() + .stream() + .map(doc->gson.fromJson(doc.toString(), Attorney.class)) + .collect(Collectors.toList()); + AttorneyResponse ar = new AttorneyResponse(); ar.setCode(200); ar.setSuccess(true); - ar.setAttorney(qr.getDocs()); - ar.setWarning(qr.getWarning()); + ar.setAttorney(attorneys); + ar.setWarning(findResponse.getWarning()); return Response.ok().entity(ar).build(); - //return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } + @Override public Response getAttorneyById(String attorneyId, SecurityContext securityContext) throws NotFoundException { System.out.println("getAttorneyById"); System.out.println("Getting attorney: " + attorneyId); - Attorney attorney = am.read(attorneyId); + Attorney attorney = am.getAttorney(attorneyId); System.out.println("Attorney: " + attorney.toString()); return Response.ok().entity(attorney).build(); } + @Override public Response deleteAttorneyById(String attorneyId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - com.cloudant.client.api.model.Response resp = am.delete(attorneyId); + DocumentResult resp = am.delete(attorneyId); if(resp.getError() == null) { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); } else { diff --git a/src/main/java/io/swagger/api/impl/CaseApiServiceImpl.java b/src/main/java/io/swagger/api/impl/CaseApiServiceImpl.java index 4f2d2cf..db93906 100644 --- a/src/main/java/io/swagger/api/impl/CaseApiServiceImpl.java +++ b/src/main/java/io/swagger/api/impl/CaseApiServiceImpl.java @@ -7,6 +7,7 @@ import javax.ws.rs.core.SecurityContext; import application.model.AttorneyModel; +import com.ibm.cloud.cloudant.v1.model.DocumentResult; import io.swagger.api.ApiResponseMessage; import io.swagger.api.CaseApiService; import io.swagger.api.NotFoundException; @@ -18,40 +19,39 @@ public class CaseApiServiceImpl extends CaseApiService { private AttorneyModel am = null; - public CaseApiServiceImpl() { - String databaseUrl = System.getenv("AGGREGATOR_DB_URL"); - String databaseIamKey = System.getenv("AGGREGATOR_DB_IAM_KEY"); - am = new AttorneyModel(databaseUrl, databaseIamKey, "outcarcerate-attorney"); - } + public CaseApiServiceImpl() { + String serviceName = "AGGREGATOR_DB"; + am = new AttorneyModel(serviceName, "outcarcerate-attorney"); + } - @Override - public Response addCase(@NotNull String attorneyId, ModelCase body, SecurityContext securityContext) - throws NotFoundException { - System.out.println("addCase"); + @Override + public Response addCase(@NotNull String attorneyId, ModelCase body, SecurityContext securityContext) + throws NotFoundException { + System.out.println("addCase"); String id = body.getId(); if (id == null || id.trim().isEmpty()) { body.setId(am.getUuid()); } - com.cloudant.client.api.model.Response resp = am.addCaseToAttorney(attorneyId, body); - if (resp.getError() == null) { - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); - } else { - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, resp.getError())).build(); - } - } + DocumentResult resp = am.addCaseToAttorney(attorneyId, body); + if (resp.getError() == null) { + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); + } else { + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, resp.getError())).build(); + } + } - @Override - public Response deleteCaseById(String attorneyId, String caseId, SecurityContext securityContext) - throws NotFoundException { - com.cloudant.client.api.model.Response resp = am.deleteCaseFromAttorney(attorneyId, caseId); - if (resp.getError() == null) { - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); - } else { - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, resp.getError())).build(); - } - } + @Override + public Response deleteCaseById(String attorneyId, String caseId, SecurityContext securityContext) + throws NotFoundException { + DocumentResult resp = am.deleteCaseFromAttorney(attorneyId, caseId); + if (resp.getError() == null) { + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); + } else { + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, resp.getError())).build(); + } + } @Override public Response getCase(String attorneyId, String caseId, SecurityContext securityContext) @@ -65,16 +65,15 @@ public Response getCase(String attorneyId, String caseId, SecurityContext securi return Response.ok().entity(ar).build(); } - @Override - public Response getCaseById(String attorneyId, SecurityContext securityContext) throws NotFoundException { - - System.out.println("getCaseById"); - List qr = am.getCasesForAttorney(attorneyId); - CaseResponse ar = new CaseResponse(); - ar.setCode(200); - ar.setSuccess(true); - ar.setClients(qr); - return Response.ok().entity(ar).build(); + @Override + public Response getCaseById(String attorneyId, SecurityContext securityContext) throws NotFoundException { + System.out.println("getCaseById"); + List qr = am.getCasesForAttorney(attorneyId); + CaseResponse ar = new CaseResponse(); + ar.setCode(200); + ar.setSuccess(true); + ar.setClients(qr); + return Response.ok().entity(ar).build(); } diff --git a/src/main/java/io/swagger/api/impl/ClientApiServiceImpl.java b/src/main/java/io/swagger/api/impl/ClientApiServiceImpl.java index d0831c1..8642a60 100644 --- a/src/main/java/io/swagger/api/impl/ClientApiServiceImpl.java +++ b/src/main/java/io/swagger/api/impl/ClientApiServiceImpl.java @@ -1,13 +1,14 @@ package io.swagger.api.impl; +import java.util.List; import java.util.stream.Collectors; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - -import com.cloudant.client.api.query.QueryResult; - import application.model.ClientModel; +import com.google.gson.Gson; +import com.ibm.cloud.cloudant.v1.model.DocumentResult; +import com.ibm.cloud.cloudant.v1.model.FindResult; import io.swagger.api.ApiResponseMessage; import io.swagger.api.ClientApiService; import io.swagger.api.NotFoundException; @@ -19,15 +20,14 @@ public class ClientApiServiceImpl extends ClientApiService { private ClientModel am = null; public ClientApiServiceImpl() { - String databaseUrl = System.getenv("AGGREGATOR_DB_URL"); - String databaseIamKey = System.getenv("AGGREGATOR_DB_IAM_KEY"); - am = new ClientModel(databaseUrl, databaseIamKey, "outcarcerate-client"); + String serviceName = "AGGREGATOR_DB"; + am = new ClientModel(serviceName, "outcarcerate-client"); } @Override public Response addClient(Client body, SecurityContext securityContext) throws NotFoundException { System.out.println("addClient"); - com.cloudant.client.api.model.Response resp = am.save(body); + DocumentResult resp = am.save(body); if (resp.getError() == null) { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); } else { @@ -37,13 +37,12 @@ public Response addClient(Client body, SecurityContext securityContext) throws N @Override public Response deleteClientById(String clientId, SecurityContext securityContext) throws NotFoundException { - com.cloudant.client.api.model.Response resp = am.delete(clientId); + DocumentResult resp = am.delete(clientId); if (resp.getError() == null) { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, resp.getId())).build(); } else { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, resp.getError())).build(); } - } @Override @@ -51,13 +50,20 @@ public Response getClients(String clientId, String attorneyId, SecurityContext s throws NotFoundException { // When attorneyId passed if (attorneyId != null && !"".equalsIgnoreCase(attorneyId)) { - QueryResult qr = am.getAllClientsOfAttorney(attorneyId); + FindResult findResponse = am.getAllClientsOfAttorney(attorneyId); + + Gson gson = new Gson(); + List clients = findResponse.getDocs() + .stream() + .map(doc->gson.fromJson(doc.toString(), Client.class)) + .collect(Collectors.toList()); + ClientResponse cr = new ClientResponse(); cr.setCode(200); cr.setSuccess(true); - cr.setClients(clientId != null ? qr.getDocs().stream().filter(i -> i.getId().equalsIgnoreCase(clientId)) - .collect(Collectors.toList()) : qr.getDocs()); - cr.setWarning(qr.getWarning()); + cr.setClients(clientId != null ? clients.stream().filter(i -> i.getId().equalsIgnoreCase(clientId)) + .collect(Collectors.toList()) : clients); + cr.setWarning(findResponse.getWarning()); return Response.ok().entity(cr).build(); } diff --git a/src/main/liberty/config/server.sample.env b/src/main/liberty/config/server.sample.env index 98fc7a5..44ffbb9 100644 --- a/src/main/liberty/config/server.sample.env +++ b/src/main/liberty/config/server.sample.env @@ -1,2 +1,2 @@ AGGREGATOR_DB_URL=Your cloudant url -AGGREGATOR_DB_IAM_KEY=Your cloudant iamkey \ No newline at end of file +AGGREGATOR_DB_APIKEY=Your cloudant iamkey diff --git a/src/test/java/application/model/TestAttorneyModel.java b/src/test/java/application/model/TestAttorneyModel.java new file mode 100644 index 0000000..c825e5a --- /dev/null +++ b/src/test/java/application/model/TestAttorneyModel.java @@ -0,0 +1,124 @@ +package application.model; + +import com.ibm.cloud.cloudant.v1.model.*; +import com.ibm.cloud.sdk.core.http.Response; +import com.ibm.cloud.sdk.core.http.ServiceCall; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import com.ibm.cloud.cloudant.v1.Cloudant; +import io.swagger.model.Attorney; +import org.mockito.Mockito; +import java.util.HashMap; + + +public class TestAttorneyModel { + + Attorney testAttorney = new Attorney(); + + DocumentResult testGoodResponse = mock(DocumentResult.class); + DocumentResult testBadResponse = mock(DocumentResult.class); + Cloudant fakeService = mock(Cloudant.class); + ModelHelper modelHelper = mock(ModelHelper.class); + PostDocumentOptions testGoodCreateDocumentOptions = mock(PostDocumentOptions.class); + DeleteDocumentOptions testGoodDeleteDocumentOptions = mock(DeleteDocumentOptions.class); + GetDocumentOptions testGoodGetDocumentOptions = mock(GetDocumentOptions.class); + GetDocumentOptions testBadGetDocumentOptions = mock(GetDocumentOptions.class); + ServiceCall goodServiceCall = mock(ServiceCall.class); + ServiceCall badServiceCall = mock(ServiceCall.class); + ServiceCall goodCreateServiceCall = mock(ServiceCall.class); + ServiceCall goodDeleteServiceCall = mock(ServiceCall.class); + + Response goodResponse = mock(Response.class); + Response badResponse = mock(Response.class); + Response goodCreateResponse = mock(Response.class); + Response badCreateResponse = mock(Response.class); + Response goodDeleteResponse = mock(Response.class); + + AttorneyModel testAttorneyModel = null; + String databaseName = "outcarcerate-attorney"; + + @Before + public void initTestAttorneyModel() { + // Setting a test Attorney, with no cases + testAttorney.setId("0"); + testAttorney.setRev("Test Revision"); + testAttorney.setUsername("johndoe"); + testAttorney.setCases(null); + testAttorneyModel = new AttorneyModel(fakeService, modelHelper); + + when(testGoodResponse.isOk() ).thenReturn(Boolean.TRUE); + when(testBadResponse.isOk()).thenReturn(Boolean.FALSE); + when(goodCreateResponse.getStatusCode()).thenReturn(200); + when(badCreateResponse.getStatusCode()).thenReturn(500); + when(modelHelper.getPostDocumentOptions(any(),any())).thenReturn(testGoodCreateDocumentOptions); + when(fakeService.postDocument(testGoodCreateDocumentOptions)).thenReturn(goodServiceCall); + when(modelHelper.getGetDocumentOptions(Mockito.eq("0"),any())).thenReturn(testGoodGetDocumentOptions); + when(modelHelper.getGetDocumentOptions(Mockito.eq("1"),any())).thenReturn(testBadGetDocumentOptions); + when(fakeService.getDocument(testGoodGetDocumentOptions)).thenReturn(goodServiceCall); + when(fakeService.getDocument(testBadGetDocumentOptions)).thenReturn(badServiceCall); + when(goodServiceCall.execute()).thenReturn(goodResponse); + when(badServiceCall.execute()).thenReturn(badResponse); + when(goodResponse.getResult()).thenReturn(getTestDocument("0", "testRev", "johndoe")); + when(badResponse.getResult()).thenReturn(null); + //test saving document + when(modelHelper.getPostDocumentOptions(any(Document.class),any())).thenReturn(testGoodCreateDocumentOptions); + when(fakeService.postDocument(testGoodCreateDocumentOptions)).thenReturn(goodCreateServiceCall); + when(goodCreateServiceCall.execute()).thenReturn(goodCreateResponse); + when(goodCreateResponse.getResult()).thenReturn(testGoodResponse); + + //test Delete + when(modelHelper.getDeleteDocumentOptions(Mockito.eq("0"),any(),any())).thenReturn(testGoodDeleteDocumentOptions); + when(fakeService.deleteDocument(testGoodDeleteDocumentOptions)).thenReturn(goodCreateServiceCall); + when(goodDeleteServiceCall.execute()).thenReturn(goodDeleteResponse); + when(goodDeleteResponse.getResult()).thenReturn(testGoodResponse); + } + + @Test + public void testGetAttorney() throws Exception { + // We do have an attorney with id = 0, so this should return our test attorney + Attorney attorney = testAttorneyModel.getAttorney("0"); + assertTrue(attorney != null); + assertEquals(attorney.getUsername(), "johndoe"); + assertEquals(attorney.getId(),"0"); + // We don't have attorney with id = 1, should return null + attorney = testAttorneyModel.getAttorney("1"); + assertNull(attorney); + } + + @Test + public void testSave() throws Exception { + // Trying to save our testAttorney, which should returns 200 + assertEquals(testAttorneyModel.save(testAttorney).isOk(), Boolean.TRUE); + // Trying to save a null or bad Attorney value, which should returns 0 (made up error call) + assertNull(testAttorneyModel.save(null)); + } + + @Test + public void testDelete() throws Exception { + // Trying to save our testAttorney, which should returns 200 + assertEquals(testAttorneyModel.save(testAttorney).isOk(), Boolean.TRUE); + // Trying to delete our testAttorney, which should returns 200 + when(modelHelper.getDeleteDocumentOptions("0","Test Revision",databaseName)) + .thenReturn(testGoodDeleteDocumentOptions); + assertEquals(testAttorneyModel.delete("0").isOk(), Boolean.TRUE); + } + + private Document getTestDocument(String id, String rev, String username){ + Document doc = new Document(); + doc.setId(id); + doc.setRev(rev); + doc.setProperties(new HashMap() {{ + put("username",username); + }}); + + return doc; + } + + // TODO: add test for addCaseToAttorney + // TODO: add test for deleteCaseFromAttorney + // TODO: add test for getCasesForAttorney + // TODO: add test for getCasesByIdForAttorney + // TODO: add test for getAll +} \ No newline at end of file diff --git a/src/test/java/unit/application/model/TestSanity.java b/src/test/java/application/model/TestSanity.java similarity index 100% rename from src/test/java/unit/application/model/TestSanity.java rename to src/test/java/application/model/TestSanity.java diff --git a/src/test/java/unit/application/model/TestAttorneyModel.java b/src/test/java/unit/application/model/TestAttorneyModel.java deleted file mode 100644 index 1983f7f..0000000 --- a/src/test/java/unit/application/model/TestAttorneyModel.java +++ /dev/null @@ -1,88 +0,0 @@ -package application.model; - -import org.junit.Test; -import org.junit.Before; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; -import com.cloudant.client.api.model.Response; -import com.cloudant.client.api.Database; - -import io.swagger.model.Attorney; -import application.model.AttorneyModel; - -public class TestAttorneyModel { - - Attorney testAttorney = new Attorney(); - Response testGoodResponse = mock(com.cloudant.client.api.model.Response.class); - Response testBadResponse = mock(com.cloudant.client.api.model.Response.class); - Response testNotFoundResponse = mock(com.cloudant.client.api.model.Response.class); - Database fakeDatabase = mock(Database.class); - AttorneyModel testAttorneyModel = new AttorneyModel(fakeDatabase); - - @Before - public void initTestAttorneyModel() { - // Setting a test Attorney, with no cases - testAttorney.setId("0"); - testAttorney.setRev("Test Revision"); - testAttorney.setUsername("johndoe"); - testAttorney.setCases(null); - - when(testGoodResponse.getStatusCode()).thenReturn(200); - when(testBadResponse.getStatusCode()).thenReturn(0); - when(testNotFoundResponse.getStatusCode()).thenReturn(404); - - when(fakeDatabase.find(Attorney.class, "0")).thenReturn(testAttorney); - when(fakeDatabase.save(testAttorney)).thenReturn(testGoodResponse); - when(fakeDatabase.save(null)).thenReturn(testBadResponse); - when(fakeDatabase.remove(null)).thenReturn(testBadResponse); - } - - @Test - public void testRead() throws Exception { - // We do not have an attorney with id = 1, so this should return "null" - assertTrue(testAttorneyModel.read("1") == null); - // We do have an attorney with id = 0, so this should return our test attorney - assertTrue(testAttorneyModel.read("0") != null); - // Checking that the username is matching johndoe - assertEquals(testAttorneyModel.read("0").getUsername(), "johndoe"); - } - - @Test - public void testSave() throws Exception { - // Trying to save our testAttorney, which should returns 200 - assertEquals(testAttorneyModel.save(testAttorney).getStatusCode(), 200); - - // Trying to save a null or bad Attorney value, which should returns 0 (made up error call) - assertEquals(testAttorneyModel.save(null).getStatusCode(), 0); - } - - @Test - public void testDelete() throws Exception { - // Trying to save our testAttorney, which should returns 200 - assertEquals(testAttorneyModel.save(testAttorney).getStatusCode(), 200); - - // Trying to delete our testAttorney, which should returns 200 - when(fakeDatabase.remove(testAttorney)).thenReturn(testGoodResponse); - assertEquals(testAttorneyModel.delete("0").getStatusCode(), 200); - - // A second delete call should return 404, since it's already deleted - when(fakeDatabase.remove(testAttorney)).thenReturn(testNotFoundResponse); - assertEquals(testAttorneyModel.delete("0").getStatusCode(), 404); - - // Trying to delete a null or bad Attorney value, which should returns 0 (made up error call) - assertEquals(testAttorneyModel.delete(null).getStatusCode(), 0); - } - - // TODO: add test for addCaseToAttorney - // TODO: add test for deleteCaseFromAttorney - // TODO: add test for getCasesForAttorney - // TODO: add test for getCasesByIdForAttorney - // TODO: add test for getAll -} \ No newline at end of file