diff --git a/source/otus-activity/pom.xml b/source/otus-activity/pom.xml index d7dbdbc51..72fb9a64c 100644 --- a/source/otus-activity/pom.xml +++ b/source/otus-activity/pom.xml @@ -6,7 +6,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/SurveyActivity.java b/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/SurveyActivity.java index 1a419295e..dcbd2cc83 100644 --- a/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/SurveyActivity.java +++ b/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/SurveyActivity.java @@ -139,8 +139,7 @@ public Optional getLastInterview() { } public Boolean isFinalized() { - ActivityStatus activityStatus = getCurrentStatus().get(); - return activityStatus.getName().equals(ActivityStatusOptions.FINALIZED.getName()); + return currentStatusIs(ActivityStatusOptions.FINALIZED); } public static String serialize(SurveyActivity surveyActivity) { @@ -181,4 +180,17 @@ public void setParticipantData(Participant participantData) { public void setCategory(ActivityCategory category) { this.category = category; } + + public ActivityStatus getCreationStatus(){ + return this.getStatusHistory().get(0); + } + + public boolean couldBeExtracted(){ + return isFinalized() || currentStatusIs(ActivityStatusOptions.SAVED); + } + + private boolean currentStatusIs(ActivityStatusOptions activityStatusOptions){ + ActivityStatus activityStatus = getCurrentStatus().get(); + return activityStatus.getName().equals(activityStatusOptions.getName()); + } } diff --git a/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/filling/answer/TextAnswer.java b/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/filling/answer/TextAnswer.java index b8c17bd5a..39c876b83 100644 --- a/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/filling/answer/TextAnswer.java +++ b/source/otus-activity/src/main/java/org/ccem/otus/model/survey/activity/filling/answer/TextAnswer.java @@ -14,6 +14,10 @@ public String getValue() { return value; } + public void setValue(String value) { + this.value = value; + } + @Override public Map getAnswerExtract(String questionID) { Map extraction = new LinkedHashMap<>(); diff --git a/source/otus-activity/src/main/java/org/ccem/otus/persistence/ActivityDao.java b/source/otus-activity/src/main/java/org/ccem/otus/persistence/ActivityDao.java index 10ecc9645..faeab37f3 100644 --- a/source/otus-activity/src/main/java/org/ccem/otus/persistence/ActivityDao.java +++ b/source/otus-activity/src/main/java/org/ccem/otus/persistence/ActivityDao.java @@ -45,4 +45,6 @@ public interface ActivityDao { void removeStageFromActivities(ObjectId stageOID); void discardByID(ObjectId activityOID) throws DataNotFoundException; + + List getActivityIds(String acronym, Integer version, Boolean isDiscardedValue, List activityIdsToExcludeOfQuery) throws MemoryExcededException; } diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityService.java b/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityService.java index cfd646a0e..687c80951 100644 --- a/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityService.java +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityService.java @@ -52,4 +52,6 @@ public interface ActivityService { void discardByID(ObjectId activityOID) throws DataNotFoundException; + List getActivityIds(String acronym, Integer version, List activityIdsToExcludeOfQuery) throws MemoryExcededException; + } diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityServiceBean.java b/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityServiceBean.java index a720fdf7d..cca0d1733 100644 --- a/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityServiceBean.java +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/ActivityServiceBean.java @@ -190,4 +190,9 @@ public void discardByID(ObjectId activityID) throws DataNotFoundException { activityDao.discardByID(activityID); } + @Override + public List getActivityIds(String acronym, Integer version, List activityIdsToExcludeOfQuery) throws MemoryExcededException { + return activityDao.getActivityIds(acronym, version, null, activityIdsToExcludeOfQuery); + } + } diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtraction.java b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtraction.java new file mode 100644 index 000000000..153f53364 --- /dev/null +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtraction.java @@ -0,0 +1,33 @@ +package org.ccem.otus.service.extraction.model; + +import com.google.gson.annotations.SerializedName; +import org.ccem.otus.model.SerializableModel; +import org.ccem.otus.model.survey.activity.SurveyActivity; +import org.ccem.otus.participant.model.Participant; +import org.ccem.otus.survey.form.SurveyForm; + +public class ActivityExtraction extends SerializableModel { + + @SerializedName("survey") + private ActivityExtractionSurveyData surveyData; + @SerializedName("activity") + private ActivityExtractionActivityData activityData; + + public ActivityExtraction(SurveyForm surveyForm, SurveyActivity surveyActivity) { + this.surveyData = new ActivityExtractionSurveyData(surveyForm); + this.activityData = new ActivityExtractionActivityData(surveyActivity); + } + + public ActivityExtractionSurveyData getSurveyData() { + return surveyData; + } + + public ActivityExtractionActivityData getActivityData() { + return activityData; + } + + public void setParticipantData(Participant participant){ + this.activityData.setParticipantData(participant); + } + +} diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtractionActivityData.java b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtractionActivityData.java new file mode 100644 index 000000000..b4de6f256 --- /dev/null +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtractionActivityData.java @@ -0,0 +1,106 @@ +package org.ccem.otus.service.extraction.model; + +import com.google.gson.GsonBuilder; +import com.google.gson.annotations.SerializedName; +import org.ccem.otus.model.survey.activity.SurveyActivity; +import org.ccem.otus.model.survey.activity.filling.QuestionFill; +import org.ccem.otus.model.survey.activity.mode.ActivityMode; +import org.ccem.otus.model.survey.activity.navigation.NavigationTrackingItem; +import org.ccem.otus.model.survey.activity.navigation.enums.NavigationTrackingItemStatuses; +import org.ccem.otus.model.survey.activity.status.ActivityStatusOptions; +import org.ccem.otus.participant.model.Participant; +import org.ccem.otus.survey.template.utils.adapters.LocalDateTimeAdapter; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +public class ActivityExtractionActivityData { + + private String activityId; + private String acronym; + private Integer version; + private Long recruitmentNumber; + @SerializedName("recruitment_number") + private String recruitmentNumberStr; + @SerializedName("participant_field_center") + private String participantFieldCenter; + private String mode; + private String type; + private String category; + @SerializedName("participant_field_center_by_activity") + private String activityFieldCenter; + private String interviewer; + @SerializedName("current_status") + private String currentStatus; + @SerializedName("current_status_date") + private String currentStatusDate; + @SerializedName("creation_date") + private String creationDate; + @SerializedName("paper_realization_date") + private String paperRealizationDate; + @SerializedName("paper_interviewer") + private String paperInterviewer; + @SerializedName("last_finalization_date") + private String lastFinalizationDate; + @SerializedName("external_id") + private String externalId; + private String fillingList; + private List navigationTrackingItems; + + public ActivityExtractionActivityData(SurveyActivity surveyActivity) { + this.activityId = surveyActivity.getActivityID().toHexString(); + this.acronym = surveyActivity.getSurveyForm().getAcronym(); + this.version = surveyActivity.getSurveyForm().getVersion(); + this.mode = surveyActivity.getMode().toString(); + this.type = ""; + this.category = surveyActivity.getCategory().getName(); + this.activityFieldCenter = surveyActivity.getParticipantData().getFieldCenter().getAcronym(); + + surveyActivity.getLastInterview().ifPresent(interview -> { + this.interviewer = interview.getInterviewer().getEmail(); + }); + + surveyActivity.getCurrentStatus().ifPresent(status -> { + this.currentStatus = status.getName(); + this.currentStatusDate = status.getDate().toString(); + }); + + this.creationDate = surveyActivity.getCreationStatus().getDate().toString(); + + if(surveyActivity.getMode() == ActivityMode.PAPER){ + surveyActivity.getLastStatusByName(ActivityStatusOptions.INITIALIZED_OFFLINE.getName()).ifPresent(status -> { + this.paperInterviewer = status.getUser().getEmail(); + this.paperRealizationDate = status.getDate().toString(); + }); + } + + this.externalId = surveyActivity.getExternalID(); + this.fillingList = serializeAnswers(surveyActivity.getFillContainer().getFillingList()); + + this.navigationTrackingItems = surveyActivity.getNavigationTracker().items + .stream().filter(item -> item.state.equals(String.valueOf(NavigationTrackingItemStatuses.SKIPPED))) + .collect(Collectors.toList()); + + this.recruitmentNumber = surveyActivity.getParticipantData().getRecruitmentNumber(); + this.recruitmentNumberStr = this.recruitmentNumber.toString(); + } + + public String getId() { + return activityId; + } + + public Long getRecruitmentNumber() { + return recruitmentNumber; + } + + public void setParticipantData(Participant participant){ + this.participantFieldCenter = participant.getFieldCenter().getAcronym(); + } + + private String serializeAnswers(List fillingList) { + GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()); + return builder.create().toJson(fillingList); + } +} diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtractionSurveyData.java b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtractionSurveyData.java new file mode 100644 index 000000000..0db947c64 --- /dev/null +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/ActivityExtractionSurveyData.java @@ -0,0 +1,23 @@ +package org.ccem.otus.service.extraction.model; + +import com.google.gson.annotations.SerializedName; +import org.ccem.otus.survey.form.SurveyForm; +import org.ccem.otus.survey.template.item.SurveyItem; + +import java.util.List; + +public class ActivityExtractionSurveyData { + + @SerializedName("id") + private String surveyId; + private List itemContainer; + + public ActivityExtractionSurveyData(SurveyForm surveyForm) { + this.surveyId = surveyForm.getSurveyID().toHexString(); + this.itemContainer = surveyForm.getSurveyTemplate().itemContainer; + } + + public String getId() { + return surveyId; + } +} diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/Rscript.java b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/Rscript.java new file mode 100644 index 000000000..88e832792 --- /dev/null +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/Rscript.java @@ -0,0 +1,21 @@ +package org.ccem.otus.service.extraction.model; + +import org.ccem.otus.model.SerializableModel; + +public class Rscript extends SerializableModel { + + private String name; + private String script; + + public String getName() { + return name; + } + + public String getScript() { + return script; + } + + public static Rscript deserialize(String json){ + return (Rscript)deserialize(json, Rscript.class); + } +} diff --git a/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/SurveyExtraction.java b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/SurveyExtraction.java new file mode 100644 index 000000000..15723bef8 --- /dev/null +++ b/source/otus-activity/src/main/java/org/ccem/otus/service/extraction/model/SurveyExtraction.java @@ -0,0 +1,44 @@ +package org.ccem.otus.service.extraction.model; + +import org.ccem.otus.model.SerializableModelWithID; + +public class SurveyExtraction extends SerializableModelWithID { + + private String surveyId; + private String surveyAcronym; + private Integer surveyVersion; + private String RscriptName; + + public SurveyExtraction(String surveyAcronym, Integer surveyVesion, String rscriptName) { + this.surveyAcronym = surveyAcronym; + this.surveyVersion = surveyVesion; + RscriptName = rscriptName; + } + + public String getSurveyId() { + return surveyId; + } + + public String getSurveyAcronym() { + return surveyAcronym; + } + + public Integer getSurveyVersion() { + return surveyVersion; + } + + public String getRscriptName() { + return RscriptName; + } + + public void setSurveyId(String surveyId) { + this.surveyId = surveyId; + this.surveyAcronym = null; + this.surveyVersion = null; + } + + public static SurveyExtraction fromJson(String json){ + return (SurveyExtraction)deserialize(json, SurveyExtraction.class); + } + +} diff --git a/source/otus-activity/src/test/java/org/ccem/otus/service/ActivityServiceBeanTest.java b/source/otus-activity/src/test/java/org/ccem/otus/service/ActivityServiceBeanTest.java index f140b6d1d..4ab2bcfd3 100644 --- a/source/otus-activity/src/test/java/org/ccem/otus/service/ActivityServiceBeanTest.java +++ b/source/otus-activity/src/test/java/org/ccem/otus/service/ActivityServiceBeanTest.java @@ -233,9 +233,15 @@ public void removeStageFromActivities_method_should_call_removeStageFromActiviti } @Test - public void discardByID_method_should_invoke_ActivityDao_discardByID() throws DataNotFoundException { + public void discardByID_method_should_call_activityDao_discardByID_method() throws DataNotFoundException { service.discardByID(ACTIVITY_OID); verify(activityDao, times(1)).discardByID(ACTIVITY_OID); } + @Test + public void getActivityIds_method_should_call_activityDao_getActivityIds_method() throws MemoryExcededException { + final List activityIdsToExcludeOfQuery = new ArrayList<>(); + service.getActivityIds(ACRONYM, VERSION, activityIdsToExcludeOfQuery); + verify(activityDao, times(1)).getActivityIds(ACRONYM, VERSION, null, activityIdsToExcludeOfQuery); + } } diff --git a/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionActivityDataTest.java b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionActivityDataTest.java new file mode 100644 index 000000000..d34118322 --- /dev/null +++ b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionActivityDataTest.java @@ -0,0 +1,112 @@ +package org.ccem.otus.service.extraction.model; + +import org.bson.types.ObjectId; +import org.ccem.otus.model.FieldCenter; +import org.ccem.otus.model.survey.activity.SurveyActivity; +import org.ccem.otus.model.survey.activity.configuration.ActivityCategory; +import org.ccem.otus.model.survey.activity.filling.FillContainer; +import org.ccem.otus.model.survey.activity.filling.QuestionFill; +import org.ccem.otus.model.survey.activity.mode.ActivityMode; +import org.ccem.otus.model.survey.activity.navigation.NavigationTracker; +import org.ccem.otus.model.survey.activity.status.ActivityStatus; +import org.ccem.otus.model.survey.activity.status.ActivityStatusOptions; +import org.ccem.otus.participant.model.Participant; +import org.ccem.otus.survey.form.SurveyForm; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.doReturn; + +@RunWith(PowerMockRunner.class) +public class ActivityExtractionActivityDataTest { + + private static final String ACTIVITY_ID = "5e0658135b4ff40f8916d2b5"; + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final String ACRONYM = "ANTC"; + private static final Integer VERSION = 1; + private static final ActivityMode MODE = ActivityMode.ONLINE; + private static final String CATEGORY_NAME = "cat"; + private static final ActivityCategory CATEGORY = new ActivityCategory(CATEGORY_NAME, "", null, null); + private static final String ACTIVITY_CENTER_ACRONYM = "RS"; + private static final List FILLING_LIST = new ArrayList<>(); + private static final String EXTERNAL_ID = "123"; + private static final LocalDateTime CURR_STATUS_DATE = LocalDateTime.now(); + + private ActivityExtractionActivityData activityExtractionActivityData; + + @Mock + private SurveyActivity surveyActivity; + @Mock + private SurveyForm surveyForm; + @Mock + private Participant participant; + @Mock + private FieldCenter fieldCenter; + @Mock + private ActivityStatus activityStatus; + @Mock + private ActivityStatus creationActivityStatus; + @Mock + private FillContainer fillContainer; + @Mock + private NavigationTracker navigationTracker; + + + @Before + public void setUp(){ + doReturn(new ObjectId(ACTIVITY_ID)).when(surveyActivity).getActivityID(); + + doReturn(ACRONYM).when(surveyForm).getAcronym(); + doReturn(VERSION).when(surveyForm).getVersion(); + doReturn(surveyForm).when(surveyActivity).getSurveyForm(); + + doReturn(MODE).when(surveyActivity).getMode(); + doReturn(CATEGORY).when(surveyActivity).getCategory(); + + doReturn(Optional.empty()).when(surveyActivity).getLastInterview(); + + doReturn(ActivityStatusOptions.CREATED.getName()).when(activityStatus).getName(); + doReturn(CURR_STATUS_DATE).when(activityStatus).getDate(); + doReturn(CURR_STATUS_DATE).when(creationActivityStatus).getDate(); + + doReturn(Optional.of(activityStatus)).when(surveyActivity).getCurrentStatus(); + doReturn(creationActivityStatus).when(surveyActivity).getCreationStatus(); + + doReturn(EXTERNAL_ID).when(surveyActivity).getExternalID(); + + doReturn(fillContainer).when(surveyActivity).getFillContainer(); + doReturn(FILLING_LIST).when(fillContainer).getFillingList(); + + doReturn(participant).when(surveyActivity).getParticipantData(); + doReturn(RECRUITMENT_NUMBER).when(participant).getRecruitmentNumber(); + doReturn(fieldCenter).when(participant).getFieldCenter(); + doReturn(ACTIVITY_CENTER_ACRONYM).when(fieldCenter).getAcronym(); + + navigationTracker.items = new ArrayList<>(); + doReturn(navigationTracker).when(surveyActivity).getNavigationTracker(); + + activityExtractionActivityData = new ActivityExtractionActivityData(surveyActivity); + } + + @Test + public void getters_check(){ + assertEquals(ACTIVITY_ID, activityExtractionActivityData.getId()); + assertEquals(RECRUITMENT_NUMBER, activityExtractionActivityData.getRecruitmentNumber()); + } + + @Test + public void setParticipantData_should_set_participantFieldCenter(){ + activityExtractionActivityData.setParticipantData(participant); + Mockito.verify(participant, Mockito.times(2)).getFieldCenter(); + } +} diff --git a/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionSurveyDataTest.java b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionSurveyDataTest.java new file mode 100644 index 000000000..c8e2097eb --- /dev/null +++ b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionSurveyDataTest.java @@ -0,0 +1,46 @@ +package org.ccem.otus.service.extraction.model; + +import org.bson.types.ObjectId; +import org.ccem.otus.survey.form.SurveyForm; +import org.ccem.otus.survey.template.SurveyTemplate; +import org.ccem.otus.survey.template.item.SurveyItem; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.doReturn; + +@RunWith(PowerMockRunner.class) +public class ActivityExtractionSurveyDataTest { + + private static final String SURVEY_ID = "5e0658135b4ff40f8916d2b5"; + private static final List ITEM_CONTAINER = new ArrayList<>(); + + private ActivityExtractionSurveyData activityExtractionSurveyData; + + @Mock + private SurveyForm surveyForm; + @Mock + private SurveyTemplate surveyTemplate; + + @Before + public void setUp(){ + surveyTemplate.itemContainer = ITEM_CONTAINER; + + doReturn(new ObjectId(SURVEY_ID)).when(surveyForm).getSurveyID(); + doReturn(surveyTemplate).when(surveyForm).getSurveyTemplate(); + + activityExtractionSurveyData = new ActivityExtractionSurveyData(surveyForm); + } + + @Test + public void getters_check(){ + assertEquals(SURVEY_ID, activityExtractionSurveyData.getId()); + } +} diff --git a/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionTest.java b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionTest.java new file mode 100644 index 000000000..cb23e2a22 --- /dev/null +++ b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/ActivityExtractionTest.java @@ -0,0 +1,54 @@ +package org.ccem.otus.service.extraction.model; + +import org.ccem.otus.model.survey.activity.SurveyActivity; +import org.ccem.otus.participant.model.Participant; +import org.ccem.otus.survey.form.SurveyForm; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.whenNew; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ActivityExtraction.class, ActivityExtractionSurveyData.class}) +public class ActivityExtractionTest { + + private ActivityExtraction activityExtraction; + + @Mock + private ActivityExtractionSurveyData surveyData; + @Mock + private ActivityExtractionActivityData activityData; + + @Mock + private SurveyForm surveyForm; + @Mock + private SurveyActivity surveyActivity; + @Mock + private Participant participant; + + + @Before + public void setUp() throws Exception { + whenNew(ActivityExtractionSurveyData.class).withAnyArguments().thenReturn(surveyData); + whenNew(ActivityExtractionActivityData.class).withAnyArguments().thenReturn(activityData); + activityExtraction = new ActivityExtraction(surveyForm, surveyActivity); + } + + @Test + public void getters_check(){ + assertEquals(surveyData, activityExtraction.getSurveyData()); + assertEquals(activityData, activityExtraction.getActivityData()); + } + + @Test + public void setParticipantData_should_call_activityData_setParticipantData_method(){ + activityExtraction.setParticipantData(participant); + Mockito.verify(activityData, Mockito.times(1)).setParticipantData(participant); + } +} diff --git a/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/RscriptTest.java b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/RscriptTest.java new file mode 100644 index 000000000..f3345e51d --- /dev/null +++ b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/RscriptTest.java @@ -0,0 +1,38 @@ +package org.ccem.otus.service.extraction.model; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(PowerMockRunner.class) +public class RscriptTest { + + private static final String R_SCRIPT_NAME = "script"; + private static final String SCRIPT = "function(x){return(x)}"; + private static final String R_SCRIPT_JSON = "{}"; + + private Rscript rscript; + + @Before + public void setUp() throws Exception { + rscript = new Rscript(); + Whitebox.setInternalState(rscript, "name", R_SCRIPT_NAME); + Whitebox.setInternalState(rscript, "script", SCRIPT); + } + + @Test + public void getters_check(){ + assertEquals(R_SCRIPT_NAME, rscript.getName()); + assertEquals(SCRIPT, rscript.getScript()); + } + + @Test + public void deserialize_method_should_return_Rscript_instance(){ + assertTrue(Rscript.deserialize(R_SCRIPT_JSON) instanceof Rscript); + } +} diff --git a/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/SurveyExtractionTest.java b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/SurveyExtractionTest.java new file mode 100644 index 000000000..45c802a2c --- /dev/null +++ b/source/otus-activity/src/test/java/org/ccem/otus/service/extraction/model/SurveyExtractionTest.java @@ -0,0 +1,47 @@ +package org.ccem.otus.service.extraction.model; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(PowerMockRunner.class) +public class SurveyExtractionTest { + + private static final String ACRONYM = "ANTC"; + private static final Integer VERSION = 1; + private static final String SURVEY_ID = "5e0658135b4ff40f8916d2b5"; + private static final String R_SCRIPT_NAME = "some_script"; + private static final String JSON = "{}"; + + private SurveyExtraction surveyExtraction; + + @Before + public void setUp(){ + surveyExtraction = new SurveyExtraction(ACRONYM, VERSION, R_SCRIPT_NAME); + } + + @Test + public void getters_check(){ + assertEquals(null, surveyExtraction.getSurveyId()); + assertEquals(ACRONYM, surveyExtraction.getSurveyAcronym()); + assertEquals(VERSION, surveyExtraction.getSurveyVersion()); + assertEquals(R_SCRIPT_NAME, surveyExtraction.getRscriptName()); + } + + @Test + public void setSurveyId_should_set_acronym_and_version_as_null(){ + surveyExtraction.setSurveyId(SURVEY_ID); + assertEquals(SURVEY_ID, surveyExtraction.getSurveyId()); + assertEquals(null, surveyExtraction.getSurveyAcronym()); + assertEquals(null, surveyExtraction.getSurveyVersion()); + } + + @Test + public void fromJson_should_return_SurveyExtraction_instance(){ + assertTrue(SurveyExtraction.fromJson(JSON) instanceof SurveyExtraction); + } +} diff --git a/source/otus-business/pom.xml b/source/otus-business/pom.xml index 4674ff232..2283d82f7 100644 --- a/source/otus-business/pom.xml +++ b/source/otus-business/pom.xml @@ -8,7 +8,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-business/src/main/java/br/org/otus/extraction/ActivityExtractionFacade.java b/source/otus-business/src/main/java/br/org/otus/extraction/ActivityExtractionFacade.java new file mode 100644 index 000000000..cde80476e --- /dev/null +++ b/source/otus-business/src/main/java/br/org/otus/extraction/ActivityExtractionFacade.java @@ -0,0 +1,345 @@ +package br.org.otus.extraction; + +import br.org.otus.api.CsvExtraction; +import br.org.otus.api.ExtractionService; +import br.org.otus.fileuploader.api.FileUploaderFacade; +import br.org.otus.gateway.gates.ExtractionGatewayService; +import br.org.otus.gateway.response.GatewayResponse; +import br.org.otus.gateway.response.exception.NotFoundRequestException; +import br.org.otus.participant.api.ParticipantFacade; +import br.org.otus.response.exception.HttpResponseException; +import br.org.otus.response.info.NotFound; +import br.org.otus.response.info.Validation; +import br.org.otus.survey.activity.api.ActivityFacade; +import br.org.otus.survey.api.SurveyFacade; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.internal.LinkedTreeMap; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.DataSource; +import org.ccem.otus.model.survey.activity.SurveyActivity; +import org.ccem.otus.model.survey.activity.filling.QuestionFill; +import org.ccem.otus.model.survey.activity.filling.answer.TextAnswer; +import org.ccem.otus.participant.model.Participant; +import org.ccem.otus.service.DataSourceService; +import org.ccem.otus.service.extraction.ActivityProgressExtraction; +import org.ccem.otus.service.extraction.factories.ActivityProgressRecordsFactory; +import org.ccem.otus.service.extraction.model.ActivityExtraction; +import org.ccem.otus.service.extraction.model.ActivityProgressResultExtraction; +import org.ccem.otus.service.extraction.model.SurveyExtraction; +import org.ccem.otus.survey.form.SurveyForm; +import org.ccem.otus.utils.AnswerMapping; + +import javax.inject.Inject; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.zip.DataFormatException; + +public class ActivityExtractionFacade { + + private final static Logger LOGGER = Logger.getLogger("br.org.otus.extraction.ActivityExtractionFacade"); + + private boolean allowCreateExtractionForAnyActivity = false; + private String runtimeExceptionMessage = null; + + @Inject + private ActivityFacade activityFacade; + @Inject + private SurveyFacade surveyFacade; + @Inject + private FileUploaderFacade fileUploaderFacade; + @Inject + private ExtractionService extractionService; + @Inject + private ParticipantFacade participantFacade; + @Inject + private DataSourceService dataSourceService; + + + public List listSurveyVersions(String acronym) { + return surveyFacade.listVersions(acronym); + } + + public byte[] createAttachmentsReportExtraction(String acronym, Integer version) { + try { + return extractionService.getAttachmentsReport(acronym, version); + } catch (DataNotFoundException e) { + throw new HttpResponseException(NotFound.build(e.getMessage())); + } + } + + public byte[] createActivityProgressExtraction(String center) { + LinkedList progress = activityFacade.getActivityProgressExtraction(center); + ActivityProgressRecordsFactory extraction = new ActivityProgressRecordsFactory(progress); + ActivityProgressExtraction extractor = new ActivityProgressExtraction(extraction); + try { + return extractionService.createExtraction(extractor); + } catch (DataNotFoundException e) { + throw new HttpResponseException(NotFound.build(e.getMessage())); + } + } + + public byte[] downloadFiles(ArrayList oids) { + return fileUploaderFacade.downloadFiles(oids); + } + + public void createOrUpdateActivityExtraction(String activityId) throws HttpResponseException { + try { + new ExtractionGatewayService().createOrUpdateActivityExtraction(buildActivityExtractionModelForCreateOrUpdate(activityId).serialize()); + LOGGER.info("status: success, action: create/update extraction for activity " + activityId); + } + catch (RuntimeException e) { + String message = runtimeExceptionMessage; + runtimeExceptionMessage = null; + LOGGER.severe("status: fail, action: create/update extraction for activity " + activityId + ": " + message); + throw new HttpResponseException(Validation.build(message)); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: create/update extraction for activity " + activityId); + String message = (e.getCause()!=null ? e.getCause().getMessage() : e.getMessage()); + throw new HttpResponseException(Validation.build(message)); + } + } + + public void deleteActivityExtraction(String activityId) { + try { + ActivityExtraction activityExtraction = buildActivityExtractionModel(activityId); + new ExtractionGatewayService().deleteActivityExtraction( + activityExtraction.getSurveyData().getId(), + activityExtraction.getActivityData().getId() + ); + LOGGER.info("status: success, action: DELETE extraction for activity " + activityId); + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build("Activity's extraction doesn't exists")); + } + catch (RuntimeException e) { + String message = runtimeExceptionMessage; + runtimeExceptionMessage = null; + LOGGER.severe("status: fail, action: create/update extraction for activity " + activityId + ": " + message); + throw new HttpResponseException(Validation.build(message)); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: DELETE extraction for activity " + activityId); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + public void synchronizeSurveyActivityExtractions(String acronym, Integer version){ + try { + allowCreateExtractionForAnyActivity = true; + String surveyId = findSurveyId(acronym, version); + GatewayResponse gatewayResponse = new ExtractionGatewayService().getSurveyActivityIdsWithExtraction(surveyId); + ArrayList activitiesIdsWithExtraction = new GsonBuilder().create().fromJson((String) gatewayResponse.getData(), ArrayList.class); + activityFacade.getActivityIds(acronym, version, activitiesIdsWithExtraction).stream() + .filter(activityOid -> !activitiesIdsWithExtraction.contains(activityOid.toHexString())) + .forEach(activityOid -> createOrUpdateActivityExtraction(activityOid.toHexString())); + LOGGER.info("status: success, action: synchronize activities extractions of survey {" + acronym + ", version " + version + "}"); + } catch (Exception e) { + LOGGER.severe("status: fail, action: synchronize activities extractions of survey {" + acronym + ", version " + version + "}"); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + finally { + allowCreateExtractionForAnyActivity = false; + } + } + + public void forceSynchronizeSurveyActivityExtractions(String acronym, Integer version){ + try { + allowCreateExtractionForAnyActivity = true; + activityFacade.getActivityIds(acronym, version, null).stream() + .forEach(activityOid -> createOrUpdateActivityExtraction(activityOid.toHexString())); + LOGGER.info("status: success, action: synchronize activities extractions of survey {" + acronym + ", version " + version + "}"); + } catch (Exception e) { + LOGGER.severe("status: fail, action: synchronize activities extractions of survey {" + acronym + ", version " + version + "}"); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + finally { + allowCreateExtractionForAnyActivity = false; + } + } + + public void forceCreateOrUpdateActivityExtraction(String activityId) throws HttpResponseException { + try { + allowCreateExtractionForAnyActivity = true; + createOrUpdateActivityExtraction(activityId); + } + catch (Exception e) { + throw e; + } + finally{ + allowCreateExtractionForAnyActivity = false; + } + } + + public byte[] getSurveyActivitiesExtractionAsCsv(String acronym, Integer version) { + try { + String surveyId = findSurveyId(acronym, version); + GatewayResponse gatewayResponse = new ExtractionGatewayService().getCsvSurveyExtraction(surveyId); + byte[] csv = extractionService.createExtraction(new CsvExtraction((String) gatewayResponse.getData())); + LOGGER.info("status: success, action: extraction for survey {" + acronym + ", version " + version + "} as csv"); + return csv; + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build("There is no activity extractions for survey {" + acronym + ", version " + version + "}")); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: extraction for survey {" + acronym + ", version " + version + "} as csv"); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + public ArrayList getSurveyActivitiesExtractionAsJson(String acronym, Integer version) { + try { + String surveyId = findSurveyId(acronym, version); + GatewayResponse gatewayResponse = new ExtractionGatewayService().getJsonSurveyExtraction(surveyId); + ArrayList response = new GsonBuilder().create().fromJson( + (String) gatewayResponse.getData(), ArrayList.class); + LOGGER.info("status: success, action: extraction for survey {" + acronym + ", version " + version + "} as json"); + return response; + } + catch(DataNotFoundException e){ + throw new HttpResponseException(NotFound.build(e.getCause().getMessage())); + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build("There is no activity extractions for survey {" + acronym + ", version " + version + "}")); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: extraction for for survey {" + acronym + ", version " + version + "} as json"); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + public byte[] getRscriptSurveyExtractionAsCsv(String surveyExtractionJson){ + try { + SurveyExtraction surveyExtraction = SurveyExtraction.fromJson(surveyExtractionJson); + String surveyId = findSurveyId(surveyExtraction.getSurveyAcronym(), surveyExtraction.getSurveyVersion()); + surveyExtraction.setSurveyId(surveyId); + GatewayResponse gatewayResponse = new ExtractionGatewayService().getRscriptSurveyExtraction(surveyExtraction.serialize()); + byte[] csv = extractionService.createExtraction(new CsvExtraction((String) gatewayResponse.getData())); + LOGGER.info("status: success, action: R script extraction for survey {" + surveyExtractionJson + "} as csv"); + return csv; + } + catch(DataNotFoundException e){ + throw new HttpResponseException(NotFound.build(e.getCause().getMessage())); + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build(e.getErrorContent().toString())); + } + catch(DataFormatException e){ + throw new HttpResponseException(NotFound.build("Check your R script: it should return a csv string or a csv string array, " + + "both with delimiter \";\" and end of line \"\\n\"" + + e.getCause().getMessage())); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: R script extraction for survey {" + surveyExtractionJson + "} as csv"); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + public String getRscriptSurveyExtractionAsJson(String surveyExtractionJson){ + try { + SurveyExtraction surveyExtraction = SurveyExtraction.fromJson(surveyExtractionJson); + String surveyId = findSurveyId(surveyExtraction.getSurveyAcronym(), surveyExtraction.getSurveyVersion()); + surveyExtraction.setSurveyId(surveyId); + GatewayResponse gatewayResponse = new ExtractionGatewayService().getRscriptSurveyExtraction(surveyExtraction.serialize()); + String result = (String) gatewayResponse.getData(); + LOGGER.info("status: success, action: R script extraction for survey {" + surveyExtractionJson + "} as json"); + return result; + } + catch(DataNotFoundException e){ + throw new HttpResponseException(NotFound.build(e.getCause().getMessage())); + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build(e.getErrorContent().toString())); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: R script extraction for survey {" + surveyExtractionJson + "} as json"); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + + private String findSurveyId(String acronym, Integer version) throws DataNotFoundException { + try{ + return surveyFacade.get(acronym, version).getSurveyID().toHexString(); + } + catch (HttpResponseException e){ + throw new DataNotFoundException("Survey {" + acronym + ", version " + version + "} does not exists"); + } + } + + private ActivityExtraction buildActivityExtractionModel(String activityId) throws ValidationException, RuntimeException { + SurveyActivity surveyActivity = activityFacade.getByID(activityId); + if(surveyActivity.isDiscarded() && !allowCreateExtractionForAnyActivity){ + throw new ValidationException(new Throwable("Activity " + activityId + " is discarded")); + } + if(!surveyActivity.couldBeExtracted() && !allowCreateExtractionForAnyActivity){ + throw new ValidationException(new Throwable("Activity " + activityId + " could not be extracted")); + } + SurveyForm surveyForm = surveyFacade.get(surveyActivity.getSurveyForm().getAcronym(), surveyActivity.getSurveyForm().getVersion()); + + if(surveyForm.getSurveyTemplate().dataSources != null && !surveyForm.getSurveyTemplate().dataSources.isEmpty()){ + setExtractionValueInAutoCompleteQuestions(surveyActivity, surveyForm); + } + + return new ActivityExtraction(surveyForm, surveyActivity); + } + + private ActivityExtraction buildActivityExtractionModelForCreateOrUpdate(String activityId) throws ValidationException, RuntimeException { + ActivityExtraction activityExtraction = buildActivityExtractionModel(activityId); + Participant participant = participantFacade.getByRecruitmentNumber(activityExtraction.getActivityData().getRecruitmentNumber()); + activityExtraction.setParticipantData(participant); + return activityExtraction; + } + + private void setExtractionValueInAutoCompleteQuestions(SurveyActivity surveyActivity, SurveyForm surveyForm) throws RuntimeException { + List dataSourceIds = surveyForm.getSurveyTemplate().dataSources.stream() + .map(dataSourceDefinition -> dataSourceDefinition.id) + .collect(Collectors.toList()); + List dataSources = dataSourceService.list(dataSourceIds); + + surveyActivity.getFillContainer().getFillingList().stream() + .filter(questionFill -> questionFill.getAnswer().getType().equals(AnswerMapping.AUTOCOMPLETE_QUESTION.getQuestionType())) + .forEach(questionFill -> { + try { + setExtractionValueInAutoCompleteQuestion(questionFill, dataSources, surveyForm); + } catch (ValidationException e) { + throw new RuntimeException(e); + } + }); + } + + private void setExtractionValueInAutoCompleteQuestion(QuestionFill questionFill, List dataSources, SurveyForm surveyForm) throws ValidationException { + String dataSourceId = surveyForm.getSurveyTemplate().dataSources.stream() + .filter(dataSourceDefinition -> dataSourceDefinition.bindTo.contains(questionFill.getQuestionID())) + .findFirst() + .get().id; + + String value = ((TextAnswer) questionFill.getAnswer()).getValue(); + + Iterator iterator = dataSources.stream() + .filter(dataSource -> dataSource.getId().equals(dataSourceId)) + .findFirst().get().getData() + .iterator(); + + boolean found = false; + while(iterator.hasNext() && !found){ + String dataValue = iterator.next().getAsJsonObject().get("value").toString().replace("\"", ""); + found = dataValue.equals(value); + } + + if(!found){ + runtimeExceptionMessage = "Datasource " + dataSourceId + " does not have value " + value + " of question " + questionFill.getQuestionID(); + throw new ValidationException(); + } + + String extractionValue = iterator.next().getAsJsonObject().get("extractionValue").toString().replace("\"", ""); + ((TextAnswer) questionFill.getAnswer()).setValue(extractionValue); + } +} diff --git a/source/otus-business/src/main/java/br/org/otus/extraction/ExtractionFacade.java b/source/otus-business/src/main/java/br/org/otus/extraction/ExtractionFacade.java index 4fb333778..fd95e91d7 100644 --- a/source/otus-business/src/main/java/br/org/otus/extraction/ExtractionFacade.java +++ b/source/otus-business/src/main/java/br/org/otus/extraction/ExtractionFacade.java @@ -15,6 +15,7 @@ import org.ccem.otus.participant.business.ParticipantExtraction; import org.ccem.otus.participant.business.extraction.model.ParticipantResultExtraction; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.service.DataSourceService; import org.ccem.otus.service.extraction.ActivityProgressExtraction; import org.ccem.otus.service.extraction.SurveyActivityExtraction; @@ -79,47 +80,6 @@ public byte[] createActivityExtraction(String acronym, Integer version) { } } - public byte[] createExtractionFromPipeline(String pipelineName) { - try { - GatewayResponse gatewayResponse = new ExtractionGatewayService().getPipelineExtraction(pipelineName); - LOGGER.info("status: success, action: extraction for pipeline " + pipelineName); - return (byte[]) gatewayResponse.getData(); - } catch (IOException e) { - LOGGER.severe("status: fail, action: extraction for pipeline " + pipelineName); - throw new HttpResponseException(Validation.build(e.getMessage())); - } - } - - public void createActivityExtraction(String activityId) throws HttpResponseException { - try { - new ExtractionGatewayService().createActivityExtraction(activityId); - LOGGER.info("status: success, action: create extraction for activity " + activityId); - } catch (IOException e) { - LOGGER.severe("status: fail, action: create extraction for activity " + activityId); - throw new HttpResponseException(Validation.build(e.getMessage())); - } - } - - public void updateActivityExtraction(String activityId) { - try { - new ExtractionGatewayService().updateActivityExtraction(activityId); - LOGGER.info("status: success, action: update extraction for activity " + activityId); - } catch (IOException e) { - LOGGER.severe("status: fail, action: update extraction for activity " + activityId); - throw new HttpResponseException(Validation.build(e.getMessage())); - } - } - - public void deleteActivityExtraction(String activityId) { - try { - new ExtractionGatewayService().deleteActivityExtraction(activityId); - LOGGER.info("status: success, action: delete extraction for activity " + activityId); - } catch (IOException e) { - LOGGER.severe("status: fail, action: delete extraction for activity " + activityId); - throw new HttpResponseException(Validation.build(e.getMessage())); - } - } - public List listSurveyVersions(String acronym) { return surveyFacade.listVersions(acronym); } @@ -154,31 +114,8 @@ public byte[] createParticipantExtraction() { } } - public byte[] createAttachmentsReportExtraction(String acronym, Integer version) { - try { - return extractionService.getAttachmentsReport(acronym, version); - } catch (DataNotFoundException e) { - throw new HttpResponseException(NotFound.build(e.getMessage())); - } - } - - public byte[] createActivityProgressExtraction(String center) { - LinkedList progress = activityFacade.getActivityProgressExtraction(center); - ActivityProgressRecordsFactory extraction = new ActivityProgressRecordsFactory(progress); - ActivityProgressExtraction extractor = new ActivityProgressExtraction(extraction); - try { - return extractionService.createExtraction(extractor); - } catch (DataNotFoundException e) { - throw new HttpResponseException(NotFound.build(e.getMessage())); - } - } - - public byte[] downloadFiles(ArrayList oids) { - return fileUploaderFacade.downloadFiles(oids); - } - public byte[] createParticipantContactAttemptsExtraction() { - ArrayList participantContactAttempts = participantContactAttemptFacade.finParticipantContactAttempts(); + ArrayList participantContactAttempts = participantContactAttemptFacade.finParticipantContactAttempts(); ParticipantContactAttemptsExtraction extractor = new ParticipantContactAttemptsExtraction(participantContactAttempts); try { return extractionService.createExtraction(extractor); diff --git a/source/otus-business/src/main/java/br/org/otus/extraction/RscriptFacade.java b/source/otus-business/src/main/java/br/org/otus/extraction/RscriptFacade.java new file mode 100644 index 000000000..40bfd9399 --- /dev/null +++ b/source/otus-business/src/main/java/br/org/otus/extraction/RscriptFacade.java @@ -0,0 +1,54 @@ +package br.org.otus.extraction; + +import br.org.otus.gateway.gates.ExtractionGatewayService; +import br.org.otus.gateway.response.exception.NotFoundRequestException; +import br.org.otus.response.exception.HttpResponseException; +import br.org.otus.response.info.NotFound; +import br.org.otus.response.info.Validation; +import org.ccem.otus.service.extraction.model.Rscript; + +import java.util.logging.Logger; + +public class RscriptFacade { + + private final static Logger LOGGER = Logger.getLogger("br.org.otus.extraction.RscriptFacade"); + + public void createOrUpdate(String rscriptJson){ + try { + new ExtractionGatewayService().createOrUpdateRscript(rscriptJson); + LOGGER.info("status: success, action: create R script " + rscriptJson); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: create R script " + rscriptJson); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + public Rscript get(String rscriptName){ + try { + String response = (String) new ExtractionGatewayService().getRscript(rscriptName).getData(); + return Rscript.deserialize(response); + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build("R script doesn't exists")); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: get R script " + rscriptName); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } + + public void delete(String rscriptName){ + try { + new ExtractionGatewayService().deleteRscript(rscriptName); + LOGGER.info("status: success, action: delete R script " + rscriptName); + } + catch(NotFoundRequestException e){ + throw new HttpResponseException(NotFound.build("R script doesn't exists")); + } + catch (Exception e) { + LOGGER.severe("status: fail, action: get R script " + rscriptName); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } +} diff --git a/source/otus-business/src/main/java/br/org/otus/participant/api/NoteAboutParticipantFacade.java b/source/otus-business/src/main/java/br/org/otus/participant/api/NoteAboutParticipantFacade.java new file mode 100644 index 000000000..3852326d2 --- /dev/null +++ b/source/otus-business/src/main/java/br/org/otus/participant/api/NoteAboutParticipantFacade.java @@ -0,0 +1,88 @@ +package br.org.otus.participant.api; + +import br.org.otus.model.User; +import br.org.otus.response.exception.HttpResponseException; +import br.org.otus.response.info.Authorization; +import br.org.otus.response.info.NotFound; +import br.org.otus.response.info.Validation; +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; +import org.ccem.otus.participant.service.NoteAboutParticipantService; + +import javax.inject.Inject; +import java.util.List; +import java.util.logging.Logger; + +public class NoteAboutParticipantFacade { + + private static final Logger LOGGER = Logger.getLogger("br.org.otus.participant.api.NoteAboutParticipantFacade"); + + @Inject + private NoteAboutParticipantService noteAboutParticipantService; + + public String create(User user, String noteAboutParticipantJson){ + NoteAboutParticipant noteAboutParticipant = (new NoteAboutParticipant()).deserializeNonStatic(noteAboutParticipantJson); + return noteAboutParticipantService.create(user.get_id(), noteAboutParticipant).toHexString(); + } + + public void update(User user, String noteAboutParticipantJson){ + try{ + noteAboutParticipantService.update( + user.get_id(), + (new NoteAboutParticipant()).deserializeNonStatic(noteAboutParticipantJson)); + } + catch(DataNotFoundException e){ + throw new HttpResponseException(NotFound.build(e.getCause().getMessage())); + } + catch(ValidationException e){ + LOGGER.severe("User {" + user.get_id() + "} tried update note about participant not created by him"); + throw new HttpResponseException(Authorization.build("You can't update the note because you doesn't create it")); + } + } + + public void updateStarred(User user, String noteAboutParticipantId, Boolean starred){ + try{ + noteAboutParticipantService.updateStarred(user.get_id(), new ObjectId(noteAboutParticipantId), starred); + } + catch(DataNotFoundException e){ + throw new HttpResponseException(NotFound.build(e.getCause().getMessage())); + } + catch(ValidationException e){ + LOGGER.severe("User {" + user.get_id() + "} tried update starred of note about participant not created by him"); + throw new HttpResponseException(Authorization.build("You can't update starred of note because you doesn't create it")); + } + } + + public void delete(User user, String noteAboutParticipantId){ + try{ + noteAboutParticipantService.delete(user.get_id(), new ObjectId(noteAboutParticipantId)); + } + catch(DataNotFoundException e){ + throw new HttpResponseException(NotFound.build(e.getCause().getMessage())); + } + catch(ValidationException e){ + LOGGER.severe("User {" + user.get_id() + "} tried delete note about participant not created by him"); + throw new HttpResponseException(Authorization.build("You can't delete the note because you doesn't create it")); + } + } + + public List getAll(User user, Long recruitmentNumber, String searchSettingsDtoJson){ + try{ + return noteAboutParticipantService.getAll(user.get_id(), recruitmentNumber, SearchSettingsDto.deserialize(searchSettingsDtoJson)); + } + catch(ValidationException | MemoryExcededException e){ + LOGGER.severe(e.getMessage()); + throw new HttpResponseException(Validation.build(e.getMessage())); + } + catch(DataNotFoundException e){ + LOGGER.severe(e.getMessage()); + throw new HttpResponseException(NotFound.build(e.getMessage())); + } + } + +} diff --git a/source/otus-business/src/main/java/br/org/otus/participant/api/ParticipantContactAttemptFacade.java b/source/otus-business/src/main/java/br/org/otus/participant/api/ParticipantContactAttemptFacade.java index 87e6329d6..4983f1ce3 100644 --- a/source/otus-business/src/main/java/br/org/otus/participant/api/ParticipantContactAttemptFacade.java +++ b/source/otus-business/src/main/java/br/org/otus/participant/api/ParticipantContactAttemptFacade.java @@ -8,6 +8,7 @@ import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAddressAttempt; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptConfiguration; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.participant.model.participant_contact.Address; import org.ccem.otus.participant.service.ParticipantContactAttemptService; @@ -70,7 +71,7 @@ public ParticipantContactAttemptConfiguration findMetadataAttempt(String objectT } } - public ArrayList finParticipantContactAttempts() { + public ArrayList finParticipantContactAttempts() { try{ return participantContactAttemptService.finParticipantContactAttempts(); } diff --git a/source/otus-business/src/main/java/br/org/otus/security/api/SecurityFacade.java b/source/otus-business/src/main/java/br/org/otus/security/api/SecurityFacade.java index 16eccf06d..37726b40b 100644 --- a/source/otus-business/src/main/java/br/org/otus/security/api/SecurityFacade.java +++ b/source/otus-business/src/main/java/br/org/otus/security/api/SecurityFacade.java @@ -5,6 +5,7 @@ import br.org.otus.response.info.Authorization; import br.org.otus.security.dtos.*; import br.org.otus.security.services.SecurityService; +import org.bson.types.ObjectId; import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; import org.ccem.otus.exceptions.webservice.common.ExpiredDataException; import org.ccem.otus.exceptions.webservice.security.AuthenticationException; @@ -93,9 +94,9 @@ public void validateToken(String token) { } } - public void validateActivitySharingToken(String token) { + public void validateActivitySharingToken(String token, String activityId) { try { - securityService.validateActivitySharingToken(token); + securityService.validateActivitySharingToken(token, activityId); } catch(ExpiredDataException e){ throw new HttpResponseException(ResponseBuild.Security.Authorization.build(e.getMessage())); diff --git a/source/otus-business/src/main/java/br/org/otus/security/services/SecurityService.java b/source/otus-business/src/main/java/br/org/otus/security/services/SecurityService.java index db4f52d2f..b3b8fd0a9 100644 --- a/source/otus-business/src/main/java/br/org/otus/security/services/SecurityService.java +++ b/source/otus-business/src/main/java/br/org/otus/security/services/SecurityService.java @@ -19,7 +19,7 @@ public interface SecurityService { void validateToken(String token) throws TokenException, AuthenticationException; - void validateActivitySharingToken(String token) throws TokenException, ExpiredDataException; + void validateActivitySharingToken(String token, String activityId) throws TokenException, ExpiredDataException; String projectAuthenticate(AuthenticationData authenticationData) throws TokenException, AuthenticationException; diff --git a/source/otus-business/src/main/java/br/org/otus/security/services/SecurityServiceBean.java b/source/otus-business/src/main/java/br/org/otus/security/services/SecurityServiceBean.java index e7c4be842..031a13780 100644 --- a/source/otus-business/src/main/java/br/org/otus/security/services/SecurityServiceBean.java +++ b/source/otus-business/src/main/java/br/org/otus/security/services/SecurityServiceBean.java @@ -83,7 +83,7 @@ public void validateToken(String token) throws TokenException { } @Override - public void validateActivitySharingToken(String token) throws TokenException, ExpiredDataException { + public void validateActivitySharingToken(String token, String activityId) throws TokenException, ExpiredDataException { try { SignedJWT signedJWT = SignedJWT.parse(token); String payload = signedJWT.getPayload().toString(); @@ -93,6 +93,15 @@ public void validateActivitySharingToken(String token) throws TokenException, Ex if(activitySharing == null){ throw new TokenException(); } + + if (activityId != null) { + if (ObjectId.isValid(activityId)) { + if (!activityId.equals(activitySharing.getActivityId().toHexString())) { + throw new TokenException(); + } + } + } + if(DateUtil.before(activitySharing.getExpirationDate(), DateUtil.nowToISODate())){ throw new ExpiredDataException("Expired token"); } diff --git a/source/otus-business/src/main/java/br/org/otus/survey/activity/api/ActivityFacade.java b/source/otus-business/src/main/java/br/org/otus/survey/activity/api/ActivityFacade.java index 761d2495b..e7b62a6e5 100644 --- a/source/otus-business/src/main/java/br/org/otus/survey/activity/api/ActivityFacade.java +++ b/source/otus-business/src/main/java/br/org/otus/survey/activity/api/ActivityFacade.java @@ -24,6 +24,7 @@ import org.ccem.otus.service.extraction.model.ActivityProgressResultExtraction; import service.StageService; +import javax.ejb.EJBException; import javax.inject.Inject; import java.text.ParseException; import java.util.*; @@ -138,6 +139,8 @@ public SurveyActivity updateActivity(SurveyActivity surveyActivity, String token return activityTasksService.updateActivity(surveyActivity, token); } catch (DataNotFoundException | ParseException e) { throw new HttpResponseException(Validation.build(e.getMessage(), e.getCause())); + } catch (EJBException e) { + throw new HttpResponseException(Validation.build("Connection error", e.getCause())); } } @@ -246,4 +249,12 @@ public void discardByID(String activityId) { throw new HttpResponseException(Validation.build(e.getCause().getMessage())); } } + + public List getActivityIds(String acronym, Integer version, List activityIdsToExcludeOfQuery) { + try { + return activityService.getActivityIds(acronym, version, activityIdsToExcludeOfQuery); + } catch (MemoryExcededException e) { + throw new HttpResponseException(Validation.build(e.getMessage())); + } + } } diff --git a/source/otus-business/src/main/java/br/org/otus/survey/services/ActivityTasksServiceBean.java b/source/otus-business/src/main/java/br/org/otus/survey/services/ActivityTasksServiceBean.java index 6ff2e98de..42b49bada 100644 --- a/source/otus-business/src/main/java/br/org/otus/survey/services/ActivityTasksServiceBean.java +++ b/source/otus-business/src/main/java/br/org/otus/survey/services/ActivityTasksServiceBean.java @@ -1,6 +1,6 @@ package br.org.otus.survey.services; -import br.org.otus.extraction.ExtractionFacade; +import br.org.otus.extraction.ActivityExtractionFacade; import br.org.otus.outcomes.FollowUpFacade; import br.org.otus.response.exception.HttpResponseException; import br.org.otus.response.info.Validation; @@ -49,7 +49,7 @@ public class ActivityTasksServiceBean implements ActivityTasksService { private ActivitySharingService activitySharingService; @Inject - private ExtractionFacade extractionFacade; + private ActivityExtractionFacade extractionFacade; @Override @@ -61,16 +61,6 @@ public String create(SurveyActivity surveyActivity, boolean notify) { followUpFacade.createParticipantActivityAutoFillEvent(surveyActivity, notify); } - CompletableFuture.runAsync(() -> { - try{ - extractionFacade.createActivityExtraction(surveyActivity.getActivityID().toString()); - } - catch (Exception e){ - LOGGER.severe("status: fail, action: create activity extraction for activityId " + surveyActivity.getActivityID().toString()); - new Exception("Error while syncing results", e).printStackTrace(); - } - }); - return activityId; } @@ -92,7 +82,7 @@ public SurveyActivity updateActivity(SurveyActivity surveyActivity, String token extractionFacade.deleteActivityExtraction(surveyActivity.getActivityID().toString()); } else{ - extractionFacade.updateActivityExtraction(surveyActivity.getActivityID().toString()); + extractionFacade.createOrUpdateActivityExtraction(surveyActivity.getActivityID().toString()); } } catch (Exception e){ @@ -111,7 +101,7 @@ public void save(String userEmail, OfflineActivityCollection offlineActivityColl CompletableFuture.runAsync(() -> { offlineActivityCollection.getActivities().forEach(surveyActivity -> { try{ - extractionFacade.updateActivityExtraction(surveyActivity.getActivityID().toString()); + extractionFacade.createOrUpdateActivityExtraction(surveyActivity.getActivityID().toString()); } catch (Exception e){ LOGGER.severe("status: fail, action: save activity extraction for activityId " + surveyActivity.getActivityID().toString() + diff --git a/source/otus-business/src/test/java/br/org/otus/extraction/ActivityExtractionFacadeTest.java b/source/otus-business/src/test/java/br/org/otus/extraction/ActivityExtractionFacadeTest.java new file mode 100644 index 000000000..388b8dfc9 --- /dev/null +++ b/source/otus-business/src/test/java/br/org/otus/extraction/ActivityExtractionFacadeTest.java @@ -0,0 +1,350 @@ +package br.org.otus.extraction; + +import br.org.otus.api.CsvExtraction; +import br.org.otus.api.ExtractionService; +import br.org.otus.fileuploader.api.FileUploaderFacade; +import br.org.otus.gateway.gates.ExtractionGatewayService; +import br.org.otus.gateway.response.GatewayResponse; +import br.org.otus.participant.api.ParticipantFacade; +import br.org.otus.response.exception.HttpResponseException; +import br.org.otus.survey.activity.api.ActivityFacade; +import br.org.otus.survey.api.SurveyFacade; +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.model.survey.activity.SurveyActivity; +import org.ccem.otus.participant.model.Participant; +import org.ccem.otus.service.extraction.ActivityProgressExtraction; +import org.ccem.otus.service.extraction.SurveyActivityExtraction; +import org.ccem.otus.service.extraction.model.ActivityExtraction; +import org.ccem.otus.service.extraction.model.ActivityExtractionActivityData; +import org.ccem.otus.service.extraction.model.ActivityExtractionSurveyData; +import org.ccem.otus.service.extraction.model.SurveyExtraction; +import org.ccem.otus.survey.form.SurveyForm; +import org.ccem.otus.survey.template.SurveyTemplate; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ActivityExtractionFacade.class, SurveyExtraction.class}) +public class ActivityExtractionFacadeTest { + + private static final SurveyTemplate SURVEY_TEMPLATE = new SurveyTemplate(); + private static final String USER_EMAIL = "otus@otus.com"; + private static final String CENTER = "RS"; + private static final String ACRONYM = "ANTC"; + private static final Integer VERSION = 1; + private static final String SURVEY_ID = "5e0658135b4ff40f8916d2b5"; + private static final String ACTIVITY_ID = "5e0658135b4ff40f8916d2b6"; + private static final String ACTIVITY_ID_WITHOUT_EXTRACTION = "5e0658135b4ff40f8916d2b7"; + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final ArrayList SURVEYS = new ArrayList<>(); + private static final byte[] CSV_BYTES = null; + private static final String EXTRACTIONS_JSON = "[{}]"; + private static final int EXTRACTIONS_JSON_SIZE = 1; + private static final byte[] BYTES = new byte[1]; + private static final String SURVEY_EXTRACTION_JSON = "{}"; + private static final String R_SCRIPT_JSON_RESULT = "{}"; + private static final String CSV_JSON = "{header: [\"x\"], values: [1]}"; + + @InjectMocks + private ActivityExtractionFacade activityExtractionFacade; + @Mock + private ActivityFacade activityFacade; + @Mock + private SurveyFacade surveyFacade; + @Mock + private FileUploaderFacade fileUploaderFacade; + @Mock + private ExtractionService extractionService; + @Mock + private ParticipantFacade participantFacade; + + @Mock + private SurveyActivityExtraction surveyActivityExtraction; + @Mock + private ActivityProgressExtraction activityProgressExtraction; + @Mock + private ExtractionGatewayService extractionGatewayService; + @Mock + private GatewayResponse gatewayResponse; + @Mock + private ActivityExtraction activityExtraction; + @Mock + private ActivityExtractionActivityData activityExtractionActivityData; + @Mock + private ActivityExtractionSurveyData activityExtractionSurveyData; + + @Mock + private SurveyActivity surveyActivity; + @Mock + private SurveyExtraction surveyExtraction; + @Mock + private CsvExtraction csvExtraction; + private SurveyForm surveyForm = PowerMockito.spy(new SurveyForm(SURVEY_TEMPLATE, USER_EMAIL)); + private Participant participant = PowerMockito.spy(new Participant(RECRUITMENT_NUMBER)); + + @Before + public void setUp() throws Exception { + SURVEYS.add(surveyForm); + + surveyActivity.setStatusHistory(new ArrayList<>()); + surveyActivity.setActivityID(new ObjectId(ACTIVITY_ID)); + + PowerMockito.when(surveyForm.getSurveyID()).thenReturn(new ObjectId(SURVEY_ID)); + PowerMockito.when(surveyForm.getAcronym()).thenReturn(ACRONYM); + PowerMockito.when(surveyForm.getVersion()).thenReturn(VERSION); + + PowerMockito.when(surveyActivity.getSurveyForm()).thenReturn(surveyForm); + PowerMockito.when(surveyFacade.get(ACRONYM, VERSION)).thenReturn(surveyForm); + + PowerMockito.when(activityExtractionActivityData.getRecruitmentNumber()).thenReturn(RECRUITMENT_NUMBER); + PowerMockito.when(activityExtractionActivityData.getId()).thenReturn(ACTIVITY_ID); + PowerMockito.when(activityExtractionSurveyData.getId()).thenReturn(SURVEY_ID); + + PowerMockito.when(activityExtraction.getSurveyData()).thenReturn(activityExtractionSurveyData); + PowerMockito.when(activityExtraction.getActivityData()).thenReturn(activityExtractionActivityData); + + PowerMockito.when(activityFacade.getExtraction(ACRONYM, VERSION)).thenReturn(new ArrayList<>()); + PowerMockito.when(activityFacade.getByID(ACTIVITY_ID)).thenReturn(surveyActivity); + + PowerMockito.when(participantFacade.getByRecruitmentNumber(RECRUITMENT_NUMBER)).thenReturn(participant); + + PowerMockito.whenNew(SurveyActivityExtraction.class).withAnyArguments().thenReturn(surveyActivityExtraction); + PowerMockito.whenNew(ActivityProgressExtraction.class).withAnyArguments().thenReturn(activityProgressExtraction); + PowerMockito.whenNew(ExtractionGatewayService.class).withNoArguments().thenReturn(extractionGatewayService); + PowerMockito.whenNew(ActivityExtraction.class).withAnyArguments().thenReturn(activityExtraction); + PowerMockito.whenNew(CsvExtraction.class).withAnyArguments().thenReturn(csvExtraction); + + when(surveyExtraction.getSurveyAcronym()).thenReturn(ACRONYM); + when(surveyExtraction.getSurveyVersion()).thenReturn(VERSION); + PowerMockito.mockStatic(SurveyExtraction.class); + when(SurveyExtraction.class, "fromJson", SURVEY_EXTRACTION_JSON).thenReturn(surveyExtraction); + when(extractionService.createExtraction(csvExtraction)).thenReturn(BYTES); + } + + @Test + public void listSurveyVersions_method_should_call_listVersions_from_surveyFacade() { + activityExtractionFacade.listSurveyVersions(ACRONYM); + Mockito.verify(surveyFacade).listVersions(ACRONYM); + } + + @Test + public void createAttachmentsReportExtraction_method_should_call_getAttachmentsReport_from_extractionService() throws DataNotFoundException { + activityExtractionFacade.createAttachmentsReportExtraction(ACRONYM, VERSION); + Mockito.verify(extractionService).getAttachmentsReport(ACRONYM, VERSION); + } + + @Test(expected = HttpResponseException.class) + public void createAttachmentsReportExtraction_method_should_handle_DataNotFoundException() throws DataNotFoundException { + doThrow(new DataNotFoundException()).when(extractionService).getAttachmentsReport(ACRONYM, VERSION); + activityExtractionFacade.createAttachmentsReportExtraction(ACRONYM, VERSION); + } + + @Test + public void createActivityProgressExtraction_method_should_call_methods_expected() throws DataNotFoundException { + when(extractionService.createExtraction(activityProgressExtraction)).thenReturn(BYTES); + activityExtractionFacade.createActivityProgressExtraction(CENTER); + Mockito.verify(activityFacade, Mockito.times(1)).getActivityProgressExtraction(CENTER); + Mockito.verify(extractionService, Mockito.times(1)).createExtraction(activityProgressExtraction); + } + + @Test(expected = HttpResponseException.class) + public void createActivityProgressExtraction_method_should_handle_DataNotFoundException() throws DataNotFoundException { + doThrow(new DataNotFoundException()).when(extractionService).createExtraction(activityProgressExtraction); + activityExtractionFacade.createActivityProgressExtraction(CENTER); + } + + @Test + public void downloadFiles_method_should_call_fileUploaderFacade_downloadFiles_method(){ + ArrayList oids = new ArrayList<>(); + when(fileUploaderFacade.downloadFiles(oids)).thenReturn(BYTES); + byte[] result = activityExtractionFacade.downloadFiles(oids); + verify(fileUploaderFacade, Mockito.times(1)).downloadFiles(oids); + assertEquals(BYTES, result); + } + + @Test + public void createOrUpdateActivityExtraction_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { + doReturn(true).when(surveyActivity).isFinalized(); + when(surveyActivity.couldBeExtracted()).thenReturn(true); + doNothing().when(extractionGatewayService).createOrUpdateActivityExtraction(ACTIVITY_ID); + activityExtractionFacade.createOrUpdateActivityExtraction(ACTIVITY_ID); + verify(extractionGatewayService, Mockito.times(1)).createOrUpdateActivityExtraction(activityExtraction.serialize()); + } + + @Test(expected = HttpResponseException.class) + public void createOrUpdateActivityExtraction_method_should_handle_ValidationException_in_case_discarded_activity() { + when(surveyActivity.isDiscarded()).thenReturn(true); + activityExtractionFacade.createOrUpdateActivityExtraction(ACTIVITY_ID); + } + + @Test(expected = HttpResponseException.class) + public void createOrUpdateActivityExtraction_method_should_handle_ValidationException_in_case_activity_unextractable() { + when(surveyActivity.isDiscarded()).thenReturn(false); + when(surveyActivity.couldBeExtracted()).thenReturn(false); + activityExtractionFacade.createOrUpdateActivityExtraction(ACTIVITY_ID); + } + + @Test + public void deleteActivityExtraction_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { + when(surveyActivity.isDiscarded()).thenReturn(false); + when(surveyActivity.couldBeExtracted()).thenReturn(true); + activityExtractionFacade.deleteActivityExtraction(ACTIVITY_ID); + verify(extractionGatewayService, Mockito.times(1)).deleteActivityExtraction(SURVEY_ID, ACTIVITY_ID); + } + + @Test(expected = HttpResponseException.class) + public void deleteActivityExtraction_method_should_handle_IOException() throws IOException { + when(surveyActivity.isDiscarded()).thenReturn(false); + when(surveyActivity.couldBeExtracted()).thenReturn(true); + doThrow(new MalformedURLException()).when(extractionGatewayService).deleteActivityExtraction(SURVEY_ID, ACTIVITY_ID); + activityExtractionFacade.deleteActivityExtraction(ACTIVITY_ID); + } + + @Test + public void synchronizeSurveyActivityExtractions_method_should_create_extraction_for_each_activity_without_extraction() throws IOException { + when(extractionGatewayService.getSurveyActivityIdsWithExtraction(SURVEY_ID)).thenReturn(gatewayResponse); + when(gatewayResponse.getData()).thenReturn("[" + ACTIVITY_ID + "]"); + List activitiesIdsWithExtraction = new ArrayList<>(); + activitiesIdsWithExtraction.add(ACTIVITY_ID); + List activityOidsWithoutExtraction = new ArrayList<>(); + activityOidsWithoutExtraction.add(new ObjectId(ACTIVITY_ID_WITHOUT_EXTRACTION)); + when(activityFacade.getActivityIds(ACRONYM, VERSION, activitiesIdsWithExtraction)).thenReturn(activityOidsWithoutExtraction); + when(activityFacade.getByID(ACTIVITY_ID_WITHOUT_EXTRACTION)).thenReturn(surveyActivity); + when(surveyActivity.isDiscarded()).thenReturn(false); + when(surveyActivity.couldBeExtracted()).thenReturn(true); + activityExtractionFacade.synchronizeSurveyActivityExtractions(ACRONYM, VERSION); + verify(extractionGatewayService, Mockito.times(1)).getSurveyActivityIdsWithExtraction(SURVEY_ID); + } + + @Test(expected = HttpResponseException.class) + public void synchronizeSurveyActivityExtractions_method_should_handle_IOException() throws IOException { + doThrow(new MalformedURLException()).when(extractionGatewayService).getSurveyActivityIdsWithExtraction(SURVEY_ID); + activityExtractionFacade.synchronizeSurveyActivityExtractions(ACRONYM, VERSION); + } + + @Test + public void forceSynchronizeSurveyActivityExtractions_method_should_create_extraction_for_each_activity_without_extraction() throws IOException { + when(extractionGatewayService.getSurveyActivityIdsWithExtraction(SURVEY_ID)).thenReturn(gatewayResponse); + when(gatewayResponse.getData()).thenReturn("[" + ACTIVITY_ID + "]"); + List activityOidsWithoutExtraction = new ArrayList<>(); + activityOidsWithoutExtraction.add(new ObjectId(ACTIVITY_ID_WITHOUT_EXTRACTION)); + when(activityFacade.getActivityIds(ACRONYM, VERSION, null)).thenReturn(activityOidsWithoutExtraction); + when(activityFacade.getByID(ACTIVITY_ID_WITHOUT_EXTRACTION)).thenReturn(surveyActivity); + when(surveyActivity.isDiscarded()).thenReturn(false); + when(surveyActivity.couldBeExtracted()).thenReturn(true); + activityExtractionFacade.forceSynchronizeSurveyActivityExtractions(ACRONYM, VERSION); + verify(extractionGatewayService, Mockito.times(1)).createOrUpdateActivityExtraction(activityExtraction.serialize()); + } + + @Test(expected = HttpResponseException.class) + public void forceSynchronizeSurveyActivityExtractions_method_should_handle_IOException() throws IOException { + List activityOidsWithoutExtraction = new ArrayList<>(); + activityOidsWithoutExtraction.add(new ObjectId(ACTIVITY_ID_WITHOUT_EXTRACTION)); + when(activityFacade.getActivityIds(ACRONYM, VERSION, null)).thenReturn(activityOidsWithoutExtraction); + when(activityFacade.getByID(ACTIVITY_ID_WITHOUT_EXTRACTION)).thenReturn(surveyActivity); + doThrow(new IOException()).when(extractionGatewayService).createOrUpdateActivityExtraction(Mockito.anyString()); + activityExtractionFacade.forceSynchronizeSurveyActivityExtractions(ACRONYM, VERSION); + } + + + @Test + public void forceCreateOrUpdateActivityExtraction_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { + doReturn(true).when(surveyActivity).isFinalized(); + when(surveyActivity.couldBeExtracted()).thenReturn(true); + doNothing().when(extractionGatewayService).createOrUpdateActivityExtraction(ACTIVITY_ID); + activityExtractionFacade.forceCreateOrUpdateActivityExtraction(ACTIVITY_ID); + verify(extractionGatewayService, Mockito.times(1)).createOrUpdateActivityExtraction(activityExtraction.serialize()); + } + + @Test(expected = HttpResponseException.class) + public void forceCreateOrUpdateActivityExtraction_method_should_handle_ValidationException_in_case_discarded_activity() throws IOException { + when(surveyActivity.isDiscarded()).thenReturn(true); + doThrow(new IOException()).when(extractionGatewayService).createOrUpdateActivityExtraction(Mockito.anyString()); + activityExtractionFacade.forceCreateOrUpdateActivityExtraction(ACTIVITY_ID); + } + + @Test + public void getSurveyActivitiesExtractionAsCsv_method_should_return_bytes_array() throws IOException, DataNotFoundException { + when(extractionGatewayService.getCsvSurveyExtraction(SURVEY_ID)).thenReturn(gatewayResponse); + when(extractionService.createExtraction(csvExtraction)).thenReturn(CSV_BYTES); + assertEquals(CSV_BYTES, activityExtractionFacade.getSurveyActivitiesExtractionAsCsv(ACRONYM, VERSION)); + } + + @Test(expected = HttpResponseException.class) + public void getSurveyActivitiesExtractionAsCsv_method_should_handle_MalformedURLException() throws IOException { + when(extractionGatewayService.getCsvSurveyExtraction(SURVEY_ID)).thenThrow(new MalformedURLException()); + activityExtractionFacade.getSurveyActivitiesExtractionAsCsv(ACRONYM, VERSION); + } + + @Test(expected = HttpResponseException.class) + public void getSurveyActivitiesExtractionAsCsv_method_should_handle_DataNotFoundException() throws IOException, DataNotFoundException { + when(extractionGatewayService.getCsvSurveyExtraction(SURVEY_ID)).thenReturn(gatewayResponse); + when(extractionService.createExtraction(csvExtraction)).thenThrow(new DataNotFoundException()); + activityExtractionFacade.getSurveyActivitiesExtractionAsCsv(ACRONYM, VERSION); + } + + @Test + public void getSurveyActivitiesExtractionAsJson_method_should_return_bytes_array() throws IOException { + when(extractionGatewayService.getJsonSurveyExtraction(SURVEY_ID)).thenReturn(gatewayResponse); + when(gatewayResponse.getData()).thenReturn(EXTRACTIONS_JSON); + assertEquals(EXTRACTIONS_JSON_SIZE, activityExtractionFacade.getSurveyActivitiesExtractionAsJson(ACRONYM, VERSION).size()); + } + + @Test(expected = HttpResponseException.class) + public void getSurveyActivitiesExtractionAsJson_method_should_handle_MalformedURLException() throws IOException { + when(extractionGatewayService.getJsonSurveyExtraction(SURVEY_ID)).thenThrow(new MalformedURLException()); + activityExtractionFacade.getSurveyActivitiesExtractionAsJson(ACRONYM, VERSION); + } + + + @Test + public void getRscriptSurveyExtractionAsCsv_method_should_return_bytes_array() throws IOException { + when(extractionGatewayService.getRscriptSurveyExtraction(surveyExtraction.serialize())).thenReturn(gatewayResponse); + assertEquals(BYTES, activityExtractionFacade.getRscriptSurveyExtractionAsCsv(SURVEY_EXTRACTION_JSON)); + } + + @Test(expected = HttpResponseException.class) + public void getRscriptSurveyExtractionAsCsv_method_should_handle_IOException() throws IOException { + when(extractionGatewayService.getRscriptSurveyExtraction(surveyExtraction.serialize())).thenThrow(new IOException()); + activityExtractionFacade.getRscriptSurveyExtractionAsCsv(SURVEY_EXTRACTION_JSON); + } + + @Test(expected = HttpResponseException.class) + public void getRscriptSurveyExtractionAsCsv_method_should_handle_DataNotFoundException() throws IOException, DataNotFoundException { + when(extractionGatewayService.getRscriptSurveyExtraction(surveyExtraction.serialize())).thenReturn(gatewayResponse); + doReturn(CSV_JSON).when(gatewayResponse).getData(); + doThrow(new DataNotFoundException("")).when(extractionService).createExtraction(csvExtraction); + activityExtractionFacade.getRscriptSurveyExtractionAsCsv(SURVEY_EXTRACTION_JSON); + } + + @Test + public void getRscriptSurveyExtractionAsJson_method_should_return_bytes_array() throws IOException { + when(extractionGatewayService.getRscriptSurveyExtraction(surveyExtraction.serialize())).thenReturn(gatewayResponse); + when(gatewayResponse.getData()).thenReturn(R_SCRIPT_JSON_RESULT); + assertEquals(R_SCRIPT_JSON_RESULT, activityExtractionFacade.getRscriptSurveyExtractionAsJson(SURVEY_EXTRACTION_JSON)); + } + + @Test(expected = HttpResponseException.class) + public void getRscriptSurveyExtractionAsJson_method_should_handle_IOException() throws IOException { + when(extractionGatewayService.getRscriptSurveyExtraction(surveyExtraction.serialize())).thenThrow(new IOException()); + activityExtractionFacade.getRscriptSurveyExtractionAsJson(SURVEY_EXTRACTION_JSON); + } + +} diff --git a/source/otus-business/src/test/java/br/org/otus/extraction/ExtractionFacadeTest.java b/source/otus-business/src/test/java/br/org/otus/extraction/ExtractionFacadeTest.java index 571b5ac45..34ee89764 100644 --- a/source/otus-business/src/test/java/br/org/otus/extraction/ExtractionFacadeTest.java +++ b/source/otus-business/src/test/java/br/org/otus/extraction/ExtractionFacadeTest.java @@ -1,26 +1,12 @@ package br.org.otus.extraction; -import static org.junit.Assert.*; import static org.mockito.Mockito.*; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.util.ArrayList; import br.org.otus.LoggerTestsParent; import br.org.otus.api.ExtractionService; -import br.org.otus.fileuploader.api.FileUploaderFacade; -import br.org.otus.gateway.gates.ExtractionGatewayService; -import br.org.otus.gateway.response.GatewayResponse; import br.org.otus.response.exception.HttpResponseException; import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; import org.ccem.otus.service.DataSourceService; -import org.ccem.otus.service.extraction.ActivityProgressExtraction; -import org.ccem.otus.service.extraction.SurveyActivityExtraction; -import org.ccem.otus.service.extraction.preprocessing.AutocompleteQuestionPreProcessor; -import org.ccem.otus.survey.form.SurveyForm; -import org.ccem.otus.survey.template.SurveyTemplate; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -35,38 +21,18 @@ import br.org.otus.examUploader.business.extraction.ExamUploadExtration; import br.org.otus.laboratory.extraction.LaboratoryExtraction; import br.org.otus.laboratory.participant.api.ParticipantLaboratoryFacade; -import br.org.otus.survey.activity.api.ActivityFacade; -import br.org.otus.survey.api.SurveyFacade; @RunWith(PowerMockRunner.class) @PrepareForTest({ExtractionFacade.class}) public class ExtractionFacadeTest extends LoggerTestsParent { - private static final SurveyTemplate SURVEY_TEMPLATE = new SurveyTemplate(); - private static final String USER_EMAIL = "otus@otus.com"; - private static final String CENTER = "RS"; - private static final String ACRONYM = "ANTC"; - private static final Integer VERSION = 1; - private static final ArrayList SURVEYS = new ArrayList<>(); - private static final byte[] BYTES = new byte[1]; - private static final String PIPELINE_NAME = "pipeline"; - private static final String ACTIVITY_ID = "12345"; - @InjectMocks private ExtractionFacade extractionFacade; @Mock - private ActivityFacade activityFacade; - @Mock - private SurveyFacade surveyFacade; - @Mock private ExamUploadFacade examUploadFacade; @Mock - private AutocompleteQuestionPreProcessor autocompleteQuestionPreProcessor; - @Mock private ParticipantLaboratoryFacade participantLaboratoryFacade; @Mock - private FileUploaderFacade fileUploaderFacade; - @Mock private ExtractionService extractionService; @Mock private DataSourceService dataSourceService; @@ -74,114 +40,14 @@ public class ExtractionFacadeTest extends LoggerTestsParent { @Mock private LaboratoryExtraction laboratoryExtraction; @Mock - private SurveyActivityExtraction surveyActivityExtraction; - @Mock private ExamUploadExtration examUploadExtration; - @Mock - private ActivityProgressExtraction activityProgressExtraction; - @Mock - private ExtractionGatewayService extractionGatewayService; - @Mock - private GatewayResponse gatewayResponse; - private SurveyForm surveyForm = new SurveyForm(SURVEY_TEMPLATE, USER_EMAIL); @Before public void setUp() throws Exception { setUpLogger(ExtractionFacade.class); - SURVEYS.add(surveyForm); - SURVEYS.add(surveyForm); - PowerMockito.when(surveyFacade.get(ACRONYM, VERSION)).thenReturn(SURVEYS.get(0)); - PowerMockito.when(activityFacade.getExtraction(ACRONYM, VERSION)).thenReturn(new ArrayList<>()); - PowerMockito.whenNew(SurveyActivityExtraction.class).withAnyArguments().thenReturn(surveyActivityExtraction); PowerMockito.whenNew(ExamUploadExtration.class).withAnyArguments().thenReturn(examUploadExtration); PowerMockito.whenNew(LaboratoryExtraction.class).withAnyArguments().thenReturn(laboratoryExtraction); - PowerMockito.whenNew(ActivityProgressExtraction.class).withAnyArguments().thenReturn(activityProgressExtraction); - PowerMockito.whenNew(ExtractionGatewayService.class).withNoArguments().thenReturn(extractionGatewayService); - } - - @Test - public void createActivityExtraction_method_should_return_new_extraction_of_activities() throws Exception { - extractionFacade.createActivityExtraction(ACRONYM, VERSION); - Mockito.verify(activityFacade).getExtraction(ACRONYM, VERSION); - Mockito.verify(surveyFacade).get(ACRONYM, VERSION); - Mockito.verify(surveyActivityExtraction, Mockito.times(1)).addPreProcessor(autocompleteQuestionPreProcessor); - Mockito.verify(extractionService).createExtraction(surveyActivityExtraction); - } - - @Test(expected = HttpResponseException.class) - public void createActivityExtraction_method_should_handle_DataNotFoundException() throws DataNotFoundException { - doThrow(new DataNotFoundException()).when(extractionService).createExtraction(surveyActivityExtraction); - extractionFacade.createActivityExtraction(ACRONYM, VERSION); - } - - - @Test - public void createExtractionFromPipeline_method_should_return_bytes_array() throws IOException { - when(extractionGatewayService.getPipelineExtraction(PIPELINE_NAME)).thenReturn(gatewayResponse); - when(gatewayResponse.getData()).thenReturn(BYTES); - assertEquals(BYTES, extractionFacade.createExtractionFromPipeline(PIPELINE_NAME)); - } - - @Test(expected = HttpResponseException.class) - public void createExtractionFromPipeline_method_should_handle_MalformedURLException() throws IOException { - doThrow(new MalformedURLException()).when(extractionGatewayService).getPipelineExtraction(PIPELINE_NAME); - extractionFacade.createExtractionFromPipeline(PIPELINE_NAME); - } - - - @Test - public void createActivityExtraction_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { - doNothing().when(extractionGatewayService).createActivityExtraction(ACTIVITY_ID); - extractionFacade.createActivityExtraction(ACTIVITY_ID); - verify(extractionGatewayService, Mockito.times(1)).createActivityExtraction(ACTIVITY_ID); - verifyLoggerInfoWasCalled(); - } - - @Test(expected = HttpResponseException.class) - public void createActivityExtraction_method_should_handle_IOException() throws IOException { - doThrow(new MalformedURLException()).when(extractionGatewayService).createActivityExtraction(ACTIVITY_ID); - extractionFacade.createActivityExtraction(ACTIVITY_ID); - verifyLoggerSevereWasCalled(); - } - - - @Test - public void updateActivityExtraction_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { - doNothing().when(extractionGatewayService).updateActivityExtraction(ACTIVITY_ID); - extractionFacade.updateActivityExtraction(ACTIVITY_ID); - verify(extractionGatewayService, Mockito.times(1)).updateActivityExtraction(ACTIVITY_ID); - verifyLoggerInfoWasCalled(); - } - - @Test(expected = HttpResponseException.class) - public void updateActivityExtraction_method_should_handle_IOException() throws IOException { - doThrow(new MalformedURLException()).when(extractionGatewayService).updateActivityExtraction(ACTIVITY_ID); - extractionFacade.updateActivityExtraction(ACTIVITY_ID); - verifyLoggerSevereWasCalled(); - } - - - @Test - public void deleteActivityExtraction_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { - doNothing().when(extractionGatewayService).deleteActivityExtraction(ACTIVITY_ID); - extractionFacade.deleteActivityExtraction(ACTIVITY_ID); - verify(extractionGatewayService, Mockito.times(1)).deleteActivityExtraction(ACTIVITY_ID); - verifyLoggerInfoWasCalled(); - } - - @Test(expected = HttpResponseException.class) - public void deleteActivityExtraction_method_should_handle_IOException() throws IOException { - doThrow(new MalformedURLException()).when(extractionGatewayService).deleteActivityExtraction(ACTIVITY_ID); - extractionFacade.deleteActivityExtraction(ACTIVITY_ID); - verifyLoggerSevereWasCalled(); - } - - - @Test - public void listSurveyVersions_method_should_call_listVersions_from_surveyFacade() { - extractionFacade.listSurveyVersions(ACRONYM); - Mockito.verify(surveyFacade).listVersions(ACRONYM); } @@ -212,41 +78,4 @@ public void createLaboratoryExtraction_method_should_handle_DataNotFoundExceptio extractionFacade.createLaboratoryExtraction(); } - - @Test - public void createAttachmentsReportExtraction_method_should_call_getAttachmentsReport_from_extractionService() throws DataNotFoundException { - extractionFacade.createAttachmentsReportExtraction(ACRONYM, VERSION); - Mockito.verify(extractionService).getAttachmentsReport(ACRONYM, VERSION); - } - - @Test(expected = HttpResponseException.class) - public void createAttachmentsReportExtraction_method_should_handle_DataNotFoundException() throws DataNotFoundException { - doThrow(new DataNotFoundException()).when(extractionService).getAttachmentsReport(ACRONYM, VERSION); - extractionFacade.createAttachmentsReportExtraction(ACRONYM, VERSION); - } - - - @Test - public void createActivityProgressExtraction_method_should_call_methods_expected() throws DataNotFoundException { - extractionFacade.createActivityProgressExtraction(CENTER); - Mockito.verify(activityFacade, Mockito.times(1)).getActivityProgressExtraction(CENTER); - Mockito.verify(extractionService, Mockito.times(1)).createExtraction(activityProgressExtraction); - } - - @Test(expected = HttpResponseException.class) - public void createActivityProgressExtraction_method_should_handle_DataNotFoundException() throws DataNotFoundException { - doThrow(new DataNotFoundException()).when(extractionService).createExtraction(activityProgressExtraction); - extractionFacade.createActivityProgressExtraction(CENTER); - } - - - @Test - public void downloadFiles_method_should_call_fileUploaderFacade_downloadFiles_method(){ - ArrayList oids = new ArrayList<>(); - when(fileUploaderFacade.downloadFiles(oids)).thenReturn(BYTES); - byte[] result = extractionFacade.downloadFiles(oids); - verify(fileUploaderFacade, Mockito.times(1)).downloadFiles(oids); - assertEquals(BYTES, result); - } - } diff --git a/source/otus-business/src/test/java/br/org/otus/extraction/RscriptFacadeTest.java b/source/otus-business/src/test/java/br/org/otus/extraction/RscriptFacadeTest.java new file mode 100644 index 000000000..56b87a12d --- /dev/null +++ b/source/otus-business/src/test/java/br/org/otus/extraction/RscriptFacadeTest.java @@ -0,0 +1,81 @@ +package br.org.otus.extraction; + +import br.org.otus.gateway.gates.ExtractionGatewayService; +import br.org.otus.gateway.response.GatewayResponse; +import br.org.otus.response.exception.HttpResponseException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.io.IOException; + +import static org.mockito.Mockito.*; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({RscriptFacade.class}) +public class RscriptFacadeTest { + + private static final String R_SCRIPT_JSON = "{}"; + private static final String R_SCRIPT_NAME = "script"; + + @InjectMocks + private RscriptFacade rscriptFacade; + + @Mock + private ExtractionGatewayService extractionGatewayService; + @Mock + private GatewayResponse gatewayResponse; + + @Before + public void setUp() throws Exception { + PowerMockito.whenNew(ExtractionGatewayService.class).withNoArguments().thenReturn(extractionGatewayService); + } + + @Test + public void createOrUpdateRscript_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { + doNothing().when(extractionGatewayService).createOrUpdateRscript(R_SCRIPT_JSON); + rscriptFacade.createOrUpdate(R_SCRIPT_JSON); + verify(extractionGatewayService, Mockito.times(1)).createOrUpdateRscript(R_SCRIPT_JSON); + } + + @Test(expected = HttpResponseException.class) + public void createOrUpdateRscript_method_should_handle_IOException() throws IOException { + doThrow(new IOException()).when(extractionGatewayService).createOrUpdateRscript(R_SCRIPT_JSON); + rscriptFacade.createOrUpdate(R_SCRIPT_JSON); + } + + @Test + public void get_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { + doReturn(gatewayResponse).when(extractionGatewayService).getRscript(R_SCRIPT_NAME); + when(gatewayResponse.getData()).thenReturn(R_SCRIPT_JSON); + rscriptFacade.get(R_SCRIPT_NAME); + verify(extractionGatewayService, Mockito.times(1)).getRscript(R_SCRIPT_NAME); + } + + @Test(expected = HttpResponseException.class) + public void get_method_should_handle_IOException() throws IOException { + doThrow(new IOException()).when(extractionGatewayService).getRscript(R_SCRIPT_NAME); + rscriptFacade.get(R_SCRIPT_NAME); + } + + @Test + public void delete_method_should_call_same_method_from_ExtractionGatewayService() throws IOException { + doNothing().when(extractionGatewayService).deleteRscript(R_SCRIPT_NAME); + rscriptFacade.delete(R_SCRIPT_NAME); + verify(extractionGatewayService, Mockito.times(1)).deleteRscript(R_SCRIPT_NAME); + } + + @Test(expected = HttpResponseException.class) + public void delete_method_should_handle_IOException() throws IOException { + doThrow(new IOException()).when(extractionGatewayService).deleteRscript(R_SCRIPT_NAME); + rscriptFacade.delete(R_SCRIPT_NAME); + } + +} diff --git a/source/otus-business/src/test/java/br/org/otus/participant/api/NoteAboutParticipantFacadeTest.java b/source/otus-business/src/test/java/br/org/otus/participant/api/NoteAboutParticipantFacadeTest.java new file mode 100644 index 000000000..f509af972 --- /dev/null +++ b/source/otus-business/src/test/java/br/org/otus/participant/api/NoteAboutParticipantFacadeTest.java @@ -0,0 +1,152 @@ +package br.org.otus.participant.api; + +import br.org.otus.LoggerTestsParent; +import br.org.otus.model.User; +import br.org.otus.response.exception.HttpResponseException; +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.service.NoteAboutParticipantService; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({NoteAboutParticipantFacade.class, SearchSettingsDto.class}) +public class NoteAboutParticipantFacadeTest extends LoggerTestsParent { + + private static final String NOTE_ABOUT_PARTICIPANT_ID = "5a33cb4a28f10d1043710f7d"; + private static final ObjectId NOTE_ABOUT_PARTICIPANT_OID = new ObjectId(NOTE_ABOUT_PARTICIPANT_ID); + private static final String NOTE_ABOUT_PARTICIPANT_JSON = "{}"; + private static final Boolean STARRED = true; + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final String SEARCH_SETTINGS_JSON = "{}"; + private static final ObjectId USER_OID = new ObjectId("5a33cb4a28f10d1043710f00"); + + @InjectMocks + private NoteAboutParticipantFacade facade; + + @Mock + private NoteAboutParticipantService service; + + @Mock + private NoteAboutParticipant noteAboutParticipant; + @Mock + private User user; + @Mock + private SearchSettingsDto searchSettingsDto; + + private DataNotFoundException dataNotFoundException = new DataNotFoundException(new Throwable("error")); + private ValidationException validationException = new ValidationException(new Throwable("error")); + + @Before + public void setUp() throws Exception { + setUpLogger(NoteAboutParticipantFacade.class); + + PowerMockito.whenNew(NoteAboutParticipant.class).withNoArguments().thenReturn(noteAboutParticipant); + doReturn(noteAboutParticipant).when(noteAboutParticipant).deserializeNonStatic(NOTE_ABOUT_PARTICIPANT_JSON); + doReturn(USER_OID).when(user).get_id(); + + PowerMockito.mockStatic(SearchSettingsDto.class); + when(SearchSettingsDto.class, "deserialize", SEARCH_SETTINGS_JSON).thenReturn(searchSettingsDto); + } + + @Test + public void create_method_should_call_create_service_method_and_return_id(){ + doReturn(NOTE_ABOUT_PARTICIPANT_OID).when(service).create(USER_OID, noteAboutParticipant); + assertEquals( + NOTE_ABOUT_PARTICIPANT_OID.toHexString(), + facade.create(user, NOTE_ABOUT_PARTICIPANT_JSON) + ); + } + + @Test + public void update_method_should_call_update_service_method() throws ValidationException, DataNotFoundException { + facade.update(user, NOTE_ABOUT_PARTICIPANT_JSON); + verify(service, Mockito.times(1)).update(USER_OID, noteAboutParticipant); + } + + @Test(expected = HttpResponseException.class) + public void update_method_should_handle_DataNotFoundException() throws ValidationException, DataNotFoundException { + doThrow(dataNotFoundException).when(service).update(USER_OID, noteAboutParticipant); + facade.update(user, NOTE_ABOUT_PARTICIPANT_JSON); + } + + @Test(expected = HttpResponseException.class) + public void update_method_should_handle_ValidationException() throws ValidationException, DataNotFoundException { + doThrow(validationException).when(service).update(USER_OID, noteAboutParticipant); + facade.update(user, NOTE_ABOUT_PARTICIPANT_JSON); + verifyLoggerSevereWasCalled(); + } + + @Test + public void updateStarred_method_should_call_updateStarred_service_method() throws ValidationException, DataNotFoundException { + facade.updateStarred(user, NOTE_ABOUT_PARTICIPANT_ID, STARRED); + verify(service, Mockito.times(1)).updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + } + + @Test(expected = HttpResponseException.class) + public void updateStarred_method_should_handle_DataNotFoundException() throws ValidationException, DataNotFoundException { + doThrow(dataNotFoundException).when(service).updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + facade.updateStarred(user, NOTE_ABOUT_PARTICIPANT_ID, STARRED); + } + + @Test(expected = HttpResponseException.class) + public void updateStarred_method_should_handle_ValidationException() throws ValidationException, DataNotFoundException { + doThrow(validationException).when(service).updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + facade.updateStarred(user, NOTE_ABOUT_PARTICIPANT_ID, STARRED); + verifyLoggerSevereWasCalled(); + } + + @Test + public void delete_method_should_call_delete_service_method() throws ValidationException, DataNotFoundException { + facade.delete(user, NOTE_ABOUT_PARTICIPANT_ID); + verify(service, Mockito.times(1)).delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + } + + @Test(expected = HttpResponseException.class) + public void delete_method_should_handle_DataNotFoundException() throws ValidationException, DataNotFoundException { + doThrow(dataNotFoundException).when(service).delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + facade.delete(user, NOTE_ABOUT_PARTICIPANT_ID); + } + + @Test(expected = HttpResponseException.class) + public void delete_method_should_handle_ValidationException() throws ValidationException, DataNotFoundException { + doThrow(validationException).when(service).delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + facade.delete(user, NOTE_ABOUT_PARTICIPANT_ID); + verifyLoggerSevereWasCalled(); + } + + @Test + public void getAll_method_should_call_getAll_service_method() throws ValidationException, DataNotFoundException, MemoryExcededException { + facade.getAll(user, RECRUITMENT_NUMBER, SEARCH_SETTINGS_JSON); + verify(service, Mockito.times(1)).getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto); + } + + @Test(expected = HttpResponseException.class) + public void getAll_method_should_handle_DataNotFoundException() throws ValidationException, DataNotFoundException, MemoryExcededException { + doThrow(dataNotFoundException).when(service).getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto); + facade.getAll(user, RECRUITMENT_NUMBER, SEARCH_SETTINGS_JSON); + } + + @Test(expected = HttpResponseException.class) + public void getAll_method_should_handle_ValidationException() throws ValidationException, DataNotFoundException, MemoryExcededException { + doThrow(validationException).when(service).getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto); + facade.getAll(user, RECRUITMENT_NUMBER, SEARCH_SETTINGS_JSON); + verifyLoggerSevereWasCalled(); + } + +} diff --git a/source/otus-business/src/test/java/br/org/otus/survey/activity/api/ActivityFacadeTest.java b/source/otus-business/src/test/java/br/org/otus/survey/activity/api/ActivityFacadeTest.java index e104338e0..2292dac8a 100644 --- a/source/otus-business/src/test/java/br/org/otus/survey/activity/api/ActivityFacadeTest.java +++ b/source/otus-business/src/test/java/br/org/otus/survey/activity/api/ActivityFacadeTest.java @@ -282,4 +282,18 @@ public void discardById_method_should_handle_DataNotFoundException() throws Exce PowerMockito.doThrow(new DataNotFoundException("")).when(activityTasksService, "discardById", ACTIVITY_ID); activityFacade.discardByID(ACTIVITY_ID); } + + @Test + public void getActivityIds_method_should_invoke_ActivityService_getActivityIds() throws MemoryExcededException { + List activityIdsToExcludeOfQuery = new ArrayList<>(); + activityFacade.getActivityIds(ACRONYM, VERSION, activityIdsToExcludeOfQuery); + verify(activityService, Mockito.times(1)).getActivityIds(ACRONYM, VERSION, activityIdsToExcludeOfQuery); + } + + @Test(expected = HttpResponseException.class) + public void getActivityIds_method_should_handle_MemoryExceededException() throws Exception { + List activityIdsToExcludeOfQuery = new ArrayList<>(); + PowerMockito.doThrow(new MemoryExcededException("")).when(activityService, "getActivityIds", ACRONYM, VERSION, activityIdsToExcludeOfQuery); + activityFacade.getActivityIds(ACRONYM, VERSION, activityIdsToExcludeOfQuery); + } } \ No newline at end of file diff --git a/source/otus-business/src/test/java/br/org/otus/survey/services/ActivityTasksServiceBeanTest.java b/source/otus-business/src/test/java/br/org/otus/survey/services/ActivityTasksServiceBeanTest.java index f469a0248..54b1047ba 100644 --- a/source/otus-business/src/test/java/br/org/otus/survey/services/ActivityTasksServiceBeanTest.java +++ b/source/otus-business/src/test/java/br/org/otus/survey/services/ActivityTasksServiceBeanTest.java @@ -1,7 +1,7 @@ package br.org.otus.survey.services; import br.org.otus.LoggerTestsParent; -import br.org.otus.extraction.ExtractionFacade; +import br.org.otus.extraction.ActivityExtractionFacade; import br.org.otus.model.User; import br.org.otus.outcomes.FollowUpFacade; import br.org.otus.response.exception.HttpResponseException; @@ -95,7 +95,7 @@ public class ActivityTasksServiceBeanTest extends LoggerTestsParent { @Mock private ActivitySharingService activitySharingService; @Mock - private ExtractionFacade extractionFacade; + private ActivityExtractionFacade extractionFacade; private SurveyActivity surveyActivity; private SurveyActivity surveyActivityToUpdate; @@ -121,7 +121,6 @@ public void create_method_should_create_surveyActivity_and_extraction() throws I assertNotNull(surveyActivity.getActivityID()); assertEquals(ACTIVITY_ID, surveyActivity.getActivityID().toString()); - verify(extractionFacade, times(1)).createActivityExtraction(ACTIVITY_ID); assertEquals(ACTIVITY_ID, result); } @@ -136,25 +135,8 @@ public void create_method_should_create_surveyActivity_and_extraction_and_autoFi assertNotNull(surveyActivity.getActivityID()); assertEquals(ACTIVITY_ID, surveyActivity.getActivityID().toString()); verify(followUpFacade, times(1)).createParticipantActivityAutoFillEvent(surveyActivity, NOTIFY); - verify(extractionFacade, times(1)).createActivityExtraction(ACTIVITY_ID); } - @Test - public void create_method_should_log_extraction_creation_exception() throws InterruptedException { - doThrow(new HttpResponseException(null)).when(extractionFacade).createActivityExtraction(ACTIVITY_ID); - when(surveyActivity.getMode()).thenReturn(ActivityMode.ONLINE); - - String result = service.create(surveyActivity, NOTIFY); - Thread.sleep(100); - - assertEquals(ACTIVITY_ID, result); - assertNotNull(surveyActivity.getActivityID()); - assertEquals(ACTIVITY_ID, surveyActivity.getActivityID().toString()); - verify(extractionFacade, times(1)).createActivityExtraction(ACTIVITY_ID); - verifyLoggerSevereWasCalled(); - } - - @Test public void updateActivity_method_should_update_surveyActivity_and_extraction() throws Exception { mockUserForUpdate(); @@ -163,7 +145,6 @@ public void updateActivity_method_should_update_surveyActivity_and_extraction() SurveyActivity updatedActivity = service.updateActivity(surveyActivityToUpdate, TOKEN_BEARER); Thread.sleep(100); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID); assertEquals(surveyActivityToUpdate, updatedActivity); } @@ -180,7 +161,7 @@ public void updateActivity_method_should_update_autofillSurveyActivity_and_extra String lastStatusHistoryName = surveyActivityToUpdate.getLastStatus().get().getName(); verify(followUpFacade, times(1)).statusUpdateEvent(lastStatusHistoryName, ACTIVITY_ID); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID); + verify(extractionFacade, times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID); } @Test @@ -204,13 +185,13 @@ public void updateActivity_method_should_update_autofillSurveyActivity_and_cance public void updateActivity_method_should_log_extraction_update_exception() throws Exception { mockUserForUpdate(); setUpdatedActivity(ActivityMode.AUTOFILL); - doThrow(new HttpResponseException(null)).when(extractionFacade).updateActivityExtraction(ACTIVITY_ID); + doThrow(new HttpResponseException(null)).when(extractionFacade).createOrUpdateActivityExtraction(ACTIVITY_ID); SurveyActivity updatedActivity = service.updateActivity(surveyActivityToUpdate, TOKEN_BEARER); Thread.sleep(100); assertEquals(surveyActivityToUpdate, updatedActivity); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID); + verify(extractionFacade, times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID); verifyLoggerSevereWasCalled(); } @@ -228,20 +209,20 @@ public void save_method_should_save_offlineActivityCollection_surveyActivities_a service.save(USER_EMAIL, offlineActivityCollection); Thread.sleep(100); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID_2); + verify(extractionFacade, times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID); + verify(extractionFacade, times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID_2); } @Test public void save_method_should_log_extraction_update_exception() throws InterruptedException, DataNotFoundException { setOfflineActivityCollection(); - doThrow(new HttpResponseException(null)).when(extractionFacade).updateActivityExtraction(ACTIVITY_ID); + doThrow(new HttpResponseException(null)).when(extractionFacade).createOrUpdateActivityExtraction(ACTIVITY_ID); service.save(USER_EMAIL, offlineActivityCollection); Thread.sleep(100); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID); - verify(extractionFacade, times(1)).updateActivityExtraction(ACTIVITY_ID_2); + verify(extractionFacade, times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID); + verify(extractionFacade, times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID_2); verifyLoggerSevereWasCalled(); } diff --git a/source/otus-center/pom.xml b/source/otus-center/pom.xml index 8f974d58a..bf71b92f9 100644 --- a/source/otus-center/pom.xml +++ b/source/otus-center/pom.xml @@ -6,7 +6,7 @@ otus-root org.ccem.otus - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-commons/pom.xml b/source/otus-commons/pom.xml index dfb723bd2..3f1817d53 100644 --- a/source/otus-commons/pom.xml +++ b/source/otus-commons/pom.xml @@ -6,7 +6,7 @@ otus-root org.ccem.otus - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml @@ -28,6 +28,12 @@ ${mongodb.bson.version} compile + + org.ccem.otus + survey-model + 1.12.0 + compile + diff --git a/source/otus-commons/src/main/java/org/ccem/otus/exceptions/webservice/validation/ValidationException.java b/source/otus-commons/src/main/java/org/ccem/otus/exceptions/webservice/validation/ValidationException.java index 445912889..51abb41f3 100644 --- a/source/otus-commons/src/main/java/org/ccem/otus/exceptions/webservice/validation/ValidationException.java +++ b/source/otus-commons/src/main/java/org/ccem/otus/exceptions/webservice/validation/ValidationException.java @@ -5,6 +5,10 @@ public class ValidationException extends Exception { private static final long serialVersionUID = 1L; private Object data; + public ValidationException(String message) { + super(message); + } + public ValidationException(Throwable cause) { super(cause); } diff --git a/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModel.java b/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModel.java index 499143a93..109dff727 100644 --- a/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModel.java +++ b/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModel.java @@ -1,19 +1,42 @@ package org.ccem.otus.model; import com.google.gson.GsonBuilder; +import org.ccem.otus.survey.template.utils.adapters.LocalDateTimeAdapter; +import org.ccem.otus.utils.LongAdapter; + +import java.time.LocalDateTime; public abstract class SerializableModel { - protected static String serialize(Object object) { - return getGsonBuilder().create().toJson(object); + protected static Object deserialize(String json, Class clazz){ + return new GsonBuilder().create().fromJson(json, clazz); } - protected static Object deserialize(String json, Class clazz){ - return getGsonBuilder().create().fromJson(json, clazz); + /* Non static methods */ + + public String serialize(){ + return getGsonBuilderNonStatic().create().toJson(this); + } + + public T deserializeNonStatic(String json){ + return (T) getGsonBuilderNonStatic().create().fromJson(json, this.getClass()); + } + + protected GsonBuilder getGsonBuilderNonStatic() { + GsonBuilder builder = new GsonBuilder(); + registerSpecificTypeAdapter(builder); + return builder; + } + + /* Override or not by child class */ + protected void registerSpecificTypeAdapter(GsonBuilder builder){ } + + protected void registerGsonBuilderLongAdapter(GsonBuilder builder){ + builder.registerTypeAdapter(Long.class, new LongAdapter()); } - protected static GsonBuilder getGsonBuilder() { - return new GsonBuilder(); + protected void registerGsonBuilderLocalDateTimeAdapter(GsonBuilder builder){ + builder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()); } } diff --git a/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModelWithID.java b/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModelWithID.java index c3bfbdb35..f6fdf29da 100644 --- a/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModelWithID.java +++ b/source/otus-commons/src/main/java/org/ccem/otus/model/SerializableModelWithID.java @@ -5,16 +5,11 @@ import org.ccem.otus.utils.ObjectIdAdapter; import org.ccem.otus.utils.ObjectIdToStringAdapter; -public abstract class SerializableModelWithID { - - public static String serialize(Object object) { - return getGsonBuilder().create().toJson(object); - } +public abstract class SerializableModelWithID extends SerializableModel { protected static Object deserialize(String json, Class clazz){ return getGsonBuilder().create().fromJson(json, clazz); } - protected static GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(ObjectId.class, new ObjectIdAdapter()); @@ -27,4 +22,21 @@ public static GsonBuilder getFrontGsonBuilder() { return builder; } + /* Non static methods */ + + @Override + protected GsonBuilder getGsonBuilderNonStatic() { + GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(ObjectId.class, new ObjectIdAdapter()); + registerSpecificTypeAdapter(builder); + return builder; + } + + public GsonBuilder getFrontGsonBuilderNonStatic() { + GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(ObjectId.class, new ObjectIdToStringAdapter()); + registerSpecificTypeAdapter(builder); + return builder; + } + } diff --git a/source/otus-commons/src/main/java/org/ccem/otus/model/searchSettingsDto/OrderSettingsDto.java b/source/otus-commons/src/main/java/org/ccem/otus/model/searchSettingsDto/OrderSettingsDto.java new file mode 100644 index 000000000..2155043d5 --- /dev/null +++ b/source/otus-commons/src/main/java/org/ccem/otus/model/searchSettingsDto/OrderSettingsDto.java @@ -0,0 +1,37 @@ +package org.ccem.otus.model.searchSettingsDto; + +import org.ccem.otus.exceptions.Dto; +import org.ccem.otus.model.SerializableModel; + +public class OrderSettingsDto extends SerializableModel implements Dto { + + private Enum fieldOptions; + private String[] fields; + private Integer mode; + + public OrderSettingsDto(Enum fieldOptions) { + this.fieldOptions = fieldOptions; + } + + public String[] getFields() { return fields; } + + public Integer getMode() { return mode; } + + public Boolean isValid() { + if(fields == null){ + return (mode == null); + } + if(mode == null || (mode != 1 && mode != -1)){ + return false; + } + boolean fieldsAreValid = (fields.length > 0); + for(String field : fields){ + fieldsAreValid &= (fieldOptions.valueOf(fieldOptions.getClass(), field) != null); + } + return fieldsAreValid; + } + + public static OrderSettingsDto deserialize(String json){ + return (OrderSettingsDto)deserialize(json, OrderSettingsDto.class); + } +} diff --git a/source/otus-commons/src/main/java/org/ccem/otus/model/searchSettingsDto/SearchSettingsDto.java b/source/otus-commons/src/main/java/org/ccem/otus/model/searchSettingsDto/SearchSettingsDto.java new file mode 100644 index 000000000..ad7d83c3f --- /dev/null +++ b/source/otus-commons/src/main/java/org/ccem/otus/model/searchSettingsDto/SearchSettingsDto.java @@ -0,0 +1,37 @@ +package org.ccem.otus.model.searchSettingsDto; + +import org.ccem.otus.model.SerializableModel; + +public class SearchSettingsDto extends SerializableModel { + + protected int currentQuantity; + protected int quantityToGet; + protected OrderSettingsDto order; + + public SearchSettingsDto(){} + + public SearchSettingsDto(Enum orderFieldsOptions) { + order = new OrderSettingsDto(orderFieldsOptions); + } + + public int getCurrentQuantity() { + return currentQuantity; + } + + public int getQuantityToGet() { + return quantityToGet; + } + + public OrderSettingsDto getOrder() { + return order; + } + + public Boolean isValid() { + return (currentQuantity >= 0 && quantityToGet > 0 && (order == null || order.isValid())); + } + + public static SearchSettingsDto deserialize(String json){ + return (SearchSettingsDto)deserialize(json, SearchSettingsDto.class); + } + +} diff --git a/source/otus-commons/src/main/java/org/ccem/otus/utils/LongAdapter.java b/source/otus-commons/src/main/java/org/ccem/otus/utils/LongAdapter.java new file mode 100644 index 000000000..53e1484c6 --- /dev/null +++ b/source/otus-commons/src/main/java/org/ccem/otus/utils/LongAdapter.java @@ -0,0 +1,22 @@ +package org.ccem.otus.utils; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import java.lang.reflect.Type; + +public class LongAdapter implements JsonDeserializer { + + private static String NUMBER_LONG = "$numberLong"; + + @Override + public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + if (json.isJsonObject()) { + return json.getAsJsonObject().get(NUMBER_LONG).getAsLong(); + } + return json.getAsLong(); + } + +} diff --git a/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelTest.java b/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelTest.java index c10b04f38..4a580f54c 100644 --- a/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelTest.java +++ b/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelTest.java @@ -1,28 +1,58 @@ package org.ccem.otus.model; import com.google.gson.GsonBuilder; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; @RunWith(PowerMockRunner.class) +@PrepareForTest({SerializableModel.class, GsonBuilder.class}) public class SerializableModelTest { - @Test - public void serializeStaticMethod_should_convert_objectModel_to_JsonString() { - assertTrue(SerializableModel.serialize(Mockito.anyObject()) instanceof String); + private static final int NUM_TYPE_ADAPTERS = 2; + private static final String JSON = "{}"; + + private class FakeModel extends SerializableModel { + @Override + protected void registerSpecificTypeAdapter(GsonBuilder builder){ + registerGsonBuilderLocalDateTimeAdapter(builder); + registerGsonBuilderLongAdapter(builder); + } + } + + private FakeModel serializableModel; + private GsonBuilder builder; + + @Before + public void setUp() throws Exception { + serializableModel = new FakeModel(); + + builder = PowerMockito.spy(new GsonBuilder()); + PowerMockito.whenNew(GsonBuilder.class).withNoArguments().thenReturn(builder); } @Test - public void deserializeStaticMethod_should_convert_JsonString_to_objectModel() { + public void deserialize_static_method_should_convert_JsonString_to_objectModel() { assertTrue(SerializableModel.deserialize("{}", Object.class) instanceof Object); } @Test - public void getGsonBuilder_return_GsonBuilder_instance(){ - assertTrue(SerializableModel.getGsonBuilder() instanceof GsonBuilder); + public void serialize_method_should_convert_objectModel_to_JsonString() { + assertTrue(serializableModel.serialize() instanceof String); + verify(builder, Mockito.times(NUM_TYPE_ADAPTERS)).registerTypeAdapter(Mockito.any(), Mockito.any()); } + + @Test + public void deserializeNonStatic_method_should_convert_objectModel_to_JsonString() { + assertTrue(serializableModel.deserializeNonStatic(JSON) instanceof FakeModel); + verify(builder, Mockito.times(NUM_TYPE_ADAPTERS)).registerTypeAdapter(Mockito.any(), Mockito.any()); + } + } diff --git a/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelWithIDTest.java b/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelWithIDTest.java index 52f497070..a6ed9cef2 100644 --- a/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelWithIDTest.java +++ b/source/otus-commons/src/test/java/org/ccem/otus/model/SerializableModelWithIDTest.java @@ -1,19 +1,43 @@ package org.ccem.otus.model; import com.google.gson.GsonBuilder; +import org.bson.types.ObjectId; +import org.ccem.otus.utils.ObjectIdAdapter; +import org.ccem.otus.utils.ObjectIdToStringAdapter; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; @RunWith(PowerMockRunner.class) +@PrepareForTest({SerializableModelWithID.class, GsonBuilder.class, ObjectIdAdapter.class, ObjectIdToStringAdapter.class}) public class SerializableModelWithIDTest { - @Test - public void serializeStaticMethod_should_convert_objectModel_to_JsonString() { - assertTrue(SerializableModelWithID.serialize(Mockito.anyObject()) instanceof String); + private class FakeModel extends SerializableModelWithID { } + + private FakeModel serializableModelWithId; + private GsonBuilder builder; + private ObjectIdAdapter objectIdAdapter; + private ObjectIdToStringAdapter objectIdToStringAdapter; + + @Before + public void setUp() throws Exception { + serializableModelWithId = new FakeModel(); + + builder = PowerMockito.spy(new GsonBuilder()); + PowerMockito.whenNew(GsonBuilder.class).withNoArguments().thenReturn(builder); + + objectIdAdapter = PowerMockito.spy(new ObjectIdAdapter()); + PowerMockito.whenNew(ObjectIdAdapter.class).withNoArguments().thenReturn(objectIdAdapter); + + objectIdToStringAdapter = PowerMockito.spy(new ObjectIdToStringAdapter()); + PowerMockito.whenNew(ObjectIdToStringAdapter.class).withNoArguments().thenReturn(objectIdToStringAdapter); } @Test @@ -30,4 +54,16 @@ public void getGsonBuilder_return_GsonBuilder_instance(){ public void getFrontGsonBuilder_return_GsonBuilder_instance(){ assertTrue(SerializableModelWithID.getFrontGsonBuilder() instanceof GsonBuilder); } + + @Test + public void serialize_method_should_convert_ObjectModel_to_JsonString_and_register_ObjectIdAdapter(){ + assertTrue(serializableModelWithId.serialize() instanceof String); + verify(builder, Mockito.times(1)).registerTypeAdapter(ObjectId.class, objectIdAdapter); + } + + @Test + public void getFrontGsonBuilderNonStatic_method_should_return_register_ObjectIdToStringAdapter(){ + assertTrue(serializableModelWithId.getFrontGsonBuilderNonStatic() instanceof GsonBuilder); + verify(builder, Mockito.times(1)).registerTypeAdapter(ObjectId.class, objectIdToStringAdapter); + } } diff --git a/source/otus-commons/src/test/java/org/ccem/otus/model/searchSettingsDto/SearchSettingsDtoTest.java b/source/otus-commons/src/test/java/org/ccem/otus/model/searchSettingsDto/SearchSettingsDtoTest.java new file mode 100644 index 000000000..a4e6b08c2 --- /dev/null +++ b/source/otus-commons/src/test/java/org/ccem/otus/model/searchSettingsDto/SearchSettingsDtoTest.java @@ -0,0 +1,83 @@ +package org.ccem.otus.model.searchSettingsDto; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.junit.Assert.*; +import static org.powermock.api.mockito.PowerMockito.doReturn; + +@RunWith(PowerMockRunner.class) +public class SearchSettingsDtoTest { + + private static final int CURRENT_QUANTITY = 0; + private static final int INVALID_CURRENT_QUANTITY = -1; + private static final int QUANTITY_TO_GET = 5; + private static final int INVALID_QUANTITY_TO_GET = 0; + private static final Enum ORDER_FIELDS_OPTIONS = null; + private static final String JSON = "{}"; + + private SearchSettingsDto searchSettingsDto; + @Mock + private OrderSettingsDto orderSettingsDto; + + @Before + public void setUp(){ + searchSettingsDto = new SearchSettingsDto(); + Whitebox.setInternalState(searchSettingsDto, "currentQuantity", CURRENT_QUANTITY); + Whitebox.setInternalState(searchSettingsDto, "quantityToGet", QUANTITY_TO_GET); + } + + @Test + public void constructor_with_args_should_set_oderSettingDto(){ + searchSettingsDto = new SearchSettingsDto(ORDER_FIELDS_OPTIONS); + assertNotNull(searchSettingsDto.getOrder()); + } + + @Test + public void getters_check(){ + assertEquals(CURRENT_QUANTITY, searchSettingsDto.getCurrentQuantity()); + assertEquals(QUANTITY_TO_GET, searchSettingsDto.getQuantityToGet()); + assertNull(searchSettingsDto.getOrder()); + } + + @Test + public void isValid_method_should_return_true_with_null_orderSettingsDto(){ + assertTrue(searchSettingsDto.isValid()); + } + + @Test + public void isValid_method_should_return_true_with_NOT_null_orderSettingsDto(){ + Whitebox.setInternalState(searchSettingsDto, "order", orderSettingsDto); + doReturn(true).when(orderSettingsDto).isValid(); + assertTrue(searchSettingsDto.isValid()); + } + + @Test + public void isValid_method_should_return_false_in_case_invalid_currentQuantity(){ + Whitebox.setInternalState(searchSettingsDto, "currentQuantity", INVALID_CURRENT_QUANTITY); + assertFalse(searchSettingsDto.isValid()); + } + + @Test + public void isValid_method_should_return_false_in_case_invalid_quantityToGet(){ + Whitebox.setInternalState(searchSettingsDto, "quantityToGet", INVALID_QUANTITY_TO_GET); + assertFalse(searchSettingsDto.isValid()); + } + + @Test + public void isValid_method_should_return_false_in_case_invalid_orderSettingsDto(){ + Whitebox.setInternalState(searchSettingsDto, "order", orderSettingsDto); + doReturn(false).when(orderSettingsDto).isValid(); + assertFalse(searchSettingsDto.isValid()); + } + + @Test + public void deserialize_static_method_should_convert_JsonString_to_objectModel(){ + assertTrue(SearchSettingsDto.deserialize(JSON) instanceof SearchSettingsDto); + } + +} diff --git a/source/otus-configuration/pom.xml b/source/otus-configuration/pom.xml index 4539688a8..67cd2dc1a 100644 --- a/source/otus-configuration/pom.xml +++ b/source/otus-configuration/pom.xml @@ -6,7 +6,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-datasource/pom.xml b/source/otus-datasource/pom.xml index 24260abe1..7fe0fd775 100644 --- a/source/otus-datasource/pom.xml +++ b/source/otus-datasource/pom.xml @@ -6,7 +6,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-datasource/src/main/java/org/ccem/otus/persistence/DataSourceDao.java b/source/otus-datasource/src/main/java/org/ccem/otus/persistence/DataSourceDao.java index 8424e9fb8..549ea0d6f 100644 --- a/source/otus-datasource/src/main/java/org/ccem/otus/persistence/DataSourceDao.java +++ b/source/otus-datasource/src/main/java/org/ccem/otus/persistence/DataSourceDao.java @@ -20,4 +20,6 @@ public interface DataSourceDao { DataSource findByID(String id) throws DataNotFoundException; DataSourceValuesMapping getDataSourceMapping(); + + List find(List datasourceNames); } diff --git a/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceService.java b/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceService.java index 1b9382bb5..b4093dd18 100644 --- a/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceService.java +++ b/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceService.java @@ -21,4 +21,6 @@ public interface DataSourceService { String getElementExtractionValue(List dataSources, String value); void populateDataSourceMapping(); + + List list(List dataSourceNames); } diff --git a/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceServiceBean.java b/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceServiceBean.java index 9956f63ea..01f60ad5a 100644 --- a/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceServiceBean.java +++ b/source/otus-datasource/src/main/java/org/ccem/otus/service/DataSourceServiceBean.java @@ -11,6 +11,7 @@ import javax.inject.Inject; import java.util.HashSet; import java.util.List; +import java.util.stream.Collectors; @Stateless public class DataSourceServiceBean implements DataSourceService { @@ -76,5 +77,10 @@ public void populateDataSourceMapping() { this.dataSourceValuesMapping = dataSourceDao.getDataSourceMapping(); } + @Override + public List list(List dataSourceIds) { + return dataSourceDao.find(dataSourceIds); + } + } diff --git a/source/otus-ear/pom.xml b/source/otus-ear/pom.xml index 1be261a5e..5efdc7e68 100644 --- a/source/otus-ear/pom.xml +++ b/source/otus-ear/pom.xml @@ -8,7 +8,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-exam-uploader/pom.xml b/source/otus-exam-uploader/pom.xml index 98d2d4db0..cd4ddb8aa 100644 --- a/source/otus-exam-uploader/pom.xml +++ b/source/otus-exam-uploader/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-extraction/pom.xml b/source/otus-extraction/pom.xml index 49d98b279..86e916ab8 100644 --- a/source/otus-extraction/pom.xml +++ b/source/otus-extraction/pom.xml @@ -8,7 +8,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-extraction/src/main/java/br/org/otus/api/CsvExtraction.java b/source/otus-extraction/src/main/java/br/org/otus/api/CsvExtraction.java new file mode 100644 index 000000000..5c0446064 --- /dev/null +++ b/source/otus-extraction/src/main/java/br/org/otus/api/CsvExtraction.java @@ -0,0 +1,38 @@ +package br.org.otus.api; + +import com.google.gson.GsonBuilder; +import org.bson.Document; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; + +import java.util.List; +import java.util.zip.DataFormatException; + +public class CsvExtraction implements Extractable { + + private static final String HEADER_KEY_NAME = "header"; + private static final String VALUES_KEY_NAME = "values"; + + private List header; + private List> values; + + public CsvExtraction(String content) throws DataFormatException { + try{ + Document doc = new GsonBuilder().create().fromJson(content, Document.class); + this.header = (List) doc.get(HEADER_KEY_NAME); + this.values = (List>)doc.get(VALUES_KEY_NAME); + } + catch(Exception e){ + throw new DataFormatException("Invalid csv content: " + e.getMessage()); + } + } + + @Override + public List getHeaders() { + return header; + } + + @Override + public List> getValues() throws DataNotFoundException { + return this.values; + } +} diff --git a/source/otus-extraction/src/main/java/br/org/otus/service/CsvWriter.java b/source/otus-extraction/src/main/java/br/org/otus/service/CsvWriter.java index cab1d4b90..9eb1026da 100644 --- a/source/otus-extraction/src/main/java/br/org/otus/service/CsvWriter.java +++ b/source/otus-extraction/src/main/java/br/org/otus/service/CsvWriter.java @@ -2,6 +2,7 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.List; @@ -22,7 +23,7 @@ public CsvWriter() { try { out = new ByteArrayOutputStream(); csvFileFormat = CSVFormat.newFormat(DELIMITER).withRecordSeparator(RECORD_SEPARATOR).withQuote('\"').withQuoteMode(QuoteMode.MINIMAL); - csvFilePrinter = new CSVPrinter(new PrintWriter(out), csvFileFormat); + csvFilePrinter = new CSVPrinter(new PrintWriter(new OutputStreamWriter(out, "UTF-8")), csvFileFormat); } catch (IOException e) { e.printStackTrace(); } diff --git a/source/otus-file-uploader/pom.xml b/source/otus-file-uploader/pom.xml index 8e2910829..79d882ea6 100644 --- a/source/otus-file-uploader/pom.xml +++ b/source/otus-file-uploader/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-gateway/pom.xml b/source/otus-gateway/pom.xml index 99b99dd1c..9ac232fff 100644 --- a/source/otus-gateway/pom.xml +++ b/source/otus-gateway/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/gates/ExtractionGatewayService.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/gates/ExtractionGatewayService.java index 01295fcd8..81aef33cb 100644 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/gates/ExtractionGatewayService.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/gates/ExtractionGatewayService.java @@ -3,43 +3,89 @@ import br.org.otus.gateway.request.*; import br.org.otus.gateway.resource.ExtractionMicroServiceResources; import br.org.otus.gateway.response.GatewayResponse; +import br.org.otus.gateway.response.exception.NotFoundRequestException; import br.org.otus.gateway.response.exception.ReadRequestException; +import br.org.otus.gateway.response.exception.RequestException; import java.io.IOException; import java.net.URL; public class ExtractionGatewayService { - public GatewayResponse getPipelineExtraction(String pipelineName) throws IOException { - URL requestURL = new ExtractionMicroServiceResources().getPipelineExtractionAddress(pipelineName); - try { - String response = new JsonGETUtility(requestURL).finish(); - return new GatewayResponse().buildSuccess(response); - } catch (IOException e) { - throw new ReadRequestException(); - } + public void createOrUpdateActivityExtraction(String activityExtractionJson) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getActivityExtractionCreateAddress(); + sendRequest(new JsonPUTRequestUtility(requestURL, activityExtractionJson)); + } + + public void deleteActivityExtraction(String surveyId, String activityId) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getActivityExtractionDeleteAddress(surveyId, activityId); + sendRequest(new JsonDELETEUtility(requestURL)); + } + + public GatewayResponse getSurveyActivityIdsWithExtraction(String surveyId) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getSurveyActivityIdsWithExtractionAddress(surveyId); + return sendRequestAndGetResponse(new JsonGETUtility(requestURL)); + } + + public GatewayResponse getCsvSurveyExtraction(String surveyId) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getCsvSurveyExtractionAddress(surveyId); + return sendRequestAndGetResponse(new JsonGETUtility(requestURL)); + } + + public GatewayResponse getJsonSurveyExtraction(String surveyId) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getJsonSurveyExtractionAddress(surveyId); + return sendRequestAndGetResponse(new JsonGETUtility(requestURL)); + } + + public void createOrUpdateRscript(String rscriptJson) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getRScriptCreationAddress(); + sendRequest(new JsonPUTRequestUtility(requestURL, rscriptJson)); } - public void createActivityExtraction(String activityId) throws IOException { - URL requestURL = new ExtractionMicroServiceResources().getActivityExtractionCreateAddress(activityId); - sendActivityExtractionRequest(new JsonPOSTUtility(requestURL, "")); + public GatewayResponse getRscript(String rscriptName) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getRScriptGetterAddress(rscriptName); + return sendRequestAndGetResponse(new JsonGETUtility(requestURL)); } - public void updateActivityExtraction(String activityId) throws IOException { - URL requestURL = new ExtractionMicroServiceResources().getActivityExtractionUpdateAddress(activityId); - sendActivityExtractionRequest(new JsonPUTRequestUtility(requestURL)); + public void deleteRscript(String rscriptName) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getRScriptDeleteAddress(rscriptName); + sendRequest(new JsonDELETEUtility(requestURL)); } - public void deleteActivityExtraction(String activityId) throws IOException { - URL requestURL = new ExtractionMicroServiceResources().getActivityExtractionDeleteAddress(activityId); - sendActivityExtractionRequest(new JsonDELETEUtility(requestURL)); + public GatewayResponse getRscriptSurveyExtraction(String rscriptSurveyExtractionJson) throws IOException { + URL requestURL = new ExtractionMicroServiceResources().getRScriptJsonSurveyExtractionAddress(); + return sendRequestAndGetResponse(new JsonPOSTUtility(requestURL, rscriptSurveyExtractionJson)); } - private void sendActivityExtractionRequest(JsonRequestUtility jsonRequestUtility){ + + private void sendRequest(JsonRequestUtility jsonRequestUtility){ try { jsonRequestUtility.finish(); - } catch (IOException e) { - throw new ReadRequestException(); + } + catch(NotFoundRequestException e){ + throw e; + } + catch (RequestException e){ + throw new ReadRequestException(e.getErrorMessage(), e.getCause()); + } + catch (Exception e) { + throw new ReadRequestException(e.getMessage(), e.getCause()); + } + } + + private GatewayResponse sendRequestAndGetResponse(JsonRequestUtility jsonRequestUtility){ + try { + String response = jsonRequestUtility.finish(); + return new GatewayResponse().buildSuccess(response); + } + catch(NotFoundRequestException e){ + throw e; + } + catch (RequestException e){ + throw new ReadRequestException(e.getErrorMessage(), e.getCause()); + } + catch (Exception e) { + throw new ReadRequestException(e.getMessage(), e.getCause()); } } diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPOSTUtility.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPOSTUtility.java index 85385bbd4..0d708ff1c 100755 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPOSTUtility.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPOSTUtility.java @@ -7,8 +7,8 @@ public class JsonPOSTUtility extends JsonWritingRequestUtility { public JsonPOSTUtility(URL requestURL, String body) throws IOException { - super(RequestTypeOptions.POST, requestURL, "application/json"); + super(RequestTypeOptions.POST, requestURL, APPLICATION_JSON_CONTENT_TYPE); request.write(body.getBytes(StandardCharsets.UTF_8)); } -} +} \ No newline at end of file diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPUTRequestUtility.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPUTRequestUtility.java index 0906872ad..e8921eb56 100755 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPUTRequestUtility.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonPUTRequestUtility.java @@ -7,11 +7,16 @@ public class JsonPUTRequestUtility extends JsonWritingRequestUtility{ public JsonPUTRequestUtility(URL requestURL) throws IOException { - super(RequestTypeOptions.PUT, requestURL, "application/json"); + super(RequestTypeOptions.PUT, requestURL, APPLICATION_JSON_CONTENT_TYPE); + } + + public JsonPUTRequestUtility(URL requestURL, String body) throws IOException { + super(RequestTypeOptions.PUT, requestURL, APPLICATION_JSON_CONTENT_TYPE); + writeBody(body); } public void writeBody(String body) throws IOException { this.request.write(body.getBytes(StandardCharsets.UTF_8)); } -} +} \ No newline at end of file diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonRequestUtility.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonRequestUtility.java index 9fb7993f8..a4812a6d0 100644 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonRequestUtility.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonRequestUtility.java @@ -1,5 +1,6 @@ package br.org.otus.gateway.request; +import br.org.otus.gateway.response.exception.NotFoundRequestException; import br.org.otus.gateway.response.exception.RequestException; import java.io.IOException; @@ -21,9 +22,12 @@ public String finish() throws IOException, RequestException { if (status != HttpURLConnection.HTTP_OK) { String errorMessage = httpConn.getResponseMessage(); Object errorContent = RequestUtility.getErrorContent(httpConn); + if(status == HttpURLConnection.HTTP_NOT_FOUND){ + throw new NotFoundRequestException(errorMessage, errorContent); + } throw new RequestException(status, errorMessage, errorContent); } return RequestUtility.getString(httpConn); } -} +} \ No newline at end of file diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonWritingRequestUtility.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonWritingRequestUtility.java index 069c0e48e..747da6d82 100644 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonWritingRequestUtility.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/JsonWritingRequestUtility.java @@ -8,6 +8,8 @@ public abstract class JsonWritingRequestUtility extends JsonRequestUtility { + protected static final String APPLICATION_JSON_CONTENT_TYPE = "application/json"; + protected DataOutputStream request; public JsonWritingRequestUtility(RequestTypeOptions requestTypeOption, URL requestURL, String contentType) throws IOException { @@ -25,4 +27,4 @@ public String finish() throws IOException, RequestException { request.close(); return super.finish(); } -} +} \ No newline at end of file diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/RequestUtility.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/RequestUtility.java index da20a0fbc..ab7f1bd29 100755 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/request/RequestUtility.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/request/RequestUtility.java @@ -7,7 +7,9 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import com.google.gson.JsonSyntaxException; import org.bson.Document; import com.google.gson.GsonBuilder; @@ -16,6 +18,8 @@ public class RequestUtility { + private static final String EXPECTED_BEGIN_ARRAY_PREFIX_MESSAGE = "Expected BEGIN_ARRAY"; + public static String getString(HttpURLConnection httpConn) throws IOException { String response; InputStream responseStream = new BufferedInputStream(httpConn.getInputStream()); @@ -32,7 +36,16 @@ public static String getString(HttpURLConnection httpConn) throws IOException { response = stringBuilder.toString(); httpConn.disconnect(); - return new GsonBuilder().create().toJson(new GsonBuilder().create().fromJson(response, Document.class).get("data")); + + try{ + return new GsonBuilder().create().toJson(new GsonBuilder().create().fromJson(response, Document.class).get("data")); + } + catch (JsonSyntaxException e){ + if(!e.getMessage().contains(EXPECTED_BEGIN_ARRAY_PREFIX_MESSAGE)){ + throw e; + } + return new GsonBuilder().create().toJson(new GsonBuilder().create().fromJson(response, ArrayList.class)); + } } public static Object getErrorContent(HttpURLConnection httpConn) throws IOException { @@ -46,7 +59,12 @@ public static Object getErrorContent(HttpURLConnection httpConn) throws IOExcept in.close(); String responseString = response.toString(); - return new GsonBuilder().create().fromJson(responseString, Document.class).get("data"); + try{ + return new GsonBuilder().create().fromJson(responseString, Document.class).get("data"); + } + catch(Exception e){ + return responseString; + } } } diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/resource/ExtractionMicroServiceResources.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/resource/ExtractionMicroServiceResources.java index c6ddff19f..9b9a3c9bb 100644 --- a/source/otus-gateway/src/main/java/br/org/otus/gateway/resource/ExtractionMicroServiceResources.java +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/resource/ExtractionMicroServiceResources.java @@ -7,30 +7,55 @@ public class ExtractionMicroServiceResources extends MicroservicesResources { - private static final String PIPELINE_EXTRACTION_RESOURCE = "/pipeline/"; + private static final String EXTRACTION_SUFFIX = "/extractions"; + private static final String ACTIVITY_EXTRACTION_RESOURCE = EXTRACTION_SUFFIX + "/activity"; - private static final String EXTRACTION_SUFFIX = "/extraction/"; - private static final String EXTRACTION_CREATE_RESOURCE = EXTRACTION_SUFFIX + "create/"; - private static final String EXTRACTION_UPDATE_RESOURCE = EXTRACTION_SUFFIX + "update/"; - private static final String EXTRACTION_DELETE_RESOURCE = EXTRACTION_SUFFIX + "delete/"; + private static final String SURVEY_EXTRACTION_SUFFIX = "/survey"; + private static final String CSV_SURVEY_EXTRACTION_RESOURCE = SURVEY_EXTRACTION_SUFFIX + "/csv"; + private static final String JSON_SURVEY_EXTRACTION_RESOURCE = SURVEY_EXTRACTION_SUFFIX + "/json"; + private static final String RSCRIPT_SURVEY_EXTRACTION_RESOURCE = SURVEY_EXTRACTION_SUFFIX + "/rscript"; + private static final String SURVEY_ACTIVITIES_IDS_WITH_EXTRACTION_RESOURCE = SURVEY_EXTRACTION_SUFFIX + "/get-survey-activities-ids"; + + private static final String RSCRIPT_SUFFIX = "/rscript"; + private static final String RSCRIPT_CREATE_RESOURCE = RSCRIPT_SUFFIX + "/create"; public ExtractionMicroServiceResources() { super(MicroservicesEnvironments.EXTRACTION); } - public URL getPipelineExtractionAddress(String pipelineName) throws MalformedURLException { - return new URL(getMainAddress() + PIPELINE_EXTRACTION_RESOURCE + pipelineName); + public URL getActivityExtractionCreateAddress() throws MalformedURLException { + return new URL(getMainAddress() + ACTIVITY_EXTRACTION_RESOURCE); + } + + public URL getActivityExtractionDeleteAddress(String surveyId, String activityId) throws MalformedURLException { + return new URL(getMainAddress() + ACTIVITY_EXTRACTION_RESOURCE + "/" + surveyId + "/" + activityId); + } + + public URL getSurveyActivityIdsWithExtractionAddress(String surveyId) throws MalformedURLException { + return new URL(getMainAddress() + SURVEY_ACTIVITIES_IDS_WITH_EXTRACTION_RESOURCE + "/" + surveyId); + } + + public URL getCsvSurveyExtractionAddress(String surveyId) throws MalformedURLException { + return new URL(getMainAddress() + CSV_SURVEY_EXTRACTION_RESOURCE + "/" + surveyId); + } + + public URL getJsonSurveyExtractionAddress(String surveyId) throws MalformedURLException { + return new URL(getMainAddress() + JSON_SURVEY_EXTRACTION_RESOURCE + "/" + surveyId); + } + + public URL getRScriptCreationAddress() throws MalformedURLException { + return new URL(getMainAddress() + RSCRIPT_CREATE_RESOURCE); } - public URL getActivityExtractionCreateAddress(String activityId) throws MalformedURLException { - return new URL(getMainAddress() + EXTRACTION_CREATE_RESOURCE + activityId); + public URL getRScriptGetterAddress(String rscriptName) throws MalformedURLException { + return new URL(getMainAddress() + RSCRIPT_SUFFIX + "/" + rscriptName); } - public URL getActivityExtractionUpdateAddress(String activityId) throws MalformedURLException { - return new URL(getMainAddress() + EXTRACTION_UPDATE_RESOURCE + activityId); + public URL getRScriptDeleteAddress(String rscriptName) throws MalformedURLException { + return new URL(getMainAddress() + RSCRIPT_SUFFIX + "/" + rscriptName); } - public URL getActivityExtractionDeleteAddress(String activityId) throws MalformedURLException { - return new URL(getMainAddress() + EXTRACTION_DELETE_RESOURCE + activityId); + public URL getRScriptJsonSurveyExtractionAddress() throws MalformedURLException { + return new URL(getMainAddress() + RSCRIPT_SURVEY_EXTRACTION_RESOURCE); } } diff --git a/source/otus-gateway/src/main/java/br/org/otus/gateway/response/exception/NotFoundRequestException.java b/source/otus-gateway/src/main/java/br/org/otus/gateway/response/exception/NotFoundRequestException.java new file mode 100644 index 000000000..3c0c053fe --- /dev/null +++ b/source/otus-gateway/src/main/java/br/org/otus/gateway/response/exception/NotFoundRequestException.java @@ -0,0 +1,14 @@ +package br.org.otus.gateway.response.exception; + +public class NotFoundRequestException extends RequestException { + + private static final int STATUS = java.net.HttpURLConnection.HTTP_NOT_FOUND; + + public NotFoundRequestException() { + super(STATUS, "Not Found", null); + } + + public NotFoundRequestException(String errorMessage, Object errorContent) { + super(STATUS, errorMessage, errorContent); + } +} diff --git a/source/otus-gateway/src/test/java/br/org/otus/gateway/ExtractionGatewayServiceTest.java b/source/otus-gateway/src/test/java/br/org/otus/gateway/ExtractionGatewayServiceTest.java index dd0fad115..efcb33457 100644 --- a/source/otus-gateway/src/test/java/br/org/otus/gateway/ExtractionGatewayServiceTest.java +++ b/source/otus-gateway/src/test/java/br/org/otus/gateway/ExtractionGatewayServiceTest.java @@ -32,9 +32,13 @@ public class ExtractionGatewayServiceTest { private static final String HOST = "http://localhost:"; private static final String PORT = "53004"; - private static final String PIPELINE_NAME = "pipelineName"; - private static final String ACTIVITY_ID = "5e0658135b4ff40f8916d2b5"; + private static final String SURVEY_ID = "5e0658135b4ff40f8916d2b5"; + private static final String ACTIVITY_ID = "5e0658135b4ff40f8916d2b6"; + private static final String ACTIVITY_EXTRACTION_JSON = "{}"; + private static final String SURVEY_EXTRACTION_JSON = "{}"; private static final GatewayResponse EXPECTED_GATEWAY_RESPONSE = null; + private static final String R_SCRIPT_JSON = "{}"; + private static final String R_SCRIPT_NAME = "script"; @InjectMocks private ExtractionGatewayService extractionGatewayService; @@ -70,61 +74,126 @@ public void setUp() throws Exception { } @Test - public void getPipelineExtraction_method_should_return_GatewayResponse() throws IOException { - when(extractionMicroServiceResources.getPipelineExtractionAddress(PIPELINE_NAME)).thenReturn(requestURL); - assertEquals(EXPECTED_GATEWAY_RESPONSE, extractionGatewayService.getPipelineExtraction(PIPELINE_NAME)); + public void createActivityExtraction_method_should_send_POST_request() throws IOException { + when(extractionMicroServiceResources.getActivityExtractionCreateAddress()).thenReturn(requestURL); + extractionGatewayService.createOrUpdateActivityExtraction(ACTIVITY_EXTRACTION_JSON); + verify(jsonPUTUtility, Mockito.times(1)).finish(); } @Test(expected = ReadRequestException.class) - public void getPipelineExtraction_method_should_throw_ReadRequestException() throws IOException { - when(extractionMicroServiceResources.getPipelineExtractionAddress(PIPELINE_NAME)).thenReturn(requestURL); - when(jsonGETUtility.finish()).thenThrow(new IOException()); - extractionGatewayService.getPipelineExtraction(PIPELINE_NAME); + public void createActivityExtraction_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getActivityExtractionCreateAddress()).thenReturn(requestURL); + when(jsonPUTUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.createOrUpdateActivityExtraction(ACTIVITY_EXTRACTION_JSON); + } + + @Test + public void deleteActivityExtraction_method_should_send_POST_request() throws IOException { + when(extractionMicroServiceResources.getActivityExtractionDeleteAddress(SURVEY_ID, ACTIVITY_ID)).thenReturn(requestURL); + extractionGatewayService.deleteActivityExtraction(SURVEY_ID, ACTIVITY_ID); + verify(jsonDELETEUtility, Mockito.times(1)).finish(); } + @Test(expected = ReadRequestException.class) + public void deleteActivityExtraction_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getActivityExtractionDeleteAddress(SURVEY_ID, ACTIVITY_ID)).thenReturn(requestURL); + when(jsonDELETEUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.deleteActivityExtraction(SURVEY_ID, ACTIVITY_ID); + } @Test - public void createActivityExtraction_method_should_send_POST_request() throws IOException { - when(extractionMicroServiceResources.getActivityExtractionCreateAddress(ACTIVITY_ID)).thenReturn(requestURL); - extractionGatewayService.createActivityExtraction(ACTIVITY_ID); - verify(jsonPOSTUtility, Mockito.times(1)).finish(); + public void getSurveyActivityIdsWithExtraction_method_should_send_POST_request() throws IOException { + when(extractionMicroServiceResources.getSurveyActivityIdsWithExtractionAddress(SURVEY_ID)).thenReturn(requestURL); + extractionGatewayService.getSurveyActivityIdsWithExtraction(SURVEY_ID); + verify(jsonGETUtility, Mockito.times(1)).finish(); } @Test(expected = ReadRequestException.class) - public void createActivityExtraction_method_should_throw_ReadRequestException() throws IOException { - when(extractionMicroServiceResources.getActivityExtractionCreateAddress(ACTIVITY_ID)).thenReturn(requestURL); - when(jsonPOSTUtility.finish()).thenThrow(new IOException()); - extractionGatewayService.createActivityExtraction(ACTIVITY_ID); + public void getSurveyActivityIdsWithExtraction_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getSurveyActivityIdsWithExtractionAddress(SURVEY_ID)).thenReturn(requestURL); + when(jsonGETUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.getSurveyActivityIdsWithExtraction(SURVEY_ID); } + @Test + public void getCsvSurveyExtraction_method_should_return_GatewayResponse() throws IOException { + when(extractionMicroServiceResources.getCsvSurveyExtractionAddress(SURVEY_ID)).thenReturn(requestURL); + assertEquals(EXPECTED_GATEWAY_RESPONSE, extractionGatewayService.getCsvSurveyExtraction(SURVEY_ID)); + } + + @Test(expected = ReadRequestException.class) + public void getCsvSurveyExtraction_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getCsvSurveyExtractionAddress(SURVEY_ID)).thenReturn(requestURL); + when(jsonGETUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.getCsvSurveyExtraction(SURVEY_ID); + } @Test - public void updateActivityExtraction_method_should_send_POST_request() throws IOException { - when(extractionMicroServiceResources.getActivityExtractionUpdateAddress(ACTIVITY_ID)).thenReturn(requestURL); - extractionGatewayService.updateActivityExtraction(ACTIVITY_ID); + public void getJsonSurveyExtractionAddress_method_should_return_GatewayResponse() throws IOException { + when(extractionMicroServiceResources.getJsonSurveyExtractionAddress(SURVEY_ID)).thenReturn(requestURL); + assertEquals(EXPECTED_GATEWAY_RESPONSE, extractionGatewayService.getJsonSurveyExtraction(SURVEY_ID)); + } + + @Test(expected = ReadRequestException.class) + public void getJsonSurveyExtractionAddress_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getJsonSurveyExtractionAddress(SURVEY_ID)).thenReturn(requestURL); + when(jsonGETUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.getJsonSurveyExtraction(SURVEY_ID); + } + + @Test + public void createOrUpdateRscript_method_should_send_PUT_request() throws IOException { + when(extractionMicroServiceResources.getRScriptCreationAddress()).thenReturn(requestURL); + extractionGatewayService.createOrUpdateRscript(R_SCRIPT_JSON); verify(jsonPUTUtility, Mockito.times(1)).finish(); } @Test(expected = ReadRequestException.class) - public void updateActivityExtraction_method_should_throw_ReadRequestException() throws IOException { - when(extractionMicroServiceResources.getActivityExtractionUpdateAddress(ACTIVITY_ID)).thenReturn(requestURL); + public void createOrUpdateRscript_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getRScriptCreationAddress()).thenReturn(requestURL); when(jsonPUTUtility.finish()).thenThrow(new IOException()); - extractionGatewayService.updateActivityExtraction(ACTIVITY_ID); + extractionGatewayService.createOrUpdateRscript(R_SCRIPT_JSON); } + @Test + public void getRscript_method_should_return_GatewayResponse() throws IOException { + when(extractionMicroServiceResources.getRScriptGetterAddress(R_SCRIPT_NAME)).thenReturn(requestURL); + assertEquals(EXPECTED_GATEWAY_RESPONSE, extractionGatewayService.getRscript(R_SCRIPT_NAME)); + } + + @Test(expected = ReadRequestException.class) + public void getRscript_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getRScriptGetterAddress(R_SCRIPT_NAME)).thenReturn(requestURL); + when(jsonGETUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.getRscript(R_SCRIPT_NAME); + } @Test - public void deleteActivityExtraction_method_should_send_POST_request() throws IOException { - when(extractionMicroServiceResources.getActivityExtractionDeleteAddress(ACTIVITY_ID)).thenReturn(requestURL); - extractionGatewayService.deleteActivityExtraction(ACTIVITY_ID); + public void deleteRscript_method_should_send_DELETE_request() throws IOException { + when(extractionMicroServiceResources.getRScriptDeleteAddress(R_SCRIPT_NAME)).thenReturn(requestURL); + extractionGatewayService.deleteRscript(R_SCRIPT_NAME); verify(jsonDELETEUtility, Mockito.times(1)).finish(); } @Test(expected = ReadRequestException.class) - public void deleteActivityExtraction_method_should_throw_ReadRequestException() throws IOException { - when(extractionMicroServiceResources.getActivityExtractionDeleteAddress(ACTIVITY_ID)).thenReturn(requestURL); + public void deleteRscript_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getRScriptDeleteAddress(R_SCRIPT_NAME)).thenReturn(requestURL); when(jsonDELETEUtility.finish()).thenThrow(new IOException()); - extractionGatewayService.deleteActivityExtraction(ACTIVITY_ID); + extractionGatewayService.deleteRscript(R_SCRIPT_NAME); + } + + + @Test + public void getRscriptSurveyExtraction_method_should_return_GatewayResponse() throws IOException { + when(extractionMicroServiceResources.getRScriptJsonSurveyExtractionAddress()).thenReturn(requestURL); + assertEquals(EXPECTED_GATEWAY_RESPONSE, extractionGatewayService.getRscriptSurveyExtraction(SURVEY_EXTRACTION_JSON)); + } + + @Test(expected = ReadRequestException.class) + public void getRscriptSurveyExtraction_method_should_throw_ReadRequestException() throws IOException { + when(extractionMicroServiceResources.getRScriptJsonSurveyExtractionAddress()).thenReturn(requestURL); + when(jsonPOSTUtility.finish()).thenThrow(new IOException()); + extractionGatewayService.getRscriptSurveyExtraction(SURVEY_EXTRACTION_JSON); } } diff --git a/source/otus-gateway/src/test/java/br/org/otus/gateway/resource/ExtractionMicroServiceResourcesTest.java b/source/otus-gateway/src/test/java/br/org/otus/gateway/resource/ExtractionMicroServiceResourcesTest.java index 3af8e2985..1fb6cae7c 100644 --- a/source/otus-gateway/src/test/java/br/org/otus/gateway/resource/ExtractionMicroServiceResourcesTest.java +++ b/source/otus-gateway/src/test/java/br/org/otus/gateway/resource/ExtractionMicroServiceResourcesTest.java @@ -15,7 +15,9 @@ @PrepareForTest({ExtractionMicroServiceResources.class}) public class ExtractionMicroServiceResourcesTest extends MicroServiceResourcesTestParent { - private static final String PIPELINE_NAME = "pipelineName"; + private static final String SURVEY_ID = "123"; + private static final String ACTIVITY_ID = "4567"; + private static final String R_SCRIPT_NAME = "script"; private ExtractionMicroServiceResources resources; @@ -26,9 +28,77 @@ public void setUp() throws Exception { } @Test - public void getCreateOutcomeAddress_method_should_return_expected_url() throws MalformedURLException { - url = new URL("http://" + HOST + ":" + PORT + "/pipeline/" + PIPELINE_NAME); - Assert.assertEquals(url, resources.getPipelineExtractionAddress(PIPELINE_NAME)); + public void getActivityExtractionCreateAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/extractions/activity"), + resources.getActivityExtractionCreateAddress() + ); + } + + @Test + public void getActivityExtractionDeleteAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/extractions/activity/" + SURVEY_ID + "/" + ACTIVITY_ID), + resources.getActivityExtractionDeleteAddress(SURVEY_ID, ACTIVITY_ID) + ); + } + + @Test + public void getSurveyActivityIdsWithExtractionAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/survey/get-survey-activities-ids/" + SURVEY_ID), + resources.getSurveyActivityIdsWithExtractionAddress(SURVEY_ID) + ); + } + + @Test + public void getCsvSurveyExtractionAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/survey/csv/" + SURVEY_ID), + resources.getCsvSurveyExtractionAddress(SURVEY_ID) + ); + } + + @Test + public void getJsonSurveyExtractionAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/survey/json/" + SURVEY_ID), + resources.getJsonSurveyExtractionAddress(SURVEY_ID) + ); + } + + + @Test + public void getRScriptCreationAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/rscript/create"), + resources.getRScriptCreationAddress() + ); + } + + @Test + public void getRScriptGetterAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/rscript/" + R_SCRIPT_NAME), + resources.getRScriptGetterAddress(R_SCRIPT_NAME) + ); + } + + @Test + public void getRScriptDeleteAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/rscript/" + R_SCRIPT_NAME), + resources.getRScriptDeleteAddress(R_SCRIPT_NAME) + ); + } + + + @Test + public void getRScriptJsonSurveyExtractionAddress_method_should_return_expected_url() throws MalformedURLException { + Assert.assertEquals( + new URL("http://" + HOST + ":" + PORT + "/survey/rscript"), + resources.getRScriptJsonSurveyExtractionAddress() + ); } } diff --git a/source/otus-import/pom.xml b/source/otus-import/pom.xml index 9836481ec..949dcae2a 100644 --- a/source/otus-import/pom.xml +++ b/source/otus-import/pom.xml @@ -4,7 +4,7 @@ otus-root org.ccem.otus - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml 4.0.0 diff --git a/source/otus-laboratory/pom.xml b/source/otus-laboratory/pom.xml index cdd71e575..3dcedd05e 100644 --- a/source/otus-laboratory/pom.xml +++ b/source/otus-laboratory/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/enums/LaboratoryExtractionHeaders.java b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/enums/LaboratoryExtractionHeaders.java index badb30ccf..7d4a5384b 100644 --- a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/enums/LaboratoryExtractionHeaders.java +++ b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/enums/LaboratoryExtractionHeaders.java @@ -15,7 +15,10 @@ public enum LaboratoryExtractionHeaders { ALIQUOT_CONTAINER("aliquot_container"), ALIQUOT_PROCESSING_DATE("aliquot_processing_date"), ALIQUOT_REGISTER_DATE("aliquot_register_date"), - ALIQUOT_RESPONSIBLE("aliquot_responsible"); + ALIQUOT_RESPONSIBLE("aliquot_responsible"), + ALIQUOT_ROLE("aliquot_role"), + ALIQUOT_HAS_TRANSPORTATION_LOT_ID("has_transportation_lot_id"), + ALIQUOT_HAS_EXAM_LOT_ID("has_exam_lot_id"); private final String value; diff --git a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactory.java b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactory.java index 9a2c3676e..a47456e2a 100644 --- a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactory.java +++ b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactory.java @@ -35,6 +35,9 @@ private void buildHeader() { this.headers.add(LaboratoryExtractionHeaders.ALIQUOT_PROCESSING_DATE.getValue()); this.headers.add(LaboratoryExtractionHeaders.ALIQUOT_REGISTER_DATE.getValue()); this.headers.add(LaboratoryExtractionHeaders.ALIQUOT_RESPONSIBLE.getValue()); + this.headers.add(LaboratoryExtractionHeaders.ALIQUOT_ROLE.getValue()); + this.headers.add(LaboratoryExtractionHeaders.ALIQUOT_HAS_TRANSPORTATION_LOT_ID.getValue()); + this.headers.add(LaboratoryExtractionHeaders.ALIQUOT_HAS_EXAM_LOT_ID.getValue()); } } diff --git a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactory.java b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactory.java index 10dbcb074..4636ec196 100644 --- a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactory.java +++ b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactory.java @@ -55,6 +55,9 @@ public void buildResultInformation() { answers.add(result.getAliquotProcessingDate()); answers.add(result.getAliquotRegisterDate()); answers.add(result.getAliquotResponsible()); + answers.add(result.getAliquotRole()); + answers.add(result.getHasTransportationLotId().toString()); + answers.add(result.getHasExamLotId().toString()); this.outputRecords.add(new ArrayList<>(answers)); }); diff --git a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/model/LaboratoryResultExtraction.java b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/model/LaboratoryResultExtraction.java index 90496c620..44001e513 100644 --- a/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/model/LaboratoryResultExtraction.java +++ b/source/otus-laboratory/src/main/java/br/org/otus/laboratory/extraction/model/LaboratoryResultExtraction.java @@ -18,6 +18,9 @@ public class LaboratoryResultExtraction { private String aliquotProcessingDate; private String aliquotRegisterDate; private String aliquotResponsible; + private String aliquotRole; + private Boolean hasTransportationLotId; + private Boolean hasExamLotId; public Long getRecruitmentNumber() { return recruitmentNumber; @@ -74,4 +77,20 @@ public String getAliquotResponsible() { public Integer getUnattachedLaboratoryId() { return unattachedLaboratoryId; } + + public String getAliquotRole() { return aliquotRole; } + + public Boolean getHasTransportationLotId() { + if(hasTransportationLotId == null){ + return false; + } + return hasTransportationLotId; + } + + public Boolean getHasExamLotId() { + if(hasExamLotId == null){ + return false; + } + return hasExamLotId; + } } diff --git a/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactoryTest.java b/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactoryTest.java index b6c4a0805..93acbe5c9 100644 --- a/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactoryTest.java +++ b/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionHeadersFactoryTest.java @@ -1,13 +1,11 @@ package br.org.otus.laboratory.extraction.factories; -import java.util.LinkedHashSet; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; @@ -19,13 +17,10 @@ public class LaboratoryExtractionHeadersFactoryTest { @InjectMocks private LaboratoryExtractionHeadersFactory laboratoryExtractionHeadersFactory; - @Mock - private LinkedHashSet headers; @Test public void construction_method_should_call_buildHeader_method() throws Exception { LaboratoryExtractionHeadersFactory spy = PowerMockito.spy(new LaboratoryExtractionHeadersFactory()); - PowerMockito.verifyPrivate(spy, Mockito.times(1)).invoke("buildHeader"); } @@ -47,6 +42,9 @@ public void getHeaders_method_should_return_list_with_information_headers() { Assert.assertTrue(headers.contains(LaboratoryExtractionHeaders.ALIQUOT_PROCESSING_DATE.getValue())); Assert.assertTrue(headers.contains(LaboratoryExtractionHeaders.ALIQUOT_REGISTER_DATE.getValue())); Assert.assertTrue(headers.contains(LaboratoryExtractionHeaders.ALIQUOT_RESPONSIBLE.getValue())); + Assert.assertTrue(headers.contains(LaboratoryExtractionHeaders.ALIQUOT_ROLE.getValue())); + Assert.assertTrue(headers.contains(LaboratoryExtractionHeaders.ALIQUOT_HAS_TRANSPORTATION_LOT_ID.getValue())); + Assert.assertTrue(headers.contains(LaboratoryExtractionHeaders.ALIQUOT_HAS_EXAM_LOT_ID.getValue())); } @Test @@ -68,6 +66,9 @@ public void getHeaders_method_should_return_list_with_expected_order() { Assert.assertEquals(LaboratoryExtractionHeaders.ALIQUOT_PROCESSING_DATE.getValue(), headers.get(11)); Assert.assertEquals(LaboratoryExtractionHeaders.ALIQUOT_REGISTER_DATE.getValue(), headers.get(12)); Assert.assertEquals(LaboratoryExtractionHeaders.ALIQUOT_RESPONSIBLE.getValue(), headers.get(13)); + Assert.assertEquals(LaboratoryExtractionHeaders.ALIQUOT_ROLE.getValue(), headers.get(14)); + Assert.assertEquals(LaboratoryExtractionHeaders.ALIQUOT_HAS_TRANSPORTATION_LOT_ID.getValue(), headers.get(15)); + Assert.assertEquals(LaboratoryExtractionHeaders.ALIQUOT_HAS_EXAM_LOT_ID.getValue(), headers.get(16)); } } diff --git a/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactoryTest.java b/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactoryTest.java index 28a7eb7cc..e22fb53b6 100644 --- a/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactoryTest.java +++ b/source/otus-laboratory/src/test/java/br/org/otus/laboratory/extraction/factories/LaboratoryExtractionRecordsFactoryTest.java @@ -27,6 +27,9 @@ public class LaboratoryExtractionRecordsFactoryTest { private static final String ALIQUOT_PROCESSING_DATE = "2018-05-22T18:54:09.189Z"; private static final String ALIQUOT_REGISTER_DATE = "2018-05-22T18:55:06.028Z"; private static final String ALIQUOT_RESPONSIBLE = "diogo.rosas.ferreira@gmail.com"; + private static final String ALIQUOT_ROLE = "EXAM"; + private static final Boolean ALIQUOT_HAS_TRANSPORTATION_LOT_ID = true; + private static final Boolean ALIQUOT_HAS_EXAM_LOT_ID = false; private LinkedList records; private LaboratoryExtractionRecordsFactory laboratoryExtractionRecordsFactory; @@ -67,6 +70,9 @@ public void getRecords_method_should_return_list_with_expected_values() { Assert.assertTrue(results.contains(ALIQUOT_PROCESSING_DATE)); Assert.assertTrue(results.contains(ALIQUOT_REGISTER_DATE)); Assert.assertTrue(results.contains(ALIQUOT_RESPONSIBLE)); + Assert.assertTrue(results.contains(ALIQUOT_ROLE)); + Assert.assertTrue(results.contains(ALIQUOT_HAS_TRANSPORTATION_LOT_ID.toString())); + Assert.assertTrue(results.contains(ALIQUOT_HAS_EXAM_LOT_ID.toString())); } @Test @@ -90,6 +96,9 @@ public void getRecords_method_should_return_list_with_expected_values_in_order() Assert.assertEquals(ALIQUOT_PROCESSING_DATE, results.get(11)); Assert.assertEquals(ALIQUOT_REGISTER_DATE, results.get(12)); Assert.assertEquals(ALIQUOT_RESPONSIBLE, results.get(13)); + Assert.assertEquals(ALIQUOT_ROLE, results.get(14)); + Assert.assertEquals(ALIQUOT_HAS_TRANSPORTATION_LOT_ID.toString(), results.get(15)); + Assert.assertEquals(ALIQUOT_HAS_EXAM_LOT_ID.toString(), results.get(16)); } private LaboratoryRecordExtraction createFakeLaboratoryRecordExtraction() { @@ -110,6 +119,9 @@ private LaboratoryRecordExtraction createFakeLaboratoryRecordExtraction() { Whitebox.setInternalState(result, "aliquotProcessingDate", ALIQUOT_PROCESSING_DATE); Whitebox.setInternalState(result, "aliquotRegisterDate", ALIQUOT_REGISTER_DATE); Whitebox.setInternalState(result, "aliquotResponsible", ALIQUOT_RESPONSIBLE); + Whitebox.setInternalState(result, "aliquotRole", ALIQUOT_ROLE); + Whitebox.setInternalState(result, "hasTransportationLotId", ALIQUOT_HAS_TRANSPORTATION_LOT_ID); + Whitebox.setInternalState(result, "hasExamLotId", ALIQUOT_HAS_EXAM_LOT_ID); results.add(result); diff --git a/source/otus-logs/pom.xml b/source/otus-logs/pom.xml index aa9a32ede..f9b4c04ed 100644 --- a/source/otus-logs/pom.xml +++ b/source/otus-logs/pom.xml @@ -4,7 +4,7 @@ otus-root org.ccem.otus - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml 4.0.0 diff --git a/source/otus-participant/pom.xml b/source/otus-participant/pom.xml index 1c085d18f..c9d7cfc37 100644 --- a/source/otus-participant/pom.xml +++ b/source/otus-participant/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml @@ -69,11 +69,11 @@ provided ejb - - org.ccem.otus - otus-extraction - 1.52.0-SNAPSHOT - compile - + + org.ccem.otus + otus-extraction + ${project.parent.version} + provided + diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/builder/ParticipantQueryBuilder.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/builder/ParticipantQueryBuilder.java index 4c7722648..b79f0bf75 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/builder/ParticipantQueryBuilder.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/builder/ParticipantQueryBuilder.java @@ -69,6 +69,7 @@ public ParticipantQueryBuilder projectionStructureParticipantContact() { " endereco_principal_cidade:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.main.value.city\",0]}, \"\" ] }," + " endereco_principal_uf:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.main.value.state\",0]}, \"\" ] }," + " endereco_principal_pais:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.main.value.country\",0]}, \"\" ] }," + + " endereco_principal_setor_censitario:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.main.value.census\",0]}, \"\" ] }," + " endereco_principal_observacao:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.main.observation\",0]}, \"\" ] }," + " segundo_endereco_cep:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.value.postalCode\",0]}, \"\" ] }," + " segundo_endereco_rua:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.value.street\",0]}, \"\" ] }," + @@ -78,6 +79,7 @@ public ParticipantQueryBuilder projectionStructureParticipantContact() { " segundo_endereco_cidade:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.value.city\",0]}, \"\" ] }," + " segundo_endereco_uf:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.value.state\",0]}, \"\" ] }," + " segundo_endereco_pais:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.value.country\",0]}, \"\" ] }," + + " segundo_endereco_setor_censitario:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.value.census\",0]}, \"\" ] }," + " segundo_endereco_observacao:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.second.observation\",0]}, \"\" ] }," + " terceiro_endereco_cep:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.value.postalCode\",0]}, \"\" ] }," + " terceiro_endereco_rua:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.value.street\",0]}, \"\" ] }," + @@ -87,6 +89,7 @@ public ParticipantQueryBuilder projectionStructureParticipantContact() { " terceiro_endereco_cidade:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.value.city\",0]}, \"\" ] }," + " terceiro_endereco_uf:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.value.state\",0]}, \"\" ] }," + " terceiro_endereco_pais:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.value.country\",0]}, \"\" ] }," + + " terceiro_endereco_setor_censitario:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.value.census\",0]}, \"\" ] }," + " terceiro_endereco_observacao:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.third.observation\",0]}, \"\" ] }," + " quarto_endereco_cep:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.value.postalCode\",0]}, \"\" ] }," + " quarto_endereco_rua:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.value.street\",0]}, \"\" ] }," + @@ -96,6 +99,7 @@ public ParticipantQueryBuilder projectionStructureParticipantContact() { " quarto_endereco_cidade:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.value.city\",0]}, \"\" ] }," + " quarto_endereco_uf:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.value.state\",0]}, \"\" ] }," + " quarto_endereco_pais:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.value.country\",0]}, \"\" ] }," + + " quarto_endereco_setor_censitario:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.value.census\",0]}, \"\" ] }," + " quarto_endereco_observacao:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fourth.observation\",0]}, \"\" ] }," + " quinto_endereco_cep:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.value.postalCode\",0]}, \"\" ] }," + " quinto_endereco_rua:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.value.street\",0]}, \"\" ] }," + @@ -105,6 +109,7 @@ public ParticipantQueryBuilder projectionStructureParticipantContact() { " quinto_endereco_cidade:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.value.city\",0]}, \"\" ] }," + " quinto_endereco_uf:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.value.state\",0]}, \"\" ] }," + " quinto_endereco_pais:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.value.country\",0]}, \"\" ] }," + + " quinto_endereco_setor_censitario:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.value.census\",0]}, \"\" ] }," + " quinto_endereco_observacao:{ $ifNull: [ {$arrayElemAt:[\"$CT.address.fifth.observation\",0]}, \"\" ] }" + " }" + " }")); @@ -153,6 +158,7 @@ public ParticipantQueryBuilder groupParticipantContactInLines() { " \"mainAddressCity\": \"$endereco_principal_cidade\",\n" + " \"mainAddressUf\": \"$endereco_principal_uf\",\n" + " \"mainAddressCountry\": \"$endereco_principal_pais\",\n" + + " \"mainAddressCensus\": \"$endereco_principal_setor_censitario\",\n" + " \"mainAddressObservation\": \"$endereco_principal_observacao\",\n" + " \"secondAddressCep\": \"$segundo_endereco_cep\",\n" + " \"secondAddressStreet\": \"$segundo_endereco_rua\",\n" + @@ -162,6 +168,7 @@ public ParticipantQueryBuilder groupParticipantContactInLines() { " \"secondAddressCity\": \"$segundo_endereco_cidade\",\n" + " \"secondAddressUf\": \"$segundo_endereco_uf\",\n" + " \"secondAddressCountry\": \"$segundo_endereco_pais\",\n" + + " \"secondAddressCensus\": \"$segundo_endereco_setor_censitario\",\n" + " \"secondAddressObservation\": \"$segundo_endereco_observacao\",\n" + " \"thirdAddressCep\": \"$terceiro_endereco_cep\",\n" + " \"thirdAddressStreet\": \"$terceiro_endereco_rua\",\n" + @@ -171,6 +178,7 @@ public ParticipantQueryBuilder groupParticipantContactInLines() { " \"thirdAddressCity\": \"$terceiro_endereco_cidade\",\n" + " \"thirdAddressUf\": \"$terceiro_endereco_uf\",\n" + " \"thirdAddressCountry\":\"$terceiro_endereco_pais\",\n" + + " \"thirdAddressCensus\":\"$terceiro_endereco_setor_censitario\",\n" + " \"thirdAddressObservation\":\"$terceiro_endereco_observacao\",\n" + " \"fourthAddressCep\":\"$quarto_endereco_cep\",\n" + " \"fourthAddressStreet\":\"$quarto_endereco_rua\",\n" + @@ -180,6 +188,7 @@ public ParticipantQueryBuilder groupParticipantContactInLines() { " \"fourthAddressCity\":\"$quarto_endereco_cidade\",\n" + " \"fourthAddressUf\":\"$quarto_endereco_uf\",\n" + " \"fourthAddressCountry\":\"$quarto_endereco_pais\",\n" + + " \"fourthAddressCensus\":\"$quarto_endereco_setor_censitario\",\n" + " \"fourthAddressObservation\":\"$quarto_endereco_observacao\",\n" + " \"fifthAddressCep\": \"$quinto_endereco_cep\",\n" + " \"fifthAddressStreet\": \"$quinto_endereco_rua\",\n" + @@ -189,6 +198,7 @@ public ParticipantQueryBuilder groupParticipantContactInLines() { " \"fifthAddressCity\": \"$quinto_endereco_cidade\",\n" + " \"fifthAddressUf\": \"$quinto_endereco_uf\",\n" + " \"fifthAddressCountry\": \"$quinto_endereco_pais\",\n" + + " \"fifthAddressCensus\": \"$quinto_endereco_setor_censitario\",\n" + " \"fifthAddressObservation\": \"$quinto_endereco_observacao\"\n" + " }\n" + " }\n" + diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/enums/ParticipantExtractionHeaders.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/enums/ParticipantExtractionHeaders.java index 206646b60..26d21730b 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/enums/ParticipantExtractionHeaders.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/enums/ParticipantExtractionHeaders.java @@ -37,6 +37,7 @@ public enum ParticipantExtractionHeaders { MAIN_ADDRESS_CITY("endereco_principal_cidade"), MAIN_ADDRESS_UF("endereco_principal_uf"), MAIN_ADDRESS_COUNTRY("endereco_principal_pais"), + MAIN_ADDRESS_CENSUS("endereco_principal_setor_censitario"), MAIN_ADDRESS_OBSERVATION("endereco_principal_observacao"), SECOND_ADDRESS_CEP("segundo_endereco_cep"), SECOND_ADDRESS_STREET("segundo_endereco_rua"), @@ -46,6 +47,7 @@ public enum ParticipantExtractionHeaders { SECOND_ADDRESS_CITY("segundo_endereco_cidade"), SECOND_ADDRESS_UF("segundo_endereco_uf"), SECOND_ADDRESS_COUNTRY("segundo_endereco_pais"), + SECOND_ADDRESS_CENSUS("segundo_endereco_setor_censitario"), SECOND_ADDRESS_OBSERVATION("segundo_endereco_observacao"), THIRD_ADDRESS_CEP("terceiro_endereco_cep"), THIRD_ADDRESS_STREET("terceiro_endereco_rua"), @@ -55,6 +57,7 @@ public enum ParticipantExtractionHeaders { THIRD_ADDRESS_CITY("terceiro_endereco_cidade"), THIRD_ADDRESS_UF("terceiro_endereco_uf"), THIRD_ADDRESS_COUNTRY("terceiro_endereco_pais"), + THIRD_ADDRESS_CENSUS("terceiro_endereco_setor_censitario"), THIRD_ADDRESS_OBSERVATION("terceiro_endereco_observacao"), FOURTH_ADDRESS_CEP("quarto_endereco_cep"), FOURTH_ADDRESS_STREET("quarto_endereco_rua"), @@ -64,6 +67,7 @@ public enum ParticipantExtractionHeaders { FOURTH_ADDRESS_CITY("quarto_endereco_cidade"), FOURTH_ADDRESS_UF("quarto_endereco_uf"), FOURTH_ADDRESS_COUNTRY("quarto_endereco_pais"), + FOURTH_ADDRESS_CENSUS("quarto_endereco_setor_censitario"), FOURTH_ADDRESS_OBSERVATION("quarto_endereco_observacao"), FIFTH_ADDRESS_CEP("quinto_endereco_cep"), FIFTH_ADDRESS_STREET("quinto_endereco_rua"), @@ -73,6 +77,7 @@ public enum ParticipantExtractionHeaders { FIFTH_ADDRESS_CITY("quinto_endereco_cidade"), FIFTH_ADDRESS_UF("quinto_endereco_uf"), FIFTH_ADDRESS_COUNTRY("quinto_endereco_pais"), + FIFTH_ADDRESS_CENSUS("quinto_endereco_setor_censitario"), FIFTH_ADDRESS_OBSERVATION("quinto_endereco_observacao"); private final String value; diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionHeadersFactory.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionHeadersFactory.java index 307589b4c..2f820148e 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionHeadersFactory.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionHeadersFactory.java @@ -54,6 +54,7 @@ private void buildHeader() { this.headers.add(ParticipantExtractionHeaders.MAIN_ADDRESS_CITY.getValue()); this.headers.add(ParticipantExtractionHeaders.MAIN_ADDRESS_UF.getValue()); this.headers.add(ParticipantExtractionHeaders.MAIN_ADDRESS_COUNTRY.getValue()); + this.headers.add(ParticipantExtractionHeaders.MAIN_ADDRESS_CENSUS.getValue()); this.headers.add(ParticipantExtractionHeaders.MAIN_ADDRESS_OBSERVATION.getValue()); this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_CEP.getValue()); this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_STREET.getValue()); @@ -63,6 +64,7 @@ private void buildHeader() { this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_CITY.getValue()); this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_UF.getValue()); this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_COUNTRY.getValue()); + this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_CENSUS.getValue()); this.headers.add(ParticipantExtractionHeaders.SECOND_ADDRESS_OBSERVATION.getValue()); this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_CEP.getValue()); this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_STREET.getValue()); @@ -72,6 +74,7 @@ private void buildHeader() { this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_CITY.getValue()); this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_UF.getValue()); this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_COUNTRY.getValue()); + this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_CENSUS.getValue()); this.headers.add(ParticipantExtractionHeaders.THIRD_ADDRESS_OBSERVATION.getValue()); this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_CEP.getValue()); this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_STREET.getValue()); @@ -81,6 +84,7 @@ private void buildHeader() { this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_CITY.getValue()); this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_UF.getValue()); this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_COUNTRY.getValue()); + this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_CENSUS.getValue()); this.headers.add(ParticipantExtractionHeaders.FOURTH_ADDRESS_OBSERVATION.getValue()); this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_CEP.getValue()); this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_STREET.getValue()); @@ -90,6 +94,7 @@ private void buildHeader() { this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_CITY.getValue()); this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_UF.getValue()); this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_COUNTRY.getValue()); + this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_CENSUS.getValue()); this.headers.add(ParticipantExtractionHeaders.FIFTH_ADDRESS_OBSERVATION.getValue()); } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionRecordsFactory.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionRecordsFactory.java index 5fc4bc1ab..ce50aac85 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionRecordsFactory.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/factories/ParticipantExtractionRecordsFactory.java @@ -64,6 +64,7 @@ private List createRecordsAnswers(ParticipantResultExtraction record) { answers.add(record.getMainAddressCity()); answers.add(record.getMainAddressUf()); answers.add(record.getMainAddressCountry()); + answers.add(record.getMainAddressCensus()); answers.add(record.getMainAddressObservation()); answers.add(record.getSecondAddressCep()); answers.add(record.getSecondAddressStreet()); @@ -73,6 +74,7 @@ private List createRecordsAnswers(ParticipantResultExtraction record) { answers.add(record.getSecondAddressCity()); answers.add(record.getSecondAddressUf()); answers.add(record.getSecondAddressCountry()); + answers.add(record.getSecondAddressCensus()); answers.add(record.getSecondAddressObservation()); answers.add(record.getThirdAddressCep()); answers.add(record.getThirdAddressStreet()); @@ -82,6 +84,7 @@ private List createRecordsAnswers(ParticipantResultExtraction record) { answers.add(record.getThirdAddressCity()); answers.add(record.getThirdAddressUf()); answers.add(record.getThirdAddressCountry()); + answers.add(record.getThirdAddressCensus()); answers.add(record.getThirdAddressObservation()); answers.add(record.getFourthAddressCep()); answers.add(record.getFourthAddressStreet()); @@ -91,6 +94,7 @@ private List createRecordsAnswers(ParticipantResultExtraction record) { answers.add(record.getFourthAddressCity()); answers.add(record.getFourthAddressUf()); answers.add(record.getFourthAddressCountry()); + answers.add(record.getFourthAddressCensus()); answers.add(record.getFourthAddressObservation()); answers.add(record.getFifthAddressCep()); answers.add(record.getFifthAddressStreet()); @@ -100,6 +104,7 @@ private List createRecordsAnswers(ParticipantResultExtraction record) { answers.add(record.getFifthAddressCity()); answers.add(record.getFifthAddressUf()); answers.add(record.getFifthAddressCountry()); + answers.add(record.getFifthAddressCensus()); answers.add(record.getFifthAddressObservation()); return answers; } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/model/ParticipantResultExtraction.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/model/ParticipantResultExtraction.java index 5b2d0c739..5995f91ab 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/model/ParticipantResultExtraction.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/business/extraction/model/ParticipantResultExtraction.java @@ -37,6 +37,7 @@ public class ParticipantResultExtraction { String mainAddressCity; String mainAddressUf; String mainAddressCountry; + String mainAddressCensus; String mainAddressObservation; String secondAddressCep; String secondAddressStreet; @@ -46,6 +47,7 @@ public class ParticipantResultExtraction { String secondAddressCity; String secondAddressUf; String secondAddressCountry; + String secondAddressCensus; String secondAddressObservation; String thirdAddressCep; String thirdAddressStreet; @@ -55,6 +57,7 @@ public class ParticipantResultExtraction { String thirdAddressCity; String thirdAddressUf; String thirdAddressCountry; + String thirdAddressCensus; String thirdAddressObservation; String fourthAddressCep; String fourthAddressStreet; @@ -64,6 +67,7 @@ public class ParticipantResultExtraction { String fourthAddressCity; String fourthAddressUf; String fourthAddressCountry; + String fourthAddressCensus; String fourthAddressObservation; String fifthAddressCep; String fifthAddressStreet; @@ -73,6 +77,7 @@ public class ParticipantResultExtraction { String fifthAddressCity; String fifthAddressUf; String fifthAddressCountry; + String fifthAddressCensus; String fifthAddressObservation; public Long getRecruitmentNumber() { @@ -215,6 +220,10 @@ public String getMainAddressCountry() { return mainAddressCountry; } + public String getMainAddressCensus() { + return mainAddressCensus; + } + public String getMainAddressObservation() { return mainAddressObservation; } @@ -251,6 +260,10 @@ public String getSecondAddressCountry() { return secondAddressCountry; } + public String getSecondAddressCensus() { + return secondAddressCensus; + } + public String getSecondAddressObservation() { return secondAddressObservation; } @@ -287,6 +300,10 @@ public String getThirdAddressCountry() { return thirdAddressCountry; } + public String getThirdAddressCensus() { + return thirdAddressCensus; + } + public String getThirdAddressObservation() { return thirdAddressObservation; } @@ -323,6 +340,10 @@ public String getFourthAddressCountry() { return fourthAddressCountry; } + public String getFourthAddressCensus() { + return fourthAddressCensus; + } + public String getFourthAddressObservation() { return fourthAddressObservation; } @@ -359,6 +380,10 @@ public String getFifthAddressCountry() { return fifthAddressCountry; } + public String getFifthAddressCensus() { + return fifthAddressCensus; + } + public String getFifthAddressObservation() { return fifthAddressObservation; } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/model/noteAboutParticipant/NoteAboutParticipant.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/noteAboutParticipant/NoteAboutParticipant.java new file mode 100644 index 000000000..6624cc5d4 --- /dev/null +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/noteAboutParticipant/NoteAboutParticipant.java @@ -0,0 +1,76 @@ +package org.ccem.otus.participant.model.noteAboutParticipant; + +import org.bson.types.ObjectId; +import org.ccem.otus.model.SerializableModelWithID; + +public class NoteAboutParticipant extends SerializableModelWithID { + + private ObjectId _id; + private Long recruitmentNumber; + private String creationDate; + private String lastUpdate; + private Boolean edited; + private Boolean starred; + private String comment; + private ObjectId userId; + + public NoteAboutParticipant() { + edited = false; + starred = false; + } + + public ObjectId getId() { + return _id; + } + + public Long getRecruitmentNumber() { + return recruitmentNumber; + } + + public String getCreationDate() { + return creationDate; + } + + public String getLastUpdate() { + return lastUpdate; + } + + public Boolean getEdited() { + return edited; + } + + public Boolean getStarred() { return starred; } + + public String getComment() { + return comment; + } + + public ObjectId getUserId() { + return userId; + } + + public void setId(ObjectId _id) { + this._id = _id; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public void setLastUpdate(String lastUpdate) { + this.lastUpdate = lastUpdate; + } + + public void setEdited(Boolean edited) { + this.edited = edited; + } + + public void setStarred(Boolean starred) { + this.starred = starred; + } + + public void setUserId(ObjectId userId) { + this.userId = userId; + } + +} diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/model/noteAboutParticipant/NoteAboutParticipantResponse.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/noteAboutParticipant/NoteAboutParticipantResponse.java new file mode 100644 index 000000000..818970837 --- /dev/null +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/noteAboutParticipant/NoteAboutParticipantResponse.java @@ -0,0 +1,25 @@ +package org.ccem.otus.participant.model.noteAboutParticipant; + +import com.google.gson.GsonBuilder; +import org.bson.types.ObjectId; +import org.ccem.otus.model.SerializableModelWithID; + +public class NoteAboutParticipantResponse extends SerializableModelWithID { + + private ObjectId _id; + private Long recruitmentNumber; + private String creationDate; + private String lastUpdate; + private Boolean edited; + private Boolean starred; + private String comment; + private String userName; + private Boolean isCreator; + + @Override + protected void registerSpecificTypeAdapter(GsonBuilder builder){ + registerGsonBuilderLongAdapter(builder); + registerGsonBuilderLocalDateTimeAdapter(builder); + } + +} diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttempt.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttempt.java index 6948d991e..5c69b1330 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttempt.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttempt.java @@ -5,7 +5,6 @@ import org.bson.Document; import org.bson.types.ObjectId; import org.ccem.otus.participant.model.participant_contact.Address; -import org.ccem.otus.participant.model.participant_contact.AttemptStatus; import org.ccem.otus.participant.utils.LongAdapter; import org.ccem.otus.survey.template.utils.adapters.ImmutableDateAdapter; import org.ccem.otus.survey.template.utils.adapters.LocalDateTimeAdapter; @@ -16,29 +15,23 @@ import java.time.LocalDateTime; import java.util.Arrays; - public class ParticipantContactAttempt { private ObjectId _id; private String objectType; private Long recruitmentNumber; - private Address address; + private Object address; private LocalDateTime attemptDateTime; - private AttemptStatus attemptStatus; + private Object attemptStatus; private ObjectId registeredBy; private String userEmail; private Boolean isValid; - public ParticipantContactAttempt( - String objectType, - Long recruitmentNumber, - Address address, - LocalDateTime attemptDateTime, - AttemptStatus attemptStatus, - ObjectId registeredBy, - String userEmail, - Boolean isValid - ) { + public ParticipantContactAttempt(String objectType, Long recruitmentNumber, Object address, LocalDateTime attemptDateTime, + Object attemptStatus, + ObjectId registeredBy, + String userEmail, + Boolean isValid) { this.objectType = objectType; this.recruitmentNumber = recruitmentNumber; this.address = address; @@ -61,19 +54,6 @@ public Object getAddress() { return address; } - public String getUserEmail() { return userEmail; } - public String getAttemptStatus() { return attemptStatus.getValue(); } - public LocalDateTime getAttemptDateTime() { return attemptDateTime; } - public String getAttemptAddressStreet() { return address.getStreet(); } - public Integer getAttemptAddressNumber() { return address.getStreetNumber(); } - public String getAttemptAddressZipCode() { return address.getPostalCode(); } - public String getAttemptAddressComplement() { return address.getComplements(); } - public String getAttemptAddressDistrict() { return address.getNeighbourhood(); } - public String getAttemptAddressCity() { return address.getCity(); } - public String getAttemptAddressState() { return address.getState(); } - public String getAttemptAddressCountry() { return address.getCountry(); } - public String getAttemptSectorIBGE() { return address.getCensus(); } - public void setRegisteredBy(ObjectId registeredBy) { this.registeredBy = registeredBy; } @@ -85,6 +65,7 @@ public static String serialize(ParticipantContactAttempt participantContactJson) public static ParticipantContactAttempt deserialize(String participantJson) { GsonBuilder builder = ParticipantContactAttempt.getGsonBuilder(); + builder.registerTypeAdapter(Long.class, new LongAdapter()); return builder.create().fromJson(participantJson, ParticipantContactAttempt.class); } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttemptExtractionDTO.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttemptExtractionDTO.java new file mode 100644 index 000000000..8b59bfd6d --- /dev/null +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/model/participantContactAttempt/ParticipantContactAttemptExtractionDTO.java @@ -0,0 +1,98 @@ +package org.ccem.otus.participant.model.participantContactAttempt; + +import com.google.gson.GsonBuilder; +import org.bson.types.ObjectId; +import org.ccem.otus.participant.model.participant_contact.Address; +import org.ccem.otus.participant.model.participant_contact.AttemptStatus; +import org.ccem.otus.participant.utils.LongAdapter; +import org.ccem.otus.survey.template.utils.adapters.ImmutableDateAdapter; +import org.ccem.otus.survey.template.utils.adapters.LocalDateTimeAdapter; +import org.ccem.otus.survey.template.utils.date.ImmutableDate; +import org.ccem.otus.utils.ObjectIdAdapter; + +import java.time.LocalDateTime; + +public class ParticipantContactAttemptExtractionDTO { + + private ObjectId _id; + private String objectType; + private Long recruitmentNumber; + private Address address; + private LocalDateTime attemptDateTime; + private AttemptStatus attemptStatus; + private ObjectId registeredBy; + private String userEmail; + private Boolean isValid; + + public ParticipantContactAttemptExtractionDTO( + String objectType, + Long recruitmentNumber, + Address address, + LocalDateTime attemptDateTime, + AttemptStatus attemptStatus, + ObjectId registeredBy, + String userEmail, + Boolean isValid + ) { + this.objectType = objectType; + this.recruitmentNumber = recruitmentNumber; + this.address = address; + this.attemptDateTime = attemptDateTime; + this.attemptStatus = attemptStatus; + this.registeredBy = registeredBy; + this.userEmail = userEmail; + this.isValid = isValid; + } + + public ObjectId get_id() { + return _id; + } + + public Long getRecruitmentNumber() { + return recruitmentNumber; + } + + public Object getAddress() { + return address; + } + + public String getUserEmail() { return userEmail; } + public String getAttemptStatus() { return attemptStatus.getValue(); } + public LocalDateTime getAttemptDateTime() { return attemptDateTime; } + public String getAttemptAddressStreet() { return address.getStreet(); } + public Integer getAttemptAddressNumber() { return address.getStreetNumber(); } + public String getAttemptAddressZipCode() { return address.getPostalCode(); } + public String getAttemptAddressComplement() { return address.getComplements(); } + public String getAttemptAddressDistrict() { return address.getNeighbourhood(); } + public String getAttemptAddressCity() { return address.getCity(); } + public String getAttemptAddressState() { return address.getState(); } + public String getAttemptAddressCountry() { return address.getCountry(); } + public String getAttemptSectorIBGE() { return address.getCensus(); } + + public void setRegisteredBy(ObjectId registeredBy) { + this.registeredBy = registeredBy; + } + + public static String serialize(ParticipantContactAttemptExtractionDTO participantContactJson) { + GsonBuilder builder = ParticipantContactAttempt.getGsonBuilder(); + return builder.create().toJson(participantContactJson); + } + + public static ParticipantContactAttemptExtractionDTO deserialize(String participantJson) { + GsonBuilder builder = ParticipantContactAttempt.getGsonBuilder(); + return builder.create().fromJson(participantJson, ParticipantContactAttemptExtractionDTO.class); + } + + public static GsonBuilder getGsonBuilder() { + GsonBuilder builder = new GsonBuilder(); + builder.registerTypeAdapter(ObjectId.class, new ObjectIdAdapter()); + builder.registerTypeAdapter(ImmutableDate.class, new ImmutableDateAdapter()); + builder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()); + builder.registerTypeAdapter(Long.class, new LongAdapter()); + return builder; + } + + public void setValid(Boolean valid) { + isValid = valid; + } +} diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/NoteAboutParticipantDao.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/NoteAboutParticipantDao.java new file mode 100644 index 000000000..762caa290 --- /dev/null +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/NoteAboutParticipantDao.java @@ -0,0 +1,26 @@ +package org.ccem.otus.participant.persistence; + +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; + +import java.util.List; + +public interface NoteAboutParticipantDao { + + ObjectId create(NoteAboutParticipant commentAboutParticipant); + + boolean exists(ObjectId noteAboutParticipantId); + + void update(ObjectId userOid, NoteAboutParticipant commentAboutParticipant) throws DataNotFoundException; + + void updateStarred(ObjectId userId, ObjectId noteAboutParticipantId, boolean starred) throws DataNotFoundException, ValidationException; + + void delete(ObjectId userId, ObjectId noteAboutParticipantId) throws DataNotFoundException; + + List getAll(ObjectId userOid, Long recruitmentNumber, SearchSettingsDto searchSettingsDto) throws MemoryExcededException, DataNotFoundException; +} diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/ParticipantContactAttemptDao.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/ParticipantContactAttemptDao.java index 0a4667c6b..44c66e94b 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/ParticipantContactAttemptDao.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/persistence/ParticipantContactAttemptDao.java @@ -4,6 +4,7 @@ import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAddressAttempt; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.participant.model.participant_contact.Address; import org.ccem.otus.participant.persistence.dto.ParticipantContactDto; @@ -22,7 +23,7 @@ public interface ParticipantContactAttemptDao { ArrayList findAddressAttempts(Long recruitmentNumber, String objectType, String position) throws DataNotFoundException; - ArrayList finParticipantContactAttempts() throws DataNotFoundException; + ArrayList finParticipantContactAttempts() throws DataNotFoundException; void swapMainContactAttempts(ParticipantContactDto participantContactDto, Long recruitmentNumber); } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/NoteAboutParticipantService.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/NoteAboutParticipantService.java new file mode 100644 index 000000000..24bdfc008 --- /dev/null +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/NoteAboutParticipantService.java @@ -0,0 +1,24 @@ +package org.ccem.otus.participant.service; + +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; + +import java.util.List; + +public interface NoteAboutParticipantService { + + ObjectId create(ObjectId userOid, NoteAboutParticipant noteAboutParticipant); + + void update(ObjectId userOid, NoteAboutParticipant noteAboutParticipant) throws ValidationException, DataNotFoundException; + + void updateStarred(ObjectId userOid, ObjectId noteAboutParticipantOid, Boolean starred) throws ValidationException, DataNotFoundException; + + void delete(ObjectId userOid, ObjectId noteAboutParticipantOid) throws ValidationException, DataNotFoundException; + + List getAll(ObjectId userOid, Long recruitmentNumber, SearchSettingsDto searchSettingsDto) throws MemoryExcededException, DataNotFoundException, ValidationException; +} diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/NoteAboutParticipantServiceBean.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/NoteAboutParticipantServiceBean.java new file mode 100644 index 000000000..b42b8548f --- /dev/null +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/NoteAboutParticipantServiceBean.java @@ -0,0 +1,82 @@ +package org.ccem.otus.participant.service; + +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; +import org.ccem.otus.participant.persistence.NoteAboutParticipantDao; +import org.ccem.otus.utils.DateUtil; + +import javax.ejb.Stateless; +import javax.inject.Inject; +import java.util.List; + +@Stateless +public class NoteAboutParticipantServiceBean implements NoteAboutParticipantService { + + @Inject + private NoteAboutParticipantDao noteAboutParticipantDao; + + @Override + public ObjectId create(ObjectId userOid, NoteAboutParticipant noteAboutParticipant) { + noteAboutParticipant.setUserId(userOid); + noteAboutParticipant.setCreationDate(DateUtil.nowToISODate()); + return noteAboutParticipantDao.create(noteAboutParticipant); + } + + @Override + public void update(ObjectId userOid, NoteAboutParticipant noteAboutParticipant) throws ValidationException, DataNotFoundException { + noteAboutParticipant.setLastUpdate(DateUtil.nowToISODate()); + noteAboutParticipant.setEdited(true); + try{ + noteAboutParticipantDao.update(userOid, noteAboutParticipant); + } + catch (DataNotFoundException e){ + checkNoteExistenceOnlyById(noteAboutParticipant.getId()); + throw e; + } + } + + @Override + public void updateStarred(ObjectId userOid, ObjectId noteAboutParticipantOid, Boolean starred) throws ValidationException, DataNotFoundException { + if(starred == null){ + throw new ValidationException("Missing starred field"); + } + try{ + noteAboutParticipantDao.updateStarred(userOid, noteAboutParticipantOid, starred); + } + catch (DataNotFoundException e){ + checkNoteExistenceOnlyById(noteAboutParticipantOid); + throw e; + } + } + + @Override + public void delete(ObjectId userOid, ObjectId noteAboutParticipantOid) throws ValidationException, DataNotFoundException { + try{ + noteAboutParticipantDao.delete(userOid, noteAboutParticipantOid); + } + catch (DataNotFoundException e){ + checkNoteExistenceOnlyById(noteAboutParticipantOid); + throw e; + } + } + + @Override + public List getAll(ObjectId userOid, Long recruitmentNumber, SearchSettingsDto searchSettingsDto) throws MemoryExcededException, DataNotFoundException, ValidationException { + if(!searchSettingsDto.isValid()){ + throw new ValidationException("Search settings dto is not valid"); + } + return noteAboutParticipantDao.getAll(userOid, recruitmentNumber, searchSettingsDto); + } + + private void checkNoteExistenceOnlyById(ObjectId noteAboutParticipantOid) throws ValidationException { + if(noteAboutParticipantDao.exists(noteAboutParticipantOid)){ + throw new ValidationException(); + } + } + +} diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptService.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptService.java index f00e57bf5..87b23715d 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptService.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptService.java @@ -5,6 +5,7 @@ import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAddressAttempt; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptConfiguration; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.participant.model.participant_contact.Address; import java.util.ArrayList; @@ -22,7 +23,7 @@ public interface ParticipantContactAttemptService { ArrayList findAddressAttempts(Long recruitmentNumber, String objectType, String position) throws DataNotFoundException; - ArrayList finParticipantContactAttempts() throws DataNotFoundException; + ArrayList finParticipantContactAttempts() throws DataNotFoundException; ParticipantContactAttemptConfiguration findMetadataAttempt(String objectType) throws DataNotFoundException; diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptServiceBean.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptServiceBean.java index 0f4dbb0a6..c060f022b 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptServiceBean.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/ParticipantContactAttemptServiceBean.java @@ -7,6 +7,7 @@ import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAddressAttempt; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptConfiguration; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.participant.model.participant_contact.Address; import org.ccem.otus.participant.persistence.ParticipantContactAttemptConfigurationDao; import org.ccem.otus.participant.persistence.ParticipantContactAttemptDao; @@ -58,7 +59,7 @@ public ArrayList findAddressAttempts(Long recr } @Override - public ArrayList finParticipantContactAttempts() throws DataNotFoundException { + public ArrayList finParticipantContactAttempts() throws DataNotFoundException { return participantContactAttemptDao.finParticipantContactAttempts(); } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/ParticipantContactAttemptsExtraction.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/ParticipantContactAttemptsExtraction.java index 1aa70ef66..7924b7093 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/ParticipantContactAttemptsExtraction.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/ParticipantContactAttemptsExtraction.java @@ -5,6 +5,7 @@ import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.participant.service.extraction.factories.ParticipantContactAttemptsHeadersFactory; import org.ccem.otus.participant.service.extraction.factories.ParticipantContactAttemptsRecordsFactory; @@ -15,7 +16,7 @@ public class ParticipantContactAttemptsExtraction implements Extractable { private ParticipantContactAttemptsHeadersFactory headersFactory; private ParticipantContactAttemptsRecordsFactory recordsFactory; - public ParticipantContactAttemptsExtraction(ArrayList records) { + public ParticipantContactAttemptsExtraction(ArrayList records) { this.headersFactory = new ParticipantContactAttemptsHeadersFactory(); this.recordsFactory = new ParticipantContactAttemptsRecordsFactory(records); } diff --git a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/factories/ParticipantContactAttemptsRecordsFactory.java b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/factories/ParticipantContactAttemptsRecordsFactory.java index 24179d9eb..85262c347 100644 --- a/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/factories/ParticipantContactAttemptsRecordsFactory.java +++ b/source/otus-participant/src/main/java/org/ccem/otus/participant/service/extraction/factories/ParticipantContactAttemptsRecordsFactory.java @@ -5,13 +5,14 @@ import java.util.List; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; public class ParticipantContactAttemptsRecordsFactory { - private ArrayList inputRecords; + private ArrayList inputRecords; private List> outputRecords; - public ParticipantContactAttemptsRecordsFactory(ArrayList records) { + public ParticipantContactAttemptsRecordsFactory(ArrayList records) { this.inputRecords = records; this.outputRecords = new ArrayList<>(); this.buildResultInformation(); @@ -27,7 +28,7 @@ private void buildResultInformation() { }); } - private List createRecordsAnswers(ParticipantContactAttempt record) { + private List createRecordsAnswers(ParticipantContactAttemptExtractionDTO record) { List answers = new LinkedList(); answers.add(record.getRecruitmentNumber().toString()); diff --git a/source/otus-participant/src/test/java/org/ccem/otus/model/noteAboutParticipant/NoteAboutParticipantResponseTest.java b/source/otus-participant/src/test/java/org/ccem/otus/model/noteAboutParticipant/NoteAboutParticipantResponseTest.java new file mode 100644 index 000000000..23cae6bd8 --- /dev/null +++ b/source/otus-participant/src/test/java/org/ccem/otus/model/noteAboutParticipant/NoteAboutParticipantResponseTest.java @@ -0,0 +1,33 @@ +package org.ccem.otus.model.noteAboutParticipant; + +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertTrue; + +@RunWith(PowerMockRunner.class) +public class NoteAboutParticipantResponseTest { + + private static final String NOTE_ABOUT_PARTICIPANT_RESPONSE_JSON = "{}"; + + private NoteAboutParticipantResponse noteAboutParticipantResponse; + + @Before + public void setUp(){ + noteAboutParticipantResponse = new NoteAboutParticipantResponse(); + } + + @Test + public void serialize_method_should_return_JsonString(){ + assertTrue(noteAboutParticipantResponse.serialize() instanceof String); + } + + @Test + public void deserialize_method_should_return_NoteAboutParticipantResponse_instance(){ + assertTrue(noteAboutParticipantResponse.deserializeNonStatic(NOTE_ABOUT_PARTICIPANT_RESPONSE_JSON) instanceof NoteAboutParticipantResponse); + } + +} diff --git a/source/otus-participant/src/test/java/org/ccem/otus/model/noteAboutParticipant/NoteAboutParticipantTest.java b/source/otus-participant/src/test/java/org/ccem/otus/model/noteAboutParticipant/NoteAboutParticipantTest.java new file mode 100644 index 000000000..942702fe4 --- /dev/null +++ b/source/otus-participant/src/test/java/org/ccem/otus/model/noteAboutParticipant/NoteAboutParticipantTest.java @@ -0,0 +1,93 @@ +package org.ccem.otus.model.noteAboutParticipant; + +import org.bson.types.ObjectId; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.junit.Assert.*; + +@RunWith(PowerMockRunner.class) +public class NoteAboutParticipantTest { + + private static final ObjectId NOTE_ABOUT_PARTICIPANT_OID = new ObjectId("5a33cb4a28f10d1043710f7d"); + private static final ObjectId NOTE_ABOUT_PARTICIPANT_OID_2 = new ObjectId("5a33cb4a28f10d1043710f7e"); + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final String CREATION_DATE = "2021-02-15T20:01:50.680Z"; + private static final String CREATION_DATE_2 = "2021-02-16T20:01:50.680Z"; + private static final String LAST_UPDATE = "2021-02-20T20:01:50.680Z"; + private static final String LAST_UPDATE_2 = "2021-02-21T20:01:50.680Z"; + private static final String COMMENT = "something about X"; + private static final ObjectId USER_OID = new ObjectId("5a33cb4a28f10d1043710f00"); + private static final ObjectId USER_OID_2 = new ObjectId("5a33cb4a28f10d1043710f00"); + private static final String NOTE_ABOUT_PARTICIPANT_JSON = "{}"; + + private NoteAboutParticipant noteAboutParticipant; + + @Before + public void setUp(){ + noteAboutParticipant = new NoteAboutParticipant(); + Whitebox.setInternalState(noteAboutParticipant, "_id", NOTE_ABOUT_PARTICIPANT_OID); + Whitebox.setInternalState(noteAboutParticipant, "recruitmentNumber", RECRUITMENT_NUMBER); + Whitebox.setInternalState(noteAboutParticipant, "creationDate", CREATION_DATE); + Whitebox.setInternalState(noteAboutParticipant, "lastUpdate", LAST_UPDATE); + Whitebox.setInternalState(noteAboutParticipant, "comment", COMMENT); + Whitebox.setInternalState(noteAboutParticipant, "userId", USER_OID); + } + + @Test + public void constructor_should_set_edited_and_starred_flags_as_false(){ + assertFalse(noteAboutParticipant.getEdited()); + assertFalse(noteAboutParticipant.getStarred()); + } + + @Test + public void getters_check(){ + assertEquals(NOTE_ABOUT_PARTICIPANT_OID, noteAboutParticipant.getId()); + assertEquals(RECRUITMENT_NUMBER, noteAboutParticipant.getRecruitmentNumber()); + assertEquals(CREATION_DATE, noteAboutParticipant.getCreationDate()); + assertEquals(LAST_UPDATE, noteAboutParticipant.getLastUpdate()); + assertEquals(COMMENT, noteAboutParticipant.getComment()); + assertEquals(USER_OID, noteAboutParticipant.getUserId()); + } + + @Test + public void id_setter_check(){ + noteAboutParticipant.setId(NOTE_ABOUT_PARTICIPANT_OID_2); + assertEquals(NOTE_ABOUT_PARTICIPANT_OID_2, noteAboutParticipant.getId()); + } + + @Test + public void creationDate_setter_check(){ + noteAboutParticipant.setCreationDate(CREATION_DATE_2); + assertEquals(CREATION_DATE_2, noteAboutParticipant.getCreationDate()); + } + + @Test + public void lastUpdate_setter_check(){ + noteAboutParticipant.setLastUpdate(LAST_UPDATE_2); + assertEquals(LAST_UPDATE_2, noteAboutParticipant.getLastUpdate()); + } + + @Test + public void edited_setter_check(){ + noteAboutParticipant.setEdited(true); + assertTrue(noteAboutParticipant.getEdited()); + } + + @Test + public void starred_setter_check(){ + noteAboutParticipant.setStarred(true); + assertTrue(noteAboutParticipant.getStarred()); + } + + @Test + public void userId_setter_check(){ + noteAboutParticipant.setUserId(USER_OID_2); + assertEquals(USER_OID_2, noteAboutParticipant.getUserId()); + } + +} diff --git a/source/otus-participant/src/test/java/org/ccem/otus/participant/service/NoteAboutParticipantServiceBeanTest.java b/source/otus-participant/src/test/java/org/ccem/otus/participant/service/NoteAboutParticipantServiceBeanTest.java new file mode 100644 index 000000000..3900f243b --- /dev/null +++ b/source/otus-participant/src/test/java/org/ccem/otus/participant/service/NoteAboutParticipantServiceBeanTest.java @@ -0,0 +1,164 @@ +package org.ccem.otus.participant.service; + +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.exceptions.webservice.validation.ValidationException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; +import org.ccem.otus.participant.persistence.NoteAboutParticipantDao; +import org.ccem.otus.utils.DateUtil; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.*; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({DateUtil.class}) +public class NoteAboutParticipantServiceBeanTest { + + private static final String NOTE_ABOUT_PARTICIPANT_ID = "5a33cb4a28f10d1043710f7d"; + private static final ObjectId NOTE_ABOUT_PARTICIPANT_OID = new ObjectId(NOTE_ABOUT_PARTICIPANT_ID); + private static final Boolean STARRED = true; + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final ObjectId USER_OID = new ObjectId("5a33cb4a28f10d1043710f00"); + private static final String NOW_DATE_ISO = "2021-02-15T20:01:50.680Z"; + + @InjectMocks + private NoteAboutParticipantServiceBean serviceBean; + + @Mock + private NoteAboutParticipantDao dao; + + @Mock + private NoteAboutParticipant noteAboutParticipant; + @Mock + private NoteAboutParticipant noteAboutParticipantFound; + @Mock + private SearchSettingsDto searchSettingsDto; + + @Before + public void setUp() throws Exception { + doReturn(NOTE_ABOUT_PARTICIPANT_OID).when(noteAboutParticipant).getId(); + PowerMockito.mockStatic(DateUtil.class); + when(DateUtil.class, "nowToISODate").thenReturn(NOW_DATE_ISO); + } + + @Test + public void create_method_should_set_userId_and_creationDate_and_call_dao_create_method(){ + serviceBean.create(USER_OID, noteAboutParticipant); + verify(noteAboutParticipant, Mockito.times(1)).setUserId(USER_OID); + verify(noteAboutParticipant, Mockito.times(1)).setCreationDate(NOW_DATE_ISO); + verify(dao, Mockito.times(1)).create(noteAboutParticipant); + } + + @Test + public void update_method_should_set_lastUpdate_and_edited_flag_and_call_dao_update_method() throws ValidationException, DataNotFoundException { + serviceBean.update(USER_OID, noteAboutParticipant); + verify(noteAboutParticipant, Mockito.times(1)).setLastUpdate(NOW_DATE_ISO); + verify(noteAboutParticipant, Mockito.times(1)).setEdited(true); + verify(dao, Mockito.times(1)).update(USER_OID, noteAboutParticipant); + } + + @Test(expected = DataNotFoundException.class) + public void update_method_should_throw_DataNotFoundException_in_case_NOT_found_noteAboutParticipant_by_id_and_userId() throws ValidationException, DataNotFoundException { + doThrow(new DataNotFoundException()).when(dao).update(USER_OID, noteAboutParticipant); + checkNoteExistenceOnlyByIdOk(); + serviceBean.update(USER_OID, noteAboutParticipant); + } + + @Test(expected = ValidationException.class) + public void update_method_should_throw_ValidationException_in_case_found_noteAboutParticipant_by_id_but_another_userId() throws ValidationException, DataNotFoundException { + doThrow(new DataNotFoundException()).when(dao).update(USER_OID, noteAboutParticipant); + checkNoteExistenceOnlyByIdFindSomeNote(); + serviceBean.update(USER_OID, noteAboutParticipant); + } + + + @Test(expected = ValidationException.class) + public void updateStarred_method_should_throw_ValidationException_in_case_null_starred() throws ValidationException, DataNotFoundException { + serviceBean.updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, null); + } + + @Test + public void updateStarred_method_should_call_updateStarred_dao_method() throws ValidationException, DataNotFoundException { + serviceBean.updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + verify(dao, Mockito.times(1)).updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + } + + @Test(expected = DataNotFoundException.class) + public void updateStarred_method_should_throw_DataNotFoundException_in_case_NOT_found_noteAboutParticipant_by_id_and_userId() throws ValidationException, DataNotFoundException { + doThrow(new DataNotFoundException()).when(dao).updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + checkNoteExistenceOnlyByIdOk(); + serviceBean.updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + } + + @Test(expected = ValidationException.class) + public void updateStarred_method_should_throw_DataNotFoundException_ValidationException_in_case_found_noteAboutParticipant_by_id_but_another_userId() throws ValidationException, DataNotFoundException { + doThrow(new DataNotFoundException()).when(dao).updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + checkNoteExistenceOnlyByIdFindSomeNote(); + serviceBean.updateStarred(USER_OID, NOTE_ABOUT_PARTICIPANT_OID, STARRED); + } + + + @Test + public void delete_method_should_call_delete_dao_method() throws ValidationException, DataNotFoundException { + serviceBean.delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + verify(dao, Mockito.times(1)).delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + } + + @Test(expected = DataNotFoundException.class) + public void delete_method_should_throw_DataNotFoundException_in_case_NOT_found_noteAboutParticipant_by_id_and_userId() throws ValidationException, DataNotFoundException { + doThrow(new DataNotFoundException()).when(dao).delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + checkNoteExistenceOnlyByIdOk(); + serviceBean.delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + } + + @Test(expected = ValidationException.class) + public void delete_method_should_throw_DataNotFoundException_ValidationException_in_case_found_noteAboutParticipant_by_id_but_another_userId() throws ValidationException, DataNotFoundException { + doThrow(new DataNotFoundException()).when(dao).delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + checkNoteExistenceOnlyByIdFindSomeNote(); + serviceBean.delete(USER_OID, NOTE_ABOUT_PARTICIPANT_OID); + } + + + @Test + public void getAll_method_should_call_getAll_dao_method() throws ValidationException, DataNotFoundException, MemoryExcededException { + doReturn(true).when(searchSettingsDto).isValid(); + List noteAboutParticipantResponses = new ArrayList<>(); + doReturn(noteAboutParticipantResponses).when(dao).getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto); + assertEquals( + noteAboutParticipantResponses, + serviceBean.getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto) + ); + verify(dao, Mockito.times(1)).getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto); + } + + @Test(expected = ValidationException.class) + public void getAll_method_should_throw_DataNotFoundException_in_case_NOT_found_noteAboutParticipant_by_id_and_userId() throws ValidationException, DataNotFoundException, MemoryExcededException { + doReturn(false).when(searchSettingsDto).isValid(); + serviceBean.getAll(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto); + } + + + private void checkNoteExistenceOnlyByIdOk(){ + doReturn(false).when(dao).exists(NOTE_ABOUT_PARTICIPANT_OID); + } + + private void checkNoteExistenceOnlyByIdFindSomeNote(){ + doReturn(true).when(dao).exists(NOTE_ABOUT_PARTICIPANT_OID); + } +} diff --git a/source/otus-permissions/pom.xml b/source/otus-permissions/pom.xml index a6cec41cd..573d9999d 100644 --- a/source/otus-permissions/pom.xml +++ b/source/otus-permissions/pom.xml @@ -8,7 +8,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-persistence/pom.xml b/source/otus-persistence/pom.xml index 2735e50ef..c7dab8246 100644 --- a/source/otus-persistence/pom.xml +++ b/source/otus-persistence/pom.xml @@ -8,7 +8,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-persistence/src/main/java/br/org/mongodb/MongoGenericDao.java b/source/otus-persistence/src/main/java/br/org/mongodb/MongoGenericDao.java index abb727b6d..98938607a 100644 --- a/source/otus-persistence/src/main/java/br/org/mongodb/MongoGenericDao.java +++ b/source/otus-persistence/src/main/java/br/org/mongodb/MongoGenericDao.java @@ -16,6 +16,7 @@ public abstract class MongoGenericDao { protected static final String ID_FIELD_NAME = "_id"; protected static final String OBJECT_TYPE_PATH = "objectType"; + protected static final String SET_OPERATOR = "$set"; @Inject protected MongoDatabase db; diff --git a/source/otus-persistence/src/main/java/br/org/otus/configuration/stage/StageDaoBean.java b/source/otus-persistence/src/main/java/br/org/otus/configuration/stage/StageDaoBean.java index 494b375c2..1d010bc74 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/configuration/stage/StageDaoBean.java +++ b/source/otus-persistence/src/main/java/br/org/otus/configuration/stage/StageDaoBean.java @@ -1,19 +1,16 @@ package br.org.otus.configuration.stage; import br.org.mongodb.MongoGenericDao; -import com.mongodb.client.AggregateIterable; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCursor; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import model.Stage; import org.bson.Document; -import org.bson.conversions.Bson; import org.bson.types.ObjectId; import org.ccem.otus.exceptions.webservice.common.AlreadyExistException; import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; -import org.ccem.otus.service.ParseQuery; import persistence.StageDao; import java.util.ArrayList; @@ -35,7 +32,7 @@ public StageDaoBean(){ public ObjectId create(Stage stage) throws AlreadyExistException { checkExistence(stage); - Document parsed = Document.parse(Stage.serialize(stage)); + Document parsed = Document.parse(stage.serialize()); collection.insertOne(parsed); return parsed.getObjectId(ID_FIELD_NAME); } diff --git a/source/otus-persistence/src/main/java/br/org/otus/datasource/DataSourceDaoBean.java b/source/otus-persistence/src/main/java/br/org/otus/datasource/DataSourceDaoBean.java index 1069ff16b..56153d170 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/datasource/DataSourceDaoBean.java +++ b/source/otus-persistence/src/main/java/br/org/otus/datasource/DataSourceDaoBean.java @@ -54,12 +54,10 @@ public void update(DataSource dataSource) throws ValidationException { @Override public List find() { ArrayList dataSources = new ArrayList(); - FindIterable result = collection.find(); result.forEach((Block) document -> { dataSources.add(DataSource.deserialize(document.toJson())); }); - return dataSources; } @@ -97,6 +95,17 @@ public DataSourceValuesMapping getDataSourceMapping() { return dataSourceValuesMapping; } + @Override + public List find(List datasourceIds) { + List dataSources = new ArrayList<>(); + Document query = new Document("id", new Document("$in", datasourceIds)); + FindIterable result = collection.find(query); + result.forEach((Block) document -> { + dataSources.add(DataSource.deserialize(document.toJson())); + }); + return dataSources; + } + private Bson parseQuery(String stage) { return new GsonBuilder().create().fromJson(stage, Document.class); } diff --git a/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/ParticipantLaboratoryExtractionDaoBean.java b/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/ParticipantLaboratoryExtractionDaoBean.java index d6a71e21c..cf477a858 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/ParticipantLaboratoryExtractionDaoBean.java +++ b/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/ParticipantLaboratoryExtractionDaoBean.java @@ -40,55 +40,41 @@ public LinkedList getLaboratoryExtraction() { LinkedList laboratoryExtraction = laboratoryExtraction(attachedLaboratories, false); participantLaboratoryRecordExtractions.addAll(laboratoryExtraction); - return participantLaboratoryRecordExtractions; } private LinkedList laboratoryExtraction(Document attachedLaboratories, boolean extractionFromUnattached) { LinkedList participantLaboratoryRecordExtractions = new LinkedList(); - CompletableFuture> future1 = CompletableFuture.supplyAsync(() -> { - AggregateIterable notAliquotedTubesDocument = null; - Document tubeCodeDocument = aliquotDao.aggregate(new ParticipantLaboratoryExtractionQueryBuilder().getTubeCodesInAliquotQuery()).first(); - - ArrayList tubeCodes = null; - if (tubeCodeDocument != null) { - tubeCodes = (ArrayList) tubeCodeDocument.get("tubeCodes"); - } else { - tubeCodes = new ArrayList<>(); - } - - notAliquotedTubesDocument = participantLaboratoryDao - .aggregate(new ParticipantLaboratoryExtractionQueryBuilder().getNotAliquotedTubesQuery(tubeCodes, attachedLaboratories, extractionFromUnattached)); - return notAliquotedTubesDocument; + CompletableFuture> notAliquotedTubesFuture = CompletableFuture.supplyAsync(() -> { + Document tubeCodeDocument = aliquotDao.aggregate(new ParticipantLaboratoryExtractionQueryBuilder().getTubeCodesInAliquotQuery()).first(); + ArrayList tubeCodes = (tubeCodeDocument == null ? new ArrayList<>() : (ArrayList) tubeCodeDocument.get("tubeCodes")); + return participantLaboratoryDao.aggregate( + new ParticipantLaboratoryExtractionQueryBuilder().getNotAliquotedTubesQuery(tubeCodes, attachedLaboratories, extractionFromUnattached)); }); - CompletableFuture> future2 = CompletableFuture.supplyAsync(() -> + CompletableFuture> aliquotedTubesFuture = CompletableFuture.supplyAsync(() -> aliquotDao.aggregate(new ParticipantLaboratoryExtractionQueryBuilder().getAliquotedTubesQuery(attachedLaboratories, extractionFromUnattached)) ); - try { - AggregateIterable future1Result = future1.get(); - if (future1Result != null) { - for (Document notAliquotedTube : future1Result) { - participantLaboratoryRecordExtractions.add(LaboratoryRecordExtraction.deserialize(notAliquotedTube.toJson())); - } - } - } catch (InterruptedException | ExecutionException e) { - e.printStackTrace(); - } + addFoundTubes(participantLaboratoryRecordExtractions, notAliquotedTubesFuture); + addFoundTubes(participantLaboratoryRecordExtractions, aliquotedTubesFuture); + + return participantLaboratoryRecordExtractions; + } + private void addFoundTubes(LinkedList participantLaboratoryRecordExtractions, CompletableFuture> tubesFuture){ try { - AggregateIterable future2Result = future2.get(); - if (future2Result != null) { - for (Document aliquotedTubes : future2Result) { - participantLaboratoryRecordExtractions.add(LaboratoryRecordExtraction.deserialize(aliquotedTubes.toJson())); - } + AggregateIterable tubesFutureResult = tubesFuture.get(); + if (tubesFutureResult == null) { + return; + } + for (Document tubes : tubesFutureResult) { + participantLaboratoryRecordExtractions.add(LaboratoryRecordExtraction.deserialize(tubes.toJson())); } } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } - - return participantLaboratoryRecordExtractions; } + } diff --git a/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/builder/ParticipantLaboratoryExtractionQueryBuilder.java b/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/builder/ParticipantLaboratoryExtractionQueryBuilder.java index 3f2780f7d..5be80d3a5 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/builder/ParticipantLaboratoryExtractionQueryBuilder.java +++ b/source/otus-persistence/src/main/java/br/org/otus/laboratory/extraction/builder/ParticipantLaboratoryExtractionQueryBuilder.java @@ -5,7 +5,6 @@ import java.util.Arrays; import java.util.List; -import com.mongodb.client.AggregateIterable; import org.bson.Document; import org.bson.conversions.Bson; @@ -243,4 +242,5 @@ private Document parseQuery(String query) { GsonBuilder gsonBuilder = new GsonBuilder(); return gsonBuilder.create().fromJson(query, Document.class); } + } diff --git a/source/otus-persistence/src/main/java/br/org/otus/participant/NoteAboutParticipantDaoBean.java b/source/otus-persistence/src/main/java/br/org/otus/participant/NoteAboutParticipantDaoBean.java new file mode 100644 index 000000000..230faf207 --- /dev/null +++ b/source/otus-persistence/src/main/java/br/org/otus/participant/NoteAboutParticipantDaoBean.java @@ -0,0 +1,101 @@ +package br.org.otus.participant; + +import br.org.mongodb.MongoGenericDao; +import br.org.otus.participant.builder.NoteAboutParticipantQueryBuilder; +import com.mongodb.client.AggregateIterable; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import org.bson.Document; +import org.bson.types.ObjectId; +import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; +import org.ccem.otus.exceptions.webservice.common.MemoryExcededException; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipant; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; +import org.ccem.otus.participant.persistence.NoteAboutParticipantDao; + +import java.util.ArrayList; +import java.util.List; + +import static com.mongodb.client.model.Filters.eq; + +public class NoteAboutParticipantDaoBean extends MongoGenericDao implements NoteAboutParticipantDao { + + private static final String COLLECTION_NAME = "participant_note_about"; + private static final String USER_ID_PATH = "userId"; + private static final String STARRED_PATH = "starred"; + + public NoteAboutParticipantDaoBean() { + super(COLLECTION_NAME, Document.class); + } + + @Override + public ObjectId create(NoteAboutParticipant noteAboutParticipant) { + Document parsed = Document.parse(noteAboutParticipant.serialize()); + collection.insertOne(parsed); + return parsed.getObjectId(ID_FIELD_NAME); + } + + @Override + public boolean exists(ObjectId noteAboutParticipantId) { + Document result = collection.find(eq(ID_FIELD_NAME, noteAboutParticipantId)).first(); + return (result != null); + } + + @Override + public void update(ObjectId userOid, NoteAboutParticipant noteAboutParticipant) throws DataNotFoundException { + UpdateResult updateResult = collection.updateOne( + new Document(ID_FIELD_NAME, noteAboutParticipant.getId()).append(USER_ID_PATH, userOid), + new Document(SET_OPERATOR, Document.parse(noteAboutParticipant.serialize())) + ); + if (updateResult.getMatchedCount() == 0) { + throw new DataNotFoundException("There is no note about participant with id {" + noteAboutParticipant.getId().toHexString() + "}"); + } + } + + @Override + public void updateStarred(ObjectId userOid, ObjectId noteAboutParticipantId, boolean starred) throws DataNotFoundException { + UpdateResult updateResult = collection.updateOne( + new Document(ID_FIELD_NAME, noteAboutParticipantId).append(USER_ID_PATH, userOid), + new Document(SET_OPERATOR, new Document(STARRED_PATH, starred)) + ); + if (updateResult.getMatchedCount() == 0) { + throw new DataNotFoundException("There is no note about participant with id {" + noteAboutParticipantId.toHexString() + "}"); + } + } + + @Override + public void delete(ObjectId userId, ObjectId noteAboutParticipantId) throws DataNotFoundException { + Document query = new Document(ID_FIELD_NAME, noteAboutParticipantId); + query.put(USER_ID_PATH, userId); + DeleteResult deleteResult = collection.deleteOne(query); + if (deleteResult.getDeletedCount() == 0) { + throw new DataNotFoundException("There is no note about participant with id {" + noteAboutParticipantId.toHexString() + "}"); + } + } + + @Override + public List getAll(ObjectId userOid, Long recruitmentNumber, SearchSettingsDto searchSettingsDto) throws MemoryExcededException, DataNotFoundException { + AggregateIterable results = collection.aggregate((new NoteAboutParticipantQueryBuilder().getByRnQuery(userOid, recruitmentNumber, searchSettingsDto))).allowDiskUse(true); + if (results == null) { + throw new DataNotFoundException("No results for user note about participant."); + } + + MongoCursor iterator = results.iterator(); + + List notes = new ArrayList<>(); + + while (iterator.hasNext()) { + try { + notes.add(new NoteAboutParticipantResponse().deserializeNonStatic(iterator.next().toJson())); + } catch (OutOfMemoryError e) { + notes.clear(); + throw new MemoryExcededException("Notes about participant {" + recruitmentNumber + "} exceeded memory used"); + } + } + + return notes; + } + +} diff --git a/source/otus-persistence/src/main/java/br/org/otus/participant/ParticipantContactAttemptDaoBean.java b/source/otus-persistence/src/main/java/br/org/otus/participant/ParticipantContactAttemptDaoBean.java index beed2ed2f..9a677ca9c 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/participant/ParticipantContactAttemptDaoBean.java +++ b/source/otus-persistence/src/main/java/br/org/otus/participant/ParticipantContactAttemptDaoBean.java @@ -10,6 +10,7 @@ import org.ccem.otus.exceptions.webservice.common.DataNotFoundException; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAddressAttempt; import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttempt; +import org.ccem.otus.participant.model.participantContactAttempt.ParticipantContactAttemptExtractionDTO; import org.ccem.otus.participant.model.participant_contact.Address; import org.ccem.otus.participant.persistence.ParticipantContactAttemptDao; import org.ccem.otus.participant.persistence.dto.ParticipantContactDto; @@ -156,7 +157,7 @@ public ArrayList findAddressAttempts(Long recr } @Override - public ArrayList finParticipantContactAttempts() throws DataNotFoundException { + public ArrayList finParticipantContactAttempts() throws DataNotFoundException { try{ ArrayList pipeline = new ArrayList<>(); @@ -202,13 +203,13 @@ public ArrayList finParticipantContactAttempts() thro )); AggregateIterable result = collection.aggregate(pipeline); - ArrayList attempts = new ArrayList<>(); + ArrayList attempts = new ArrayList<>(); MongoCursor iterator = result.iterator(); while (iterator.hasNext()) { Document document = iterator.next(); - ParticipantContactAttempt participantContactAttempt = ParticipantContactAttempt.deserialize(document.toJson()); + ParticipantContactAttemptExtractionDTO participantContactAttempt = ParticipantContactAttemptExtractionDTO.deserialize(document.toJson()); attempts.add(participantContactAttempt); } diff --git a/source/otus-persistence/src/main/java/br/org/otus/participant/builder/NoteAboutParticipantQueryBuilder.java b/source/otus-persistence/src/main/java/br/org/otus/participant/builder/NoteAboutParticipantQueryBuilder.java new file mode 100644 index 000000000..215cf2c1e --- /dev/null +++ b/source/otus-persistence/src/main/java/br/org/otus/participant/builder/NoteAboutParticipantQueryBuilder.java @@ -0,0 +1,75 @@ +package br.org.otus.participant.builder; + +import org.bson.conversions.Bson; +import org.bson.types.ObjectId; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.ccem.otus.service.ParseQuery; + +import java.util.ArrayList; + +public class NoteAboutParticipantQueryBuilder { + + private ArrayList pipeline; + + public ArrayList getByRnQuery(ObjectId userOid, Long recruitmentNumber, SearchSettingsDto searchSettingsDto) { + int skip = searchSettingsDto.getCurrentQuantity(); + int limit = searchSettingsDto.getQuantityToGet(); + + pipeline = new ArrayList<>(); + pipeline.add(ParseQuery.toDocument("{\n" + + " $match: {\n" + + " \"recruitmentNumber\": " + recruitmentNumber + + " }\n" + + " }")); + pipeline.add(ParseQuery.toDocument("{\n" + + " $lookup: {\n" + + " from: \"user\",\n" + + " let: {\n" + + " \"userId\": \"$userId\"\n" + + " },\n" + + " pipeline: [\n" + + " {\n" + + " $match: {\n" + + " $expr: {\n" + + " $eq: [\"$_id\", \"$$userId\"]\n" + + " }\n" + + " }\n" + + " },\n" + + " {\n" + + " $project: {\n" + + " \"name\": {\n" + + " $concat: [\"$name\", \" \", \"$surname\" ]\n" + + " }\n" + + " }\n" + + " }\n" + + " ],\n" + + " as: \"user\"\n" + + " }\n" + + " }")); + pipeline.add(ParseQuery.toDocument("{\n" + + " $addFields: {\n" + + " \"userName\": {\n" + + " $ifNull: [ { $arrayElemAt: [\"$user.name\",0] }, null ]\n" + + " },\n" + + " \"isCreator\": {\n" + + " $eq: [ {$toString: \"$userId\"}, " + userOid.toHexString()+ "]\n" + + " }\n" + + " }\n" + + " }")); + pipeline.add(ParseQuery.toDocument("{\n" + + " $project: {\n" + + " \"userId\": 0,\n" + + " \"user\": 0\n" + + " }\n" + + " }")); + pipeline.add(ParseQuery.toDocument("{\n" + + " $sort: {\n" + + " \"creationDate\": -1\n" + + " }\n" + + " }")); + pipeline.add(ParseQuery.toDocument("{ $skip: " + skip + " }")); + pipeline.add(ParseQuery.toDocument("{ $limit: " + limit + " }")); + return pipeline; + } + +} diff --git a/source/otus-persistence/src/main/java/br/org/otus/survey/activity/ActivityDaoBean.java b/source/otus-persistence/src/main/java/br/org/otus/survey/activity/ActivityDaoBean.java index 8d97c17ec..b6390b84f 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/survey/activity/ActivityDaoBean.java +++ b/source/otus-persistence/src/main/java/br/org/otus/survey/activity/ActivityDaoBean.java @@ -347,6 +347,28 @@ public void discardByID(ObjectId activityOID) throws DataNotFoundException { } } + @Override + public List getActivityIds(String acronym, Integer version, Boolean isDiscardedValue, + List activityIdsToExcludeOfQuery) throws MemoryExcededException { + + ArrayList activities = new ArrayList<>(); + + ArrayList pipeline = SurveyActivityQueryBuilder.getActivityIdsQuery(acronym, version, isDiscardedValue, activityIdsToExcludeOfQuery); + AggregateIterable results = collection.aggregate(pipeline).allowDiskUse(true); + MongoCursor iterator = results.iterator(); + + while (iterator.hasNext()) { + try { + activities.add(SurveyActivity.deserialize(iterator.next().toJson()).getActivityID()); + } catch (OutOfMemoryError e) { + activities.clear(); + throw new MemoryExcededException(String.format("Extraction { %s, version %ld } exceeded memory used.", acronym, version)); + } + } + + return activities; + } + private void removeOids(Document parsedActivity) { parsedActivity.remove("_id"); ((Document) parsedActivity.get("surveyForm")).remove("_id"); //todo: remove when this id becomes standard diff --git a/source/otus-persistence/src/main/java/br/org/otus/survey/activity/builder/SurveyActivityQueryBuilder.java b/source/otus-persistence/src/main/java/br/org/otus/survey/activity/builder/SurveyActivityQueryBuilder.java index 8f7c57697..df0370362 100644 --- a/source/otus-persistence/src/main/java/br/org/otus/survey/activity/builder/SurveyActivityQueryBuilder.java +++ b/source/otus-persistence/src/main/java/br/org/otus/survey/activity/builder/SurveyActivityQueryBuilder.java @@ -8,6 +8,21 @@ public class SurveyActivityQueryBuilder { + public static final String ACRONYM_PATH = "surveyForm.acronym"; + public static final String VERSION_PATH = "surveyForm.version"; + public static final String DISCARDED_PATH = "isDiscarded"; + public static final String TEMPLATE_PATH = "surveyForm.surveyTemplate"; + public static final String RECRUITMENT_NUMBER_PATH = "participantData.recruitmentNumber"; + public static final String CATEGORY_NAME_PATH = "category.name"; + public static final String CATEGORY_LABEL_PATH = "category.label"; + public static final String IS_DISCARDED = "isDiscarded"; + public static final String ID_PATH = "_id"; + public static final String STATUS_HISTORY_NAME = "statusHistory.name"; + public static final String FINALIZED = "FINALIZED"; + private static final String SET = "$set"; + private static final String PARTICIPANT_DATA_EMAIL = "participantData.email"; + private static final String STAGE_PATH = "stageId"; + public ArrayList getSurveyActivityListByStageAndAcronymQuery(long rn, List permittedSurveys){ ArrayList pipeline = new ArrayList<>(); @@ -113,4 +128,35 @@ public ArrayList getSurveyActivityListByStageAndAcronymQuery(long rn, List return pipeline; } + + public static ArrayList getActivityIdsQuery(String acronym, Integer version, Boolean isDiscardedValue, + List activityIdsToExcludeOfQuery){ + + String idsToExcludeExpression = ""; + if(activityIdsToExcludeOfQuery != null && !activityIdsToExcludeOfQuery.isEmpty()){ + idsToExcludeExpression = "\""+ID_PATH+"\": { $not: { $in: " + activityIdsToExcludeOfQuery.toString() + "} },\n"; + } + + String isDiscardedExpression = ""; + if(isDiscardedValue != null){ + isDiscardedExpression = "\""+DISCARDED_PATH+"\": " + isDiscardedValue.toString() +",\n"; + } + + ArrayList pipeline = new ArrayList<>(); + + pipeline.add(ParseQuery.toDocument("{\n" + + " $match: {\n" + + " " + idsToExcludeExpression + + " " + isDiscardedExpression + + " \""+ACRONYM_PATH+"\": "+ acronym + ",\n" + + " \""+VERSION_PATH+"\": "+ version + + " }\n" + + " }")); + + pipeline.add(ParseQuery.toDocument("{\n" + + " $sort: { _id: 1 }\n" + + " }")); + + return pipeline; + } } diff --git a/source/otus-persistence/src/test/java/br/org/otus/participant/builder/NoteAboutParticipantQueryBuilderTest.java b/source/otus-persistence/src/test/java/br/org/otus/participant/builder/NoteAboutParticipantQueryBuilderTest.java new file mode 100644 index 000000000..45600f082 --- /dev/null +++ b/source/otus-persistence/src/test/java/br/org/otus/participant/builder/NoteAboutParticipantQueryBuilderTest.java @@ -0,0 +1,100 @@ +package br.org.otus.participant.builder; + +import com.google.gson.GsonBuilder; +import org.bson.types.ObjectId; +import org.ccem.otus.model.searchSettingsDto.SearchSettingsDto; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.doReturn; + +@RunWith(PowerMockRunner.class) +public class NoteAboutParticipantQueryBuilderTest { + + private static final ObjectId USER_OID = new ObjectId("5a33cb4a28f10d1043710f00"); + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final int SKIP = 0; + private static final int LIMIT = 5; + + private NoteAboutParticipantQueryBuilder queryBuilder; + + @Mock + private SearchSettingsDto searchSettingsDto; + + @Before + public void setUp(){ + queryBuilder = new NoteAboutParticipantQueryBuilder(); + + doReturn(SKIP).when(searchSettingsDto).getCurrentQuantity(); + doReturn(LIMIT).when(searchSettingsDto).getQuantityToGet(); + } + + @Test + public void getByRnQuery_method_test(){ + final String EXPECTED_QUERY = "[{" + + " \"$match\": {" + + " \"recruitmentNumber\": " + RECRUITMENT_NUMBER.toString() + ".0" + + " }" + + " }," + + "{" + + " \"$lookup\": {" + + " \"from\": \"user\"," + + " \"let\": {" + + " \"userId\": \"$userId\"" + + " }," + + " \"pipeline\": [" + + " {" + + " \"$match\": {" + + " \"$expr\": {" + + " \"$eq\": [\"$_id\", \"$$userId\"]" + + " }" + + " }" + + " }," + + " {" + + " \"$project\": {" + + " \"name\": {" + + " \"$concat\": [\"$name\", \" \", \"$surname\" ]" + + " }" + + " }" + + " }" + + " ]," + + " \"as\": \"user\"" + + " }" + + " }," + + "{" + + " \"$addFields\": {" + + " \"userName\": {" + + " \"$ifNull\": [ { \"$arrayElemAt\": [\"$user.name\",0.0] }, null ]" + + " }," + + " \"isCreator\": {" + + " \"$eq\": [ {\"$toString\": \"$userId\"}, \"" + USER_OID.toHexString()+ "\"]" + + " }" + + " }" + + " }," + + "{" + + " \"$project\": {" + + " \"userId\": 0.0," + + " \"user\": 0.0" + + " }" + + " }," + + "{" + + " \"$sort\": {" + + " \"creationDate\": -1.0" + + " }" + + " }," + + "{ \"$skip\": " + SKIP + ".0}," + + "{ \"$limit\": " + LIMIT + ".0}" + "]"; + ; + assertEquals( + EXPECTED_QUERY.replaceAll(" ", "").replaceAll("\"\"", "\" \""), + new GsonBuilder().create().toJson( + queryBuilder.getByRnQuery(USER_OID, RECRUITMENT_NUMBER, searchSettingsDto) + )); + } + +} diff --git a/source/otus-report/pom.xml b/source/otus-report/pom.xml index 498d8597c..b236c7fdc 100644 --- a/source/otus-report/pom.xml +++ b/source/otus-report/pom.xml @@ -8,7 +8,7 @@ otus-root org.ccem.otus - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-rest/pom.xml b/source/otus-rest/pom.xml index e334f2354..7b1042e2d 100644 --- a/source/otus-rest/pom.xml +++ b/source/otus-rest/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml diff --git a/source/otus-rest/src/main/java/br/org/otus/AuthenticationResource.java b/source/otus-rest/src/main/java/br/org/otus/AuthenticationResource.java new file mode 100644 index 000000000..0e22bf521 --- /dev/null +++ b/source/otus-rest/src/main/java/br/org/otus/AuthenticationResource.java @@ -0,0 +1,23 @@ +package br.org.otus; + +import br.org.otus.security.AuthorizationHeaderReader; +import br.org.otus.security.context.SecurityContext; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; + +public abstract class AuthenticationResource { + + @Inject + protected SecurityContext securityContext; + + protected String getToken(HttpServletRequest request) { + return request.getHeader(HttpHeaders.AUTHORIZATION); + } + + protected String getUserEmailToken(HttpServletRequest request) { + String token = getToken(request); + return securityContext.getSession(AuthorizationHeaderReader.readToken(token)).getAuthenticationData().getUserEmail(); + } +} diff --git a/source/otus-rest/src/main/java/br/org/otus/UserAuthenticationResource.java b/source/otus-rest/src/main/java/br/org/otus/UserAuthenticationResource.java new file mode 100644 index 000000000..36dd16902 --- /dev/null +++ b/source/otus-rest/src/main/java/br/org/otus/UserAuthenticationResource.java @@ -0,0 +1,18 @@ +package br.org.otus; + +import br.org.otus.model.User; +import br.org.otus.user.api.UserFacade; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; + +public abstract class UserAuthenticationResource extends AuthenticationResource { + + @Inject + private UserFacade userFacade; + + protected User getUser(HttpServletRequest request) { + String userEmail = getUserEmailToken(request); + return userFacade.fetchByEmail(userEmail); + } +} diff --git a/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ActivityExtractionResource.java b/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ActivityExtractionResource.java new file mode 100644 index 000000000..d3e6655a2 --- /dev/null +++ b/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ActivityExtractionResource.java @@ -0,0 +1,135 @@ +package br.org.otus.extraction.rest; + +import br.org.otus.extraction.ActivityExtractionFacade; +import br.org.otus.extraction.SecuredExtraction; +import br.org.otus.rest.Response; +import com.google.gson.internal.LinkedTreeMap; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.ArrayList; + +@Path("data-extraction/activity") +public class ActivityExtractionResource { + + @Inject + private ActivityExtractionFacade activityExtractionFacade; + + + @GET + @SecuredExtraction + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Path("/{acronym}/versions") + public String listSurveyVersions(@PathParam("acronym") String acronym) { + return new Response().buildSuccess(activityExtractionFacade.listSurveyVersions(acronym.toUpperCase())).toJson(); + } + + @GET + @SecuredExtraction + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Path("/{acronym}/{version}/attachments") + public byte[] extractAnnexesReport(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { + return activityExtractionFacade.createAttachmentsReportExtraction(acronym.toUpperCase(), version); + } + + @GET + @SecuredExtraction + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Path("/progress/{center}") + public byte[] extractActivitiesProgress(@PathParam("center") String center) { + return activityExtractionFacade.createActivityProgressExtraction(center); + } + + @POST + @SecuredExtraction + @Path("/attachments") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + public javax.ws.rs.core.Response fetch(ArrayList oids) { + javax.ws.rs.core.Response.ResponseBuilder builder = javax.ws.rs.core.Response.ok(activityExtractionFacade.downloadFiles(oids)); + builder.header("Content-Disposition", "attachment; filename=" + "file-extraction.zip"); + return builder.build(); + } + + + @PUT + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/{id}") + public String createOrUpdateActivityExtraction(@PathParam("id") String activityId) { + activityExtractionFacade.createOrUpdateActivityExtraction(activityId); + return new Response().buildSuccess().toJson(); + } + + @DELETE + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/{id}") + public String deleteActivityExtraction(@PathParam("id") String activityId) { + activityExtractionFacade.deleteActivityExtraction(activityId); + return new Response().buildSuccess().toJson(); + } + + @PUT + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/sync/{acronym}/{version}") + public String syncSurveyExtractions(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { + activityExtractionFacade.synchronizeSurveyActivityExtractions(acronym, version); + return new Response().buildSuccess().toJson(); + } + + @PUT + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/sync-force/{acronym}/{version}") + public String forceSyncSurveyExtractions(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { + activityExtractionFacade.forceSynchronizeSurveyActivityExtractions(acronym, version); + return new Response().buildSuccess().toJson(); + } + + @PUT + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/force/{id}") + public String forceCreateOrUpdateActivityExtraction(@PathParam("id") String activityId) { + activityExtractionFacade.forceCreateOrUpdateActivityExtraction(activityId); + return new Response().buildSuccess().toJson(); + } + + @GET + @SecuredExtraction + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Path("/{acronym}/{version}") + public byte[] getSurveyActivitiesExtractionAsCsv(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { + return activityExtractionFacade.getSurveyActivitiesExtractionAsCsv(acronym, version); + } + + @GET + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/json/{acronym}/{version}") + public String getSurveyActivitiesExtractionAsJson(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { + ArrayList json = activityExtractionFacade.getSurveyActivitiesExtractionAsJson(acronym, version); + return new Response().buildSuccess(json).toJson(); + } + + @POST + @SecuredExtraction + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Path("/rscript/csv") + public byte[] getRscriptSurveyExtractionAsCsv(String rscriptSurveyExtractionJson) { + return activityExtractionFacade.getRscriptSurveyExtractionAsCsv(rscriptSurveyExtractionJson); + } + + @POST + @SecuredExtraction + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/rscript/json") + public String getRscriptSurveyExtractionAsJson(String rscriptSurveyExtractionJson) { + return activityExtractionFacade.getRscriptSurveyExtractionAsJson(rscriptSurveyExtractionJson); + } +} diff --git a/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ExtractionResource.java b/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ExtractionResource.java index 491e9866c..fcf6efa42 100644 --- a/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ExtractionResource.java +++ b/source/otus-rest/src/main/java/br/org/otus/extraction/rest/ExtractionResource.java @@ -28,22 +28,6 @@ public class ExtractionResource { @Inject private SecurityContext securityContext; - @GET - @SecuredExtraction - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Path("/activity/{acronym}/{version}") - public byte[] extractActivities(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { - return extractionFacade.createActivityExtraction(acronym.toUpperCase(), version); - } - - @GET - @SecuredExtraction - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Path("/activity/{acronym}/versions") - public String listSurveyVersions(@PathParam("acronym") String acronym) { - return new Response().buildSuccess(extractionFacade.listSurveyVersions(acronym.toUpperCase())).toJson(); - } - @GET @SecuredExtraction @Produces(MediaType.APPLICATION_OCTET_STREAM) @@ -68,22 +52,6 @@ public byte[] extractParticipant() { return extractionFacade.createParticipantExtraction(); } - @GET - @SecuredExtraction - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Path("/activity/{acronym}/{version}/attachments") - public byte[] extractAnnexesReport(@PathParam("acronym") String acronym, @PathParam("version") Integer version) { - return extractionFacade.createAttachmentsReportExtraction(acronym.toUpperCase(), version); - } - - @GET - @SecuredExtraction - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Path("/activity/progress/{center}") - public byte[] extractActivitiesProgress(@PathParam("center") String center) { - return extractionFacade.createActivityProgressExtraction(center); - } - @POST @Secured @Path("/enable") @@ -114,17 +82,6 @@ public String enableIps(ManagementUserDto managementUserDto) { return new Response().buildSuccess().toJson(); } - @POST - @SecuredExtraction - @Path("/activity/attachments") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_OCTET_STREAM) - public javax.ws.rs.core.Response fetch(ArrayList oids) { - javax.ws.rs.core.Response.ResponseBuilder builder = javax.ws.rs.core.Response.ok(extractionFacade.downloadFiles(oids)); - builder.header("Content-Disposition", "attachment; filename=" + "file-extraction.zip"); - return builder.build(); - } - @GET @Secured @Path("/extraction-token") @@ -136,41 +93,6 @@ public String getToken(@Context HttpServletRequest request) { return new Response().buildSuccess(extractionToken).toJson(); } - @GET - @SecuredExtraction - @Produces(MediaType.APPLICATION_JSON) - @Path("/pipeline/{pipeline}") - public byte[] extractFromPipeline(@PathParam("pipeline") String pipelineName) { - return extractionFacade.createExtractionFromPipeline(pipelineName); - } - - @POST - @SecuredExtraction - @Produces(MediaType.APPLICATION_JSON) - @Path("/activity/{id}") - public String createActivityExtraction(@PathParam("id") String activityId) { - extractionFacade.createActivityExtraction(activityId); - return new Response().buildSuccess().toJson(); - } - - @PUT - @SecuredExtraction - @Produces(MediaType.APPLICATION_JSON) - @Path("/activity/{id}") - public String updateActivityExtraction(@PathParam("id") String activityId) { - extractionFacade.updateActivityExtraction(activityId); - return new Response().buildSuccess().toJson(); - } - - @DELETE - @SecuredExtraction - @Produces(MediaType.APPLICATION_JSON) - @Path("/activity/{id}") - public String deleteActivityExtraction(@PathParam("id") String activityId) { - extractionFacade.deleteActivityExtraction(activityId); - return new Response().buildSuccess().toJson(); - } - @GET @SecuredExtraction @Produces(MediaType.APPLICATION_OCTET_STREAM) diff --git a/source/otus-rest/src/main/java/br/org/otus/extraction/rest/RscriptResource.java b/source/otus-rest/src/main/java/br/org/otus/extraction/rest/RscriptResource.java new file mode 100644 index 000000000..2097208a0 --- /dev/null +++ b/source/otus-rest/src/main/java/br/org/otus/extraction/rest/RscriptResource.java @@ -0,0 +1,42 @@ +package br.org.otus.extraction.rest; + +import br.org.otus.extraction.RscriptFacade; +import br.org.otus.extraction.SecuredExtraction; +import br.org.otus.rest.Response; + +import javax.inject.Inject; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +@Path("data-extraction/rscript") +public class RscriptResource { + + @Inject + private RscriptFacade rscriptFacade; + + @PUT + @SecuredExtraction + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String createOrUpdate(String rscriptJson) { + rscriptFacade.createOrUpdate(rscriptJson); + return new Response().buildSuccess().toJson(); + } + + @GET + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/{name}") + public String get(@PathParam("name") String rscriptName) { + return new Response().buildSuccess(rscriptFacade.get(rscriptName)).toJson(); + } + + @DELETE + @SecuredExtraction + @Produces(MediaType.APPLICATION_JSON) + @Path("/{name}") + public String delete(@PathParam("name") String rscriptName) { + rscriptFacade.delete(rscriptName); + return new Response().buildSuccess().toJson(); + } +} diff --git a/source/otus-rest/src/main/java/br/org/otus/participant/NoteAboutParticipantResource.java b/source/otus-rest/src/main/java/br/org/otus/participant/NoteAboutParticipantResource.java new file mode 100644 index 000000000..53491b5e4 --- /dev/null +++ b/source/otus-rest/src/main/java/br/org/otus/participant/NoteAboutParticipantResource.java @@ -0,0 +1,66 @@ +package br.org.otus.participant; + +import br.org.otus.UserAuthenticationResource; +import br.org.otus.participant.api.NoteAboutParticipantFacade; +import br.org.otus.rest.Response; +import br.org.otus.security.user.Secured; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; + +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; + +@Path("participant/note-about") +public class NoteAboutParticipantResource extends UserAuthenticationResource { + + @Inject + private NoteAboutParticipantFacade noteAboutParticipantFacade; + + @POST + @Secured + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String create(@Context HttpServletRequest request, String noteAboutParticipantJson){ + String id = noteAboutParticipantFacade.create(getUser(request), noteAboutParticipantJson); + return new Response().buildSuccess(id).toJson(); + } + + @PUT + @Secured + @Consumes(MediaType.APPLICATION_JSON) + public String update(@Context HttpServletRequest request, String noteAboutParticipantJson){ + noteAboutParticipantFacade.update(getUser(request), noteAboutParticipantJson); + return new Response().buildSuccess().toJson(); + } + + @PUT + @Secured + @Path("/update-starred/{id}/{starred}") + @Consumes(MediaType.APPLICATION_JSON) + public String updateStarred(@Context HttpServletRequest request, @PathParam("id") String noteAboutParticipantId, @PathParam("starred") Boolean starred){ + noteAboutParticipantFacade.updateStarred(getUser(request), noteAboutParticipantId, starred); + return new Response().buildSuccess().toJson(); + } + + @DELETE + @Secured + @Path("/{id}") + public String delete(@Context HttpServletRequest request, @PathParam("id") String noteAboutParticipantId){ + noteAboutParticipantFacade.delete(getUser(request), noteAboutParticipantId); + return new Response().buildSuccess().toJson(); + } + + @POST + @Secured + @Path("/{rn}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public String getAll(@Context HttpServletRequest request, @PathParam("rn") Long recruitmentNumber, String searchSettingsDtoJson){ + return new Response().buildSuccess( + noteAboutParticipantFacade.getAll(getUser(request), recruitmentNumber, searchSettingsDtoJson) + ).toJson(NoteAboutParticipantResponse.getFrontGsonBuilder()); + } + +} diff --git a/source/otus-rest/src/main/java/br/org/otus/rest/EndPointsLoader.java b/source/otus-rest/src/main/java/br/org/otus/rest/EndPointsLoader.java index 2738eef9a..9a90297fe 100644 --- a/source/otus-rest/src/main/java/br/org/otus/rest/EndPointsLoader.java +++ b/source/otus-rest/src/main/java/br/org/otus/rest/EndPointsLoader.java @@ -7,7 +7,9 @@ import br.org.otus.configuration.survey.SurveyResource; import br.org.otus.configuration.visual.VisualIdentityResource; import br.org.otus.examUploader.ExamUploadResource; +import br.org.otus.extraction.rest.ActivityExtractionResource; import br.org.otus.extraction.rest.ExtractionResource; +import br.org.otus.extraction.rest.RscriptResource; import br.org.otus.fieldCenter.FieldCenterResource; import br.org.otus.fileuploader.FileUploaderResource; import br.org.otus.importation.ActivityImportationResource; @@ -21,6 +23,7 @@ import br.org.otus.monitoring.MonitoringResource; import br.org.otus.outcomes.configuration.FollowUpConfiguration; import br.org.otus.outcomes.configuration.FollowUpEventConfiguration; +import br.org.otus.participant.NoteAboutParticipantResource; import br.org.otus.participant.ParticipantContactAttemptResource; import br.org.otus.participant.ParticipantContactResource; import br.org.otus.participant.ParticipantResource; @@ -174,6 +177,15 @@ public class EndPointsLoader extends Application { @Inject private StageResource stageResource; + @Inject + private ActivityExtractionResource activityExtractionResource; + + @Inject + private RscriptResource rscriptResource; + + @Inject + private NoteAboutParticipantResource noteAboutParticipantResource; + @Override public Set> getClasses() { Set> resources = new HashSet>(); @@ -217,6 +229,9 @@ public Set> getClasses() { resources.add(MessageCommunicationResource.class); resources.add(ActivitySharingResource.class); resources.add(StageResource.class); + resources.add(ActivityExtractionResource.class); + resources.add(RscriptResource.class); + resources.add(NoteAboutParticipantResource.class); return resources; } @@ -265,6 +280,9 @@ public Set getSingletons() { resources.add(messageCommunicationResource); resources.add(activitySharingResource); resources.add(stageResource); + resources.add(activityExtractionResource); + resources.add(rscriptResource); + resources.add(noteAboutParticipantResource); return resources; } diff --git a/source/otus-rest/src/main/java/br/org/otus/security/user/AuthenticationFilter.java b/source/otus-rest/src/main/java/br/org/otus/security/user/AuthenticationFilter.java index e447204d3..f57e97b7a 100644 --- a/source/otus-rest/src/main/java/br/org/otus/security/user/AuthenticationFilter.java +++ b/source/otus-rest/src/main/java/br/org/otus/security/user/AuthenticationFilter.java @@ -31,6 +31,8 @@ public class AuthenticationFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext containerRequestContext) { + final String ACTIVITIES = "activities"; + final String ID = "id"; String authorizationHeader = containerRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION); try { String token = AuthorizationHeaderReader.readToken(authorizationHeader); @@ -48,7 +50,11 @@ public void filter(ContainerRequestContext containerRequestContext) { break; case ACTIVITY_SHARING: - securityFacade.validateActivitySharingToken(AuthorizationHeaderReader.readToken(authorizationHeader)); + String activityId = ""; + if(containerRequestContext.getUriInfo().getPathSegments().get(0).getPath().equals(ACTIVITIES)){ + activityId = containerRequestContext.getUriInfo().getPathParameters().getFirst(ID); + } + securityFacade.validateActivitySharingToken(AuthorizationHeaderReader.readToken(authorizationHeader), activityId); break; default: diff --git a/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ActivityExtractionResourceTest.java b/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ActivityExtractionResourceTest.java new file mode 100644 index 000000000..19975e105 --- /dev/null +++ b/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ActivityExtractionResourceTest.java @@ -0,0 +1,116 @@ +package br.org.otus.extraction.rest; + +import br.org.otus.ResourceTestsParent; +import br.org.otus.extraction.ActivityExtractionFacade; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +import javax.ws.rs.core.Response; +import java.util.ArrayList; + +import static org.junit.Assert.assertEquals; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +public class ActivityExtractionResourceTest extends ResourceTestsParent { + + private static final String ACRONYM = "ANTC"; + private static final Integer VERSION = 1; + private static final String CENTER = "RS"; + private static final String ACTIVITY_ID = "5e0658135b4ff40f8916d2b6"; + private static final String SURVEY_EXTRACTION_JSON = "{}"; + private static final byte[] BYTES = new byte[1]; + + @InjectMocks + private ActivityExtractionResource activityExtractionResource; + @Mock + private ActivityExtractionFacade activityExtractionFacade; + + + @Test + public void listSurveyVersions_method_should_verify_method_listSurveyVersions_have_been_called() { + activityExtractionResource.listSurveyVersions(ACRONYM); + Mockito.verify(activityExtractionFacade).listSurveyVersions(ACRONYM); + } + + @Test + public void extractAnnexesReport_method_should_verify_method_extractAnnexesReport_have_been_called() { + activityExtractionResource.extractAnnexesReport(ACRONYM, VERSION); + Mockito.verify(activityExtractionFacade).createAttachmentsReportExtraction(ACRONYM, VERSION); + } + + @Test + public void extractActivitiesProgress_method_should_call_createActivityProgressExtraction_method() { + activityExtractionResource.extractActivitiesProgress(CENTER); + Mockito.verify(activityExtractionFacade).createActivityProgressExtraction(CENTER); + } + + @Test + public void fetch_method_should_call_userFacade_updateExtractionIps_method() { + final ArrayList OIDs = new ArrayList<>(); + when(activityExtractionFacade.downloadFiles(OIDs)).thenReturn(BYTES); + Response response = activityExtractionResource.fetch(OIDs); + Mockito.verify(activityExtractionFacade).downloadFiles(OIDs); + assertEquals(SUCCESS_STATUS, response.getStatus()); + } + + + @Test + public void createOrUpdateActivityExtraction_method_should_call_facade_createOrUpdateActivityExtraction_method() { + activityExtractionResource.createOrUpdateActivityExtraction(ACTIVITY_ID); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).createOrUpdateActivityExtraction(ACTIVITY_ID); + } + + @Test + public void deleteActivityExtraction_method_should_call_facade_deleteActivityExtraction_method() { + activityExtractionResource.deleteActivityExtraction(ACTIVITY_ID); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).deleteActivityExtraction(ACTIVITY_ID); + } + + @Test + public void syncSurveyExtractions_method_should_call_facade_deleteActivityExtraction_method() { + activityExtractionResource.syncSurveyExtractions(ACRONYM, VERSION); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).synchronizeSurveyActivityExtractions(ACRONYM, VERSION); + } + + @Test + public void forceSyncSurveyExtractions_method_should_call_facade_deleteActivityExtraction_method() { + activityExtractionResource.forceSyncSurveyExtractions(ACRONYM, VERSION); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).forceSynchronizeSurveyActivityExtractions(ACRONYM, VERSION); + } + + @Test + public void forceCreateOrUpdateActivityExtraction_method_should_call_facade_forceCreateOrUpdateActivityExtraction_method() { + activityExtractionResource.forceCreateOrUpdateActivityExtraction(ACTIVITY_ID); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).forceCreateOrUpdateActivityExtraction(ACTIVITY_ID); + } + + @Test + public void getSurveyActivitiesExtractionAsCsv_method_should_call_facade_getSurveyActivitiesExtractionAsCsv_method() { + activityExtractionResource.getSurveyActivitiesExtractionAsCsv(ACRONYM, VERSION); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).getSurveyActivitiesExtractionAsCsv(ACRONYM, VERSION); + } + + @Test + public void getSurveyActivitiesExtractionAsJson_method_should_call_facade_getSurveyActivitiesExtractionAsJson_method() { + activityExtractionResource.getSurveyActivitiesExtractionAsJson(ACRONYM, VERSION); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).getSurveyActivitiesExtractionAsJson(ACRONYM, VERSION); + } + + @Test + public void getRscriptSurveyExtractionAsCsv_method_should_call_facade_getRscriptSurveyExtractionAsCsv_method() { + activityExtractionResource.getRscriptSurveyExtractionAsCsv(SURVEY_EXTRACTION_JSON); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).getRscriptSurveyExtractionAsCsv(SURVEY_EXTRACTION_JSON); + } + + @Test + public void getRscriptSurveyExtractionAsJson_method_should_call_facade_getRscriptSurveyExtractionAsJson_method() { + activityExtractionResource.getRscriptSurveyExtractionAsJson(SURVEY_EXTRACTION_JSON); + Mockito.verify(activityExtractionFacade, Mockito.times(1)).getRscriptSurveyExtractionAsJson(SURVEY_EXTRACTION_JSON); + } + +} diff --git a/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ExtractionResourceTest.java b/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ExtractionResourceTest.java index a2c626c9c..ebbae48e3 100644 --- a/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ExtractionResourceTest.java +++ b/source/otus-rest/src/test/java/br/org/otus/extraction/rest/ExtractionResourceTest.java @@ -3,7 +3,6 @@ import br.org.otus.AuthenticationResourceTestsParent; import br.org.otus.security.AuthorizationHeaderReader; import br.org.otus.user.dto.ManagementUserDto; -import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -16,22 +15,13 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import javax.ws.rs.core.Response; -import java.util.ArrayList; - import static org.junit.Assert.assertEquals; -import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({AuthorizationHeaderReader.class, javax.ws.rs.core.Response.class}) public class ExtractionResourceTest extends AuthenticationResourceTestsParent { - private static final String ACRONYM = "ANTC"; - private static final Integer VERSION = 1; - private static final String CENTER = "RS"; private static final String EXTRACTION_TOKEN = "123"; - private static final String PIPELINE_NAME = "pipeline"; - private static final byte[] BYTES = new byte[1]; @InjectMocks private ExtractionResource extractionResource; @@ -40,28 +30,10 @@ public class ExtractionResourceTest extends AuthenticationResourceTestsParent { private UserFacade userFacade; @Mock private ExtractionFacade extractionFacade; - @Mock private ManagementUserDto managementUserDto; - @Before - public void setUp() { - PowerMockito.when(extractionFacade.createActivityExtraction(ACRONYM, VERSION)).thenReturn(null); - } - - @Test - public void extractActivities_method_should_verify_method_createActivityExtraction_have_been_called() { - extractionResource.extractActivities(ACRONYM, VERSION); - Mockito.verify(extractionFacade).createActivityExtraction(ACRONYM, VERSION); - } - - @Test - public void listSurveyVersions_method_should_verify_method_listSurveyVersions_have_been_called() { - extractionResource.listSurveyVersions(ACRONYM); - Mockito.verify(extractionFacade).listSurveyVersions(ACRONYM); - } - @Test public void extractExamsValues_method_should_verify_method_extractExamsValues_have_been_called() { extractionResource.extractExamsValues(); @@ -74,18 +46,6 @@ public void extractLaboratory_method_should_call_createLaboratoryExtraction_meth Mockito.verify(extractionFacade).createLaboratoryExtraction(); } - @Test - public void extractAnnexesReport_method_should_verify_method_extractAnnexesReport_have_been_called() { - extractionResource.extractAnnexesReport(ACRONYM, VERSION); - Mockito.verify(extractionFacade).createAttachmentsReportExtraction(ACRONYM, VERSION); - } - - @Test - public void extractActivitiesProgress_method_should_call_createActivityProgressExtraction_method() { - extractionResource.extractActivitiesProgress(CENTER); - Mockito.verify(extractionFacade).createActivityProgressExtraction(CENTER); - } - @Test public void enableUsers_method_should_call_userFacade_enableExtraction_method() { String response = extractionResource.enableUsers(managementUserDto); @@ -107,15 +67,6 @@ public void enableIps_method_should_call_userFacade_updateExtractionIps_method() assertEquals(EMPTY_RESPONSE, response); } - @Test - public void fetch_method_should_call_userFacade_updateExtractionIps_method() { - final ArrayList OIDs = new ArrayList<>(); - when(extractionFacade.downloadFiles(OIDs)).thenReturn(BYTES); - Response response = extractionResource.fetch(OIDs); - Mockito.verify(extractionFacade).downloadFiles(OIDs); - assertEquals(SUCCESS_STATUS, response.getStatus()); - } - @Test public void getToken_method_should_call_userFacade_getExtractionToken_method() { mockContextToSetUserEmail(); @@ -125,10 +76,4 @@ public void getToken_method_should_call_userFacade_getExtractionToken_method() { assertEquals(encapsulateExpectedStringResponse(EXTRACTION_TOKEN), response); } - @Test - public void extractFromPipeline_method_should_call_createExtractionFromPipeline_method() { - extractionResource.extractFromPipeline(PIPELINE_NAME); - Mockito.verify(extractionFacade).createExtractionFromPipeline(PIPELINE_NAME); - } - } diff --git a/source/otus-rest/src/test/java/br/org/otus/extraction/rest/RscriptResourceTest.java b/source/otus-rest/src/test/java/br/org/otus/extraction/rest/RscriptResourceTest.java new file mode 100644 index 000000000..3776cce7a --- /dev/null +++ b/source/otus-rest/src/test/java/br/org/otus/extraction/rest/RscriptResourceTest.java @@ -0,0 +1,40 @@ +package br.org.otus.extraction.rest; + +import br.org.otus.extraction.RscriptFacade; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class RscriptResourceTest { + + private static final String R_SCRIPT_JSON = "{}"; + private static final String R_SCRIPT_NAME = "script"; + + @InjectMocks + private RscriptResource rscriptResource; + + @Mock + private RscriptFacade rscriptFacade; + + @Test + public void createOrUpdate_method_should_call_same_method_from_RscriptFacade(){ + rscriptResource.createOrUpdate(R_SCRIPT_JSON); + Mockito.verify(rscriptFacade, Mockito.times(1)).createOrUpdate(R_SCRIPT_JSON); + } + + @Test + public void get_method_should_call_same_method_from_RscriptFacade(){ + rscriptResource.get(R_SCRIPT_NAME); + Mockito.verify(rscriptFacade, Mockito.times(1)).get(R_SCRIPT_NAME); + } + + @Test + public void delete_method_should_call_same_method_from_RscriptFacade(){ + rscriptResource.delete(R_SCRIPT_NAME); + Mockito.verify(rscriptFacade, Mockito.times(1)).delete(R_SCRIPT_NAME); + } +} diff --git a/source/otus-rest/src/test/java/br/org/otus/participant/NoteAboutParticipantResourceTest.java b/source/otus-rest/src/test/java/br/org/otus/participant/NoteAboutParticipantResourceTest.java new file mode 100644 index 000000000..d143f9683 --- /dev/null +++ b/source/otus-rest/src/test/java/br/org/otus/participant/NoteAboutParticipantResourceTest.java @@ -0,0 +1,88 @@ +package br.org.otus.participant; + +import br.org.otus.participant.api.NoteAboutParticipantFacade; +import br.org.otus.security.AuthorizationHeaderReader; +import br.org.otus.user.UserAuthenticationResourceTestsParent; +import org.ccem.otus.participant.model.noteAboutParticipant.NoteAboutParticipantResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.verify; +import static org.powermock.api.mockito.PowerMockito.doReturn; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AuthorizationHeaderReader.class}) +public class NoteAboutParticipantResourceTest extends UserAuthenticationResourceTestsParent { + + private static final String NOTE_ABOUT_PARTICIPANT_ID = "123"; + private static final String NOTE_ABOUT_PARTICIPANT_JSON = "{}"; + private static final Boolean STARRED = true; + private static final Long RECRUITMENT_NUMBER = 1234567L; + private static final String SEARCH_SETTINGS_JSON = "{}"; + + @InjectMocks + private NoteAboutParticipantResource resource; + + @Mock + private NoteAboutParticipantFacade facade; + + + @Before + public void setUp(){ + mockContextAndUser(); + } + + @Test + public void create_method_should_call_facade_create_method(){ + doReturn(NOTE_ABOUT_PARTICIPANT_ID).when(facade).create(user, NOTE_ABOUT_PARTICIPANT_JSON); + assertEquals( + encapsulateExpectedStringResponse(NOTE_ABOUT_PARTICIPANT_ID), + resource.create(request, NOTE_ABOUT_PARTICIPANT_JSON)); + verify(facade, Mockito.times(1)).create(user, NOTE_ABOUT_PARTICIPANT_JSON); + } + + @Test + public void update_method_should_call_update_facade_method(){ + assertEquals( + EMPTY_RESPONSE, + resource.update(request, NOTE_ABOUT_PARTICIPANT_JSON)); + verify(facade, Mockito.times(1)).update(user, NOTE_ABOUT_PARTICIPANT_JSON); + } + + @Test + public void updateStarred_method_should_call_facade_updateStarred_method(){ + assertEquals( + EMPTY_RESPONSE, + resource.updateStarred(request, NOTE_ABOUT_PARTICIPANT_ID, STARRED)); + verify(facade, Mockito.times(1)).updateStarred(user, NOTE_ABOUT_PARTICIPANT_ID, STARRED); + } + + @Test + public void delete_method_should_call_facade_delete_method(){ + assertEquals( + EMPTY_RESPONSE, + resource.delete(request, NOTE_ABOUT_PARTICIPANT_ID)); + verify(facade, Mockito.times(1)).delete(user, NOTE_ABOUT_PARTICIPANT_ID); + } + + @Test + public void getAll_method_should_call_getAll_facade_method(){ + List noteResponses = new ArrayList<>(); + doReturn(noteResponses).when(facade).getAll(user, RECRUITMENT_NUMBER, SEARCH_SETTINGS_JSON); + assertEquals( + encapsulateExpectedResponse(noteResponses.toString()), + resource.getAll(request, RECRUITMENT_NUMBER, SEARCH_SETTINGS_JSON)); + verify(facade, Mockito.times(1)).getAll(user, RECRUITMENT_NUMBER, SEARCH_SETTINGS_JSON); + } + +} diff --git a/source/otus-rest/src/test/java/br/org/otus/rest/EndPointsLoaderTest.java b/source/otus-rest/src/test/java/br/org/otus/rest/EndPointsLoaderTest.java index 89deeec0c..092f63893 100644 --- a/source/otus-rest/src/test/java/br/org/otus/rest/EndPointsLoaderTest.java +++ b/source/otus-rest/src/test/java/br/org/otus/rest/EndPointsLoaderTest.java @@ -5,7 +5,9 @@ import java.util.HashSet; import java.util.Set; +import br.org.otus.extraction.rest.ActivityExtractionResource; import br.org.otus.importation.ActivityImportationResource; +import br.org.otus.participant.NoteAboutParticipantResource; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -91,6 +93,10 @@ public class EndPointsLoaderTest { private ActivityPermissionResource activityAccessPermissionResource; @Mock private UserPermissionResource userPermissionResource; + @Mock + private ActivityExtractionResource activityExtractionResource; + @Mock + private NoteAboutParticipantResource noteAboutParticipantResource; @Test public void getClassesMetods_should_check_the_presence_of_classes_within_the_list() { @@ -121,6 +127,8 @@ public void getClassesMetods_should_check_the_presence_of_classes_within_the_lis assertTrue(resourcesClasses.contains(ProjectConfigurationResource.class)); assertTrue(resourcesClasses.contains(ActivityPermissionResource.class)); assertTrue(resourcesClasses.contains(UserPermissionResource.class)); + assertTrue(resourcesClasses.contains(ActivityExtractionResource.class)); + assertTrue(resourcesClasses.contains(NoteAboutParticipantResource.class)); } @Test @@ -151,5 +159,7 @@ public void getSingletons() { assertTrue(resourcesSingletons.contains(projectConfigurationResource)); assertTrue(resourcesSingletons.contains(activityAccessPermissionResource)); assertTrue(resourcesSingletons.contains(userPermissionResource)); + assertTrue(resourcesSingletons.contains(activityExtractionResource)); + assertTrue(resourcesSingletons.contains(noteAboutParticipantResource)); } } diff --git a/source/otus-rest/src/test/java/br/org/otus/security/user/rest/AuthenticationResourceTest.java b/source/otus-rest/src/test/java/br/org/otus/security/user/rest/AuthenticationResourceTest.java index fafdf292c..1811965e7 100644 --- a/source/otus-rest/src/test/java/br/org/otus/security/user/rest/AuthenticationResourceTest.java +++ b/source/otus-rest/src/test/java/br/org/otus/security/user/rest/AuthenticationResourceTest.java @@ -51,7 +51,7 @@ public class AuthenticationResourceTest { private ProjectAuthenticationDto projectAuthenticationDto; @Before - public void setUp() throws Exception { + public void setUp() { mockStatic(EncryptorResources.class); authenticationDto = new AuthenticationDto(); authenticationDto.setEmail(AUTHENTICATION_DTO_EMAIL); @@ -77,8 +77,7 @@ public void method_Authenticate_should_throw_EncryptedException() throws Encrypt } @Test - public void method_projectAuthenticate_should_return_response_JWT() - throws TokenException, AuthenticationException, JOSEException { + public void method_projectAuthenticate_should_return_response_JWT() { String responseJWTExpected = response.buildSuccess(JWT).toJson(); when(securityFacade.projectAuthentication(projectAuthenticationDto, request.getRemoteAddr().toString())) .thenReturn(JWT); diff --git a/source/otus-rest/src/test/java/br/org/otus/user/UserAuthenticationResourceTestsParent.java b/source/otus-rest/src/test/java/br/org/otus/user/UserAuthenticationResourceTestsParent.java new file mode 100644 index 000000000..416a49c56 --- /dev/null +++ b/source/otus-rest/src/test/java/br/org/otus/user/UserAuthenticationResourceTestsParent.java @@ -0,0 +1,24 @@ +package br.org.otus.user; + +import br.org.otus.AuthenticationResourceTestsParent; +import br.org.otus.model.User; +import br.org.otus.user.api.UserFacade; +import org.mockito.Mock; + +import static org.powermock.api.mockito.PowerMockito.doReturn; + +public abstract class UserAuthenticationResourceTestsParent extends AuthenticationResourceTestsParent { + + @Mock + protected UserFacade userFacade; + @Mock + protected User user; + + protected void mockContextAndUser(){ + /* + Must add in child class: @PrepareForTest({AuthorizationHeaderReader.class}) + */ + mockContextToSetUserEmail(); + doReturn(user).when(userFacade).fetchByEmail(USER_EMAIL); + } +} diff --git a/source/otus-root/pom.xml b/source/otus-root/pom.xml index cfd3dc002..0cca175a5 100644 --- a/source/otus-root/pom.xml +++ b/source/otus-root/pom.xml @@ -3,7 +3,7 @@ 4.0.0 org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 pom otus-api diff --git a/source/otus-user/pom.xml b/source/otus-user/pom.xml index f5547ca2d..03446082b 100644 --- a/source/otus-user/pom.xml +++ b/source/otus-user/pom.xml @@ -7,7 +7,7 @@ org.ccem.otus otus-root - 1.52.0-SNAPSHOT + 1.52.0 ../otus-root/pom.xml