Search in sources :

Example 1 with BadRequestException

use of org.sagebionetworks.bridge.exceptions.BadRequestException in project BridgeServer2 by Sage-Bionetworks.

the class NotificationsServiceTest method sendNotificationNoRegistration.

@Test
public void sendNotificationNoRegistration() {
    doReturn(Lists.newArrayList()).when(mockRegistrationDao).listRegistrations(HEALTH_CODE);
    NotificationMessage message = getNotificationMessage();
    try {
        service.sendNotificationToUser(TEST_APP_ID, HEALTH_CODE, message);
        fail("Should have thrown exception.");
    } catch (BadRequestException e) {
        assertEquals(e.getMessage(), "Participant has not registered to receive push notifications.");
    }
}
Also used : NotificationMessage(org.sagebionetworks.bridge.models.notifications.NotificationMessage) TestUtils.getNotificationMessage(org.sagebionetworks.bridge.TestUtils.getNotificationMessage) BadRequestException(org.sagebionetworks.bridge.exceptions.BadRequestException) Test(org.testng.annotations.Test)

Example 2 with BadRequestException

use of org.sagebionetworks.bridge.exceptions.BadRequestException in project BridgeServer2 by Sage-Bionetworks.

the class ConsentServiceTest method emailConsentAgreementNoRecipients.

@Test
public void emailConsentAgreementNoRecipients() {
    account.setConsentSignatureHistory(SUBPOP_GUID, ImmutableList.of(CONSENT_SIGNATURE));
    // easiest to test this if we null out the app consent email.
    app.setConsentNotificationEmail(null);
    StudyParticipant noEmail = new StudyParticipant.Builder().copyOf(PARTICIPANT).withEmail(null).build();
    try {
        consentService.resendConsentAgreement(app, SUBPOP_GUID, noEmail);
        fail("Should have thrown an exception");
    } catch (BadRequestException e) {
    }
    verify(sendMailService, never()).sendEmail(any());
}
Also used : BadRequestException(org.sagebionetworks.bridge.exceptions.BadRequestException) StudyParticipant(org.sagebionetworks.bridge.models.accounts.StudyParticipant) Test(org.testng.annotations.Test)

Example 3 with BadRequestException

use of org.sagebionetworks.bridge.exceptions.BadRequestException in project BridgeServer2 by Sage-Bionetworks.

the class GBFOrderServiceTest method getShippingConfirmationsErrorXml.

@Test
public void getShippingConfirmationsErrorXml() throws IOException {
    String errorMessage = "Failed to parse date range";
    String errorXml = "<Response><Error>" + errorMessage + "</Error></Response>";
    ConfirmShippingResponse confirmShippingResponse = new ConfirmShippingResponse(errorXml);
    HttpEntity mockEntity = mock(HttpEntity.class);
    doReturn(IOUtils.toInputStream(jsonMapper.writeValueAsString(confirmShippingResponse), UTF_8)).when(mockEntity).getContent();
    StatusLine mockStatusLine = mock(StatusLine.class);
    doReturn(200).when(mockStatusLine).getStatusCode();
    HttpResponse mockResponse = mock(HttpResponse.class);
    doReturn(mockStatusLine).when(mockResponse).getStatusLine();
    doReturn(mockEntity).when(mockResponse).getEntity();
    doReturn(mockResponse).when(service).postJson(eq(CONFIRMATION_URL), any(), any());
    try {
        service.requestShippingConfirmations(LocalDate.now().minusDays(2), LocalDate.now());
        fail("Exception expected");
    } catch (BadRequestException e) {
        assertEquals(errorMessage, e.getMessage());
    }
    verify(service).postJson(eq(CONFIRMATION_URL), any(), any());
}
Also used : ConfirmShippingResponse(org.sagebionetworks.bridge.models.crc.gbf.external.ConfirmShippingResponse) StatusLine(org.apache.http.StatusLine) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) BadRequestException(org.sagebionetworks.bridge.exceptions.BadRequestException) Test(org.testng.annotations.Test)

Example 4 with BadRequestException

use of org.sagebionetworks.bridge.exceptions.BadRequestException in project BridgeServer2 by Sage-Bionetworks.

the class UploadArchiveService method unzip.

