Search in sources :

Example 21 with BridgeServiceException

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

the class StudyConsentService method addConsent.

/**
 * Adds a new consent document to the study, and sets that consent document as active.
 *
 * @param subpopGuid
 *            the subpopulation associated with this consent
 * @param form
 *            form filled out by researcher including the path to the consent document and the minimum age required
 *            to consent.
 * @return the added consent document of type StudyConsent along with its document content
 */
public StudyConsentView addConsent(SubpopulationGuid subpopGuid, StudyConsentForm form) {
    checkNotNull(subpopGuid);
    checkNotNull(form);
    String sanitizedContent = sanitizeHTML(form.getDocumentContent());
    Validate.entityThrowingException(validator, new StudyConsentForm(sanitizedContent));
    sanitizedContent = appendSignatureBlockIfNeeded(sanitizedContent);
    long createdOn = DateUtils.getCurrentMillisFromEpoch();
    String storagePath = subpopGuid.getGuid() + "." + createdOn;
    logger.info("Accessing bucket: " + consentsBucket + " with storagePath: " + storagePath);
    try {
        Stopwatch stopwatch = Stopwatch.createStarted();
        s3Helper.writeBytesToS3(consentsBucket, storagePath, sanitizedContent.getBytes(defaultCharset()));
        logger.info("Finished writing consent to bucket " + consentsBucket + " storagePath " + storagePath + " (" + sanitizedContent.length() + " chars) in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
        StudyConsent consent = studyConsentDao.addConsent(subpopGuid, storagePath, createdOn);
        return new StudyConsentView(consent, sanitizedContent);
    } catch (Throwable t) {
        throw new BridgeServiceException(t);
    }
}
Also used : StudyConsent(org.sagebionetworks.bridge.models.subpopulations.StudyConsent) StudyConsentView(org.sagebionetworks.bridge.models.subpopulations.StudyConsentView) Stopwatch(com.google.common.base.Stopwatch) BridgeServiceException(org.sagebionetworks.bridge.exceptions.BridgeServiceException) StudyConsentForm(org.sagebionetworks.bridge.models.subpopulations.StudyConsentForm)

Example 22 with BridgeServiceException

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

the class ParticipantService method createParticipant.

/**
 * Create a study participant. A password must be provided, even if it is added on behalf of a user before
 * triggering a reset password request.
 */
public IdentifierHolder createParticipant(App app, StudyParticipant participant, boolean shouldSendVerification) {
    checkNotNull(app);
    checkNotNull(participant);
    if (app.getAccountLimit() > 0) {
        throwExceptionIfLimitMetOrExceeded(app);
    }
    StudyParticipantValidator validator = new StudyParticipantValidator(studyService, organizationService, app, true);
    Validate.entityThrowingException(validator, participant);
    // Set basic params from inputs.
    Account account = getAccount();
    account.setId(generateGUID());
    account.setAppId(app.getIdentifier());
    account.setEmail(participant.getEmail());
    account.setPhone(participant.getPhone());
    account.setEmailVerified(FALSE);
    account.setPhoneVerified(FALSE);
    account.setHealthCode(generateGUID());
    account.setStatus(UNVERIFIED);
    // Otherwise this field is ignored on create.
    if (CAN_EDIT_MEMBERS.check(ORG_ID, participant.getOrgMembership())) {
        account.setOrgMembership(participant.getOrgMembership());
    }
    // Hash password if it has been supplied.
    if (participant.getPassword() != null) {
        try {
            PasswordAlgorithm passwordAlgorithm = DEFAULT_PASSWORD_ALGORITHM;
            String passwordHash = passwordAlgorithm.generateHash(participant.getPassword());
            account.setPasswordAlgorithm(passwordAlgorithm);
            account.setPasswordHash(passwordHash);
        } catch (InvalidKeyException | InvalidKeySpecException | NoSuchAlgorithmException ex) {
            throw new BridgeServiceException("Error creating password: " + ex.getMessage(), ex);
        }
    }
    updateAccountAndRoles(app, account, participant, true);
    // enabled unless we need any kind of verification
    boolean sendEmailVerification = shouldSendVerification && app.isEmailVerificationEnabled();
    if (participant.getEmail() != null && !sendEmailVerification) {
        // not verifying, so consider it verified
        account.setEmailVerified(true);
    }
    if (participant.getPhone() != null && !shouldSendVerification) {
        // not verifying, so consider it verified
        account.setPhoneVerified(true);
    }
    account.setSynapseUserId(participant.getSynapseUserId());
    // not save if the account is inaccessible after construction.
    if (BridgeUtils.hasValidIdentifier(account)) {
        accountService.createAccount(app, account);
    }
    // send verify email
    if (sendEmailVerification && !app.isAutoVerificationEmailSuppressed()) {
        accountWorkflowService.sendEmailVerificationToken(app, account.getId(), account.getEmail());
    }
    // If you create an account with a phone number, this opts the phone number in to receiving SMS. We do this
    // _before_ phone verification / sign-in, because we need to opt the user in to SMS in order to send phone
    // verification / sign-in.
    Phone phone = account.getPhone();
    if (phone != null) {
        // Note that there is no object with both accountId and phone, so we need to pass them in separately.
        smsService.optInPhoneNumber(account.getId(), phone);
    }
    // send verify phone number
    if (shouldSendVerification && !app.isAutoVerificationPhoneSuppressed()) {
        accountWorkflowService.sendPhoneVerificationToken(app, account.getId(), phone);
    }
    return new IdentifierHolder(account.getId());
}
Also used : Account(org.sagebionetworks.bridge.models.accounts.Account) IdentifierHolder(org.sagebionetworks.bridge.models.accounts.IdentifierHolder) PasswordAlgorithm(org.sagebionetworks.bridge.models.accounts.PasswordAlgorithm) Phone(org.sagebionetworks.bridge.models.accounts.Phone) BridgeServiceException(org.sagebionetworks.bridge.exceptions.BridgeServiceException) StudyParticipantValidator(org.sagebionetworks.bridge.validators.StudyParticipantValidator) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 23 with BridgeServiceException

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

the class StudyConsentService method publishConsent.

/**
 * Set the specified consent document as active, setting all other consent documents
 * as inactive.
 *
 * @param app
 *            app for this consent
 * @param subpop
 *            the subpopulation associated with this consent
 * @param timestamp
 *            time the consent document was added to the database.
 * @return the activated consent document along with its document content
 */
public StudyConsentView publishConsent(App app, Subpopulation subpop, long timestamp) {
    checkNotNull(app);
    checkNotNull(subpop);
    checkArgument(timestamp > 0, "Timestamp is 0");
    StudyConsent consent = studyConsentDao.getConsent(subpop.getGuid(), timestamp);
    if (consent == null) {
        throw new EntityNotFoundException(StudyConsent.class);
    }
    // Only if we can publish the document, do we mark it as published in the database.
    String documentContent = loadDocumentContent(consent);
    try {
        publishFormatsToS3(app, subpop.getGuid(), documentContent);
        subpop.setPublishedConsentCreatedOn(timestamp);
        subpopService.updateSubpopulation(app, subpop);
    } catch (IOException | DocumentException | XRRuntimeException e) {
        throw new BridgeServiceException(e.getMessage());
    }
    return new StudyConsentView(consent, documentContent);
}
Also used : StudyConsent(org.sagebionetworks.bridge.models.subpopulations.StudyConsent) XRRuntimeException(org.xhtmlrenderer.util.XRRuntimeException) DocumentException(com.lowagie.text.DocumentException) StudyConsentView(org.sagebionetworks.bridge.models.subpopulations.StudyConsentView) BridgeServiceException(org.sagebionetworks.bridge.exceptions.BridgeServiceException) EntityNotFoundException(org.sagebionetworks.bridge.exceptions.EntityNotFoundException) IOException(java.io.IOException)

Example 24 with BridgeServiceException

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

the class StudyConsentService method loadDocumentContent.

private String loadDocumentContent(StudyConsent consent) {
    try {
        Stopwatch stopwatch = Stopwatch.createStarted();
        String content = s3Helper.readS3FileAsString(consentsBucket, consent.getStoragePath());
        logger.info("Finished reading consent from bucket " + consentsBucket + " storagePath " + consent.getStoragePath() + " (" + content.length() + " chars) in " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
        // Add a signature block if this document does not contain one.
        return appendSignatureBlockIfNeeded(content);
    } catch (IOException ioe) {
        logger.error("Failure loading storagePath: " + consent.getStoragePath());
        throw new BridgeServiceException(ioe);
    }
}
Also used : Stopwatch(com.google.common.base.Stopwatch) BridgeServiceException(org.sagebionetworks.bridge.exceptions.BridgeServiceException) IOException(java.io.IOException)

Example 25 with BridgeServiceException

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

the class GBFOrderService method placeOrder.

public void placeOrder(Order order, boolean isTest) {
    String orderXml;
    try {
        orderXml = XML_MAPPER.writeValueAsString(new Order.Orders(Lists.newArrayList(order)));
    } catch (JsonProcessingException e) {
        LOG.error("placeOrder failed to serialize Order XML", e);
        throw new BridgeServiceException(GBF_SERVICE_ERROR_MESSAGE);
    }
    HttpResponse httpResponse = postJson(gbfOrderUrl, gbfApiKey, new PlaceOrderRequest(orderXml, isTest));
    handleGbfHttpStatusErrors(httpResponse);
    PlaceOrderResponse response;
    try {
        response = jsonMapper.readValue(httpResponse.getEntity().getContent(), PlaceOrderResponse.class);
    } catch (IOException e) {
        LOG.error("placeOrder failed to read contents of HttpResponse", e);
        throw new BridgeServiceException(GBF_SERVICE_ERROR_MESSAGE);
    }
    if (!response.success) {
        LOG.warn("placeOrder received error from remote service: {}", response.message);
        throw new BridgeServiceException(GBF_SERVICE_ERROR_MESSAGE);
    }
}
Also used : BridgeServiceException(org.sagebionetworks.bridge.exceptions.BridgeServiceException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

BridgeServiceException (org.sagebionetworks.bridge.exceptions.BridgeServiceException)78 IOException (java.io.IOException)25 Test (org.testng.annotations.Test)21 PersistenceException (javax.persistence.PersistenceException)7 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)6 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 CacheKey (org.sagebionetworks.bridge.cache.CacheKey)5 App (org.sagebionetworks.bridge.models.apps.App)5 AmazonServiceException (com.amazonaws.AmazonServiceException)4 ObjectMetadata (com.amazonaws.services.s3.model.ObjectMetadata)4 EntityNotFoundException (org.sagebionetworks.bridge.exceptions.EntityNotFoundException)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Stopwatch (com.google.common.base.Stopwatch)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 List (java.util.List)3 BadRequestException (org.sagebionetworks.bridge.exceptions.BadRequestException)3 FailedBatch (com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch)2 AmazonS3Exception (com.amazonaws.services.s3.model.AmazonS3Exception)2 SendMessageResult (com.amazonaws.services.sqs.model.SendMessageResult)2 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)2