/**
 * <p>
 * Unzips the given stream. For each individual zip entry, this method will call entryNameToOutputStream, passing
 * in the zip entry file name and expecting an OutputStream in which to write the unzipped bytes. It will then call
 * outputStreamFinalizer, allowing the caller to finalize the stream, for example, closing the stream.
 * </p>
 * <p>
 * The caller is responsible for closing any and all streams involved.
 * </p>
 *
 * @param source
 *         input stream of zipped data to unzip
 * @param entryNameToOutpuStream
 *         arg is the zip entry file name, return value is the OutputStream in which to write the unzipped bytes
 * @param outputStreamFinalizer
 *         args are the zip entry file name and the corresponding OutputStream returned by entryNameToOutputStream;
 *         this is where you finalize the stream, eg closing the stream
 */
public void unzip(InputStream source, Function<String, OutputStream> entryNameToOutpuStream, BiConsumer<String, OutputStream> outputStreamFinalizer) {
    // Validate input
    checkNotNull(source);
    checkNotNull(entryNameToOutpuStream);
    checkNotNull(outputStreamFinalizer);
    // Unzip
    Set<String> zipEntryNameSet = new HashSet<>();
    try (ZipInputStream zis = new ZipInputStream(source)) {
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            if (zipEntryNameSet.size() >= maxNumZipEntries) {
                throw new ZipOverflowException("The number of zip entries is over the max allowed");
            }
            final String entryName = zipEntry.getName();
            if (zipEntryNameSet.contains(entryName)) {
                throw new DuplicateZipEntryException("Duplicate filename " + entryName);
            }
            final long entrySize = zipEntry.getSize();
            if (entrySize > maxZipEntrySize) {
                throw new ZipOverflowException("Zip entry size is over the max allowed size. The entry " + entryName + " has size " + entrySize + ". The max allowed size is" + maxZipEntrySize + ".");
            }
            zipEntryNameSet.add(entryName);
            OutputStream outputStream = entryNameToOutpuStream.apply(entryName);
            toByteArray(entryName, zis, outputStream);
            outputStreamFinalizer.accept(entryName, outputStream);
            zipEntry = zis.getNextEntry();
        }
    } catch (DuplicateZipEntryException | ZipOverflowException ex) {
        throw new BadRequestException(ex);
    } catch (IOException ex) {
        throw new BridgeServiceException(ex);
    }
}
Also used : ZipOverflowException(org.sagebionetworks.bridge.util.ZipOverflowException) ZipEntry(java.util.zip.ZipEntry) ZipOutputStream(java.util.zip.ZipOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) BridgeServiceException(org.sagebionetworks.bridge.exceptions.BridgeServiceException) IOException(java.io.IOException) ZipInputStream(java.util.zip.ZipInputStream) DuplicateZipEntryException(org.sagebionetworks.bridge.util.DuplicateZipEntryException) BadRequestException(org.sagebionetworks.bridge.exceptions.BadRequestException) HashSet(java.util.HashSet)

Example 5 with BadRequestException

use of org.sagebionetworks.bridge.exceptions.BadRequestException in project BridgeServer2 by Sage-Bionetworks.

the class UploadSchemaService method createUploadSchemaFromSurvey.

/**
 * <p>
 * Creates an upload schema from a survey. This is generally called when a survey is published, to
 * create the corresponding upload schema, so that health data records can be created from survey responses.
 * This method will also persist the schema to the backing store.
 * <p>
 * If newSchemaRev is true, this method will always create a new schema revision. If false, it will attempt to
 * modify the existing schema revision. However, if the schema revisions are not compatible, it will fall back to
 * creating a new schema revision.
 * </p>
 */
public UploadSchema createUploadSchemaFromSurvey(String appId, Survey survey, boolean newSchemaRev) {
    // https://sagebionetworks.jira.com/browse/BRIDGE-1698 - If the existing Schema ID points to a different survey
    // or a non-survey, this is an error. Having multiple surveys point to the same schema ID causes really bad
    // things to happen, and we need to prevent it.
    String schemaId = survey.getIdentifier();
    UploadSchema oldSchema = getUploadSchemaNoThrow(appId, schemaId);
    if (oldSchema != null) {
        if (oldSchema.getSchemaType() != UploadSchemaType.IOS_SURVEY || !Objects.equals(oldSchema.getSurveyGuid(), survey.getGuid())) {
            throw new BadRequestException("Survey with identifier " + schemaId + " conflicts with schema with the same ID. Please use a different survey identifier.");
        }
    }
    // the same survey.
    if (!newSchemaRev && oldSchema != null) {
        // Check that the old schema already has the answers field.
        List<UploadFieldDefinition> oldFieldDefList = oldSchema.getFieldDefinitions();
        UploadFieldDefinition answersFieldDef = getElement(oldFieldDefList, UploadFieldDefinition::getName, FIELD_ANSWERS).orElse(null);
        if (answersFieldDef == null) {
            // Old schema doesn't have the
            List<UploadFieldDefinition> newFieldDefList = new ArrayList<>(oldFieldDefList);
            newFieldDefList.add(UploadUtil.ANSWERS_FIELD_DEF);
            addSurveySchemaMetadata(oldSchema, survey);
            oldSchema.setFieldDefinitions(newFieldDefList);
            return updateSchemaRevisionV4(appId, schemaId, oldSchema.getRevision(), oldSchema);
        }
        // Answers field needs to be either
        // (a) an attachment (Large Text or normal)
        // (b) a string with isUnboundedLength=true
        UploadFieldType fieldType = answersFieldDef.getType();
        if (fieldType == UploadFieldType.LARGE_TEXT_ATTACHMENT || UploadFieldType.ATTACHMENT_TYPE_SET.contains(fieldType) || (UploadFieldType.STRING_TYPE_SET.contains(fieldType) && Boolean.TRUE.equals(answersFieldDef.isUnboundedText()))) {
            // The old schema works for the new survey. However, we want to ensure the old schema points to the
            // latest version of the survey. Update survey metadata in the schema.
            addSurveySchemaMetadata(oldSchema, survey);
            return updateSchemaRevisionV4(appId, schemaId, oldSchema.getRevision(), oldSchema);
        }
    // If execution gets this far, that means we have a schema with an "answers" field that's not compatible.
    // At this point, we go into the branch that creates a new schema, below.
    }
    // We were unable to reconcile this with the existing schema. Create a new schema. (Create API will
    // automatically bump the rev number if an old schema revision exists.)
    UploadSchema schemaToCreate = UploadSchema.create();
    addSurveySchemaMetadata(schemaToCreate, survey);
    schemaToCreate.setFieldDefinitions(ImmutableList.of(UploadUtil.ANSWERS_FIELD_DEF));
    return createSchemaRevisionV4(appId, schemaToCreate);
}
Also used : UploadFieldDefinition(org.sagebionetworks.bridge.models.upload.UploadFieldDefinition) UploadFieldType(org.sagebionetworks.bridge.models.upload.UploadFieldType) ArrayList(java.util.ArrayList) BadRequestException(org.sagebionetworks.bridge.exceptions.BadRequestException) UploadSchema(org.sagebionetworks.bridge.models.upload.UploadSchema)

Aggregations

BadRequestException (org.sagebionetworks.bridge.exceptions.BadRequestException)104 EntityNotFoundException (org.sagebionetworks.bridge.exceptions.EntityNotFoundException)23 Test (org.testng.annotations.Test)19 UserSession (org.sagebionetworks.bridge.models.accounts.UserSession)17 App (org.sagebionetworks.bridge.models.apps.App)17 DateTime (org.joda.time.DateTime)13 StudyParticipant (org.sagebionetworks.bridge.models.accounts.StudyParticipant)10 Study (org.sagebionetworks.bridge.models.studies.Study)10 ArrayList (java.util.ArrayList)9 Account (org.sagebionetworks.bridge.models.accounts.Account)9 StudyActivityEvent (org.sagebionetworks.bridge.models.activities.StudyActivityEvent)9 PostMapping (org.springframework.web.bind.annotation.PostMapping)9 UploadSchema (org.sagebionetworks.bridge.models.upload.UploadSchema)8 CacheKey (org.sagebionetworks.bridge.cache.CacheKey)7 AccountId (org.sagebionetworks.bridge.models.accounts.AccountId)7 ScheduleContext (org.sagebionetworks.bridge.models.schedules.ScheduleContext)7 List (java.util.List)5 Survey (org.sagebionetworks.bridge.models.surveys.Survey)5 GetMapping (org.springframework.web.bind.annotation.GetMapping)5 Map (java.util.Map)4