public void sendVerificationReminderEmail(OrcidProfile orcidProfile, String email) {
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String primaryEmail =
        orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    templateParams.put("primaryEmail", primaryEmail);
    String emailFriendlyName = deriveEmailFriendlyName(orcidProfile);
    templateParams.put("emailName", emailFriendlyName);
    String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
    templateParams.put("email", email);
    templateParams.put("subject", getSubject("email.subject.verify_reminder", orcidProfile));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body =
        templateManager.processTemplate("verification_reminder_email.ftl", templateParams);
    String htmlBody =
        templateManager.processTemplate("verification_reminder_email_html.ftl", templateParams);
    mailGunManager.sendEmail(
        SUPPORT_VERIFY_ORCID_ORG,
        email,
        getSubject("email.subject.verify_reminder", orcidProfile),
        body,
        htmlBody);
  }
 /** See {@link OrcidApiServiceDelegator}{@link #searchByQuery(Map)} */
 @Override
 @VisibilityControl
 public Response searchByQuery(Map<String, List<String>> queryMap) {
   OrcidMessage orcidMessage = orcidSearchManager.findOrcidsByQuery(queryMap);
   List<OrcidSearchResult> searchResults =
       orcidMessage.getOrcidSearchResults() != null
           ? orcidMessage.getOrcidSearchResults().getOrcidSearchResult()
           : null;
   List<OrcidSearchResult> filteredResults = new ArrayList<OrcidSearchResult>();
   OrcidSearchResults orcidSearchResults = new OrcidSearchResults();
   if (searchResults != null) {
     orcidSearchResults.setNumFound(orcidMessage.getOrcidSearchResults().getNumFound());
     if (searchResults.size() > 0) {
       for (OrcidSearchResult searchResult : searchResults) {
         OrcidSearchResult filteredSearchResult = new OrcidSearchResult();
         OrcidProfile filteredProfile = new OrcidProfile();
         filteredSearchResult.setRelevancyScore(searchResult.getRelevancyScore());
         filteredProfile.setOrcid(searchResult.getOrcidProfile().getOrcid());
         filteredProfile.setOrcidId(searchResult.getOrcidProfile().getOrcidId());
         filteredProfile.setOrcidIdentifier(searchResult.getOrcidProfile().getOrcidIdentifier());
         filteredProfile.setOrcidBio(searchResult.getOrcidProfile().getOrcidBio());
         filteredSearchResult.setOrcidProfile(filteredProfile);
         filteredResults.add(filteredSearchResult);
       }
     }
   }
   orcidSearchResults.getOrcidSearchResult().addAll(filteredResults);
   return getOrcidSearchResultsResponse(orcidSearchResults, queryMap.toString());
 }
  @Override
  public void sendOrcidDeactivateEmail(OrcidProfile orcidToDeactivate) {
    // Create verification url

    Map<String, Object> templateParams = new HashMap<String, Object>();

    String subject = getSubject("email.subject.deactivate", orcidToDeactivate);
    String email =
        orcidToDeactivate.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    String encryptedEmail = encryptionManager.encryptForExternalUse(email);
    String base64EncodedEmail = Base64.encodeBase64URLSafeString(encryptedEmail.getBytes());
    String deactivateUrlEndpointPath = "/account/confirm-deactivate-orcid";

    String emailFriendlyName = deriveEmailFriendlyName(orcidToDeactivate);
    templateParams.put("emailName", emailFriendlyName);
    templateParams.put("orcid", orcidToDeactivate.getOrcidIdentifier().getPath());
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put(
        "deactivateUrlEndpoint", deactivateUrlEndpointPath + "/" + base64EncodedEmail);
    templateParams.put("deactivateUrlEndpointUrl", deactivateUrlEndpointPath);
    templateParams.put("subject", subject);

    addMessageParams(templateParams, orcidToDeactivate);

    // Generate body from template
    String body = templateManager.processTemplate("deactivate_orcid_email.ftl", templateParams);
    // Generate html from template
    String html =
        templateManager.processTemplate("deactivate_orcid_email_html.ftl", templateParams);

    mailGunManager.sendEmail(DEACTIVATE_NOTIFY_ORCID_ORG, email, subject, body, html);
  }
  private Response getOrcidMessageResponse(OrcidMessage orcidMessage, String requestedOrcid) {
    boolean isProfileDeprecated = false;
    if (orcidMessage == null) {
      Map<String, String> params = new HashMap<String, String>();
      params.put("orcid", requestedOrcid);
      throw new OrcidNotFoundException(params);
    }
    OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
    if (orcidProfile != null) {
      orcidProfile.setOrcidInternal(null);
      // If profile is deprecated
      if (orcidMessage.getOrcidProfile().getOrcidDeprecated() != null) {
        isProfileDeprecated = true;
      }
    }

    Response response = null;

    if (isProfileDeprecated) {
      Map<String, String> params = new HashMap<String, String>();
      params.put(
          "orcid",
          orcidProfile.getOrcidDeprecated().getPrimaryRecord().getOrcidIdentifier().getUri());
      throw new OrcidDeprecatedException(params);
    } else {
      response = Response.ok(orcidMessage).build();
    }

    return response;
  }
Example #5
0
  private OrcidMessage fakeBio() throws DatatypeConfigurationException {
    OrcidMessage orcidMessage = new OrcidMessage();
    OrcidProfile orcidProfile1 = new OrcidProfile();
    OrcidIdentifier orcidIdentifier = new OrcidIdentifier();
    orcidProfile1.setOrcidIdentifier(orcidIdentifier);
    orcidIdentifier.setUri("http://orcid.example.com/000-1337");
    orcidIdentifier.setPath("000-1337");
    OrcidBio bio = new OrcidBio();
    orcidProfile1.setOrcidBio(bio);
    OrcidHistory history = new OrcidHistory();
    XMLGregorianCalendar value =
        dataTypeFactory.newXMLGregorianCalendar(1980, 12, 31, 23, 29, 29, 999, 0);
    history.setCreationMethod(CreationMethod.WEBSITE);
    history.setLastModifiedDate(new LastModifiedDate(value));
    orcidProfile1.setOrcidHistory(history);
    PersonalDetails personal = new PersonalDetails();
    bio.setPersonalDetails(personal);
    personal.setFamilyName(new FamilyName("Doe"));
    personal.setCreditName(new CreditName("John F Doe"));
    personal.setGivenNames(new GivenNames("John"));
    personal.setOtherNames(new OtherNames());
    personal.getOtherNames().addOtherName("Johnny", Visibility.PUBLIC);
    personal.getOtherNames().addOtherName("Mr Doe", Visibility.PUBLIC);

    ResearcherUrls urls = new ResearcherUrls();
    bio.setResearcherUrls(urls);

    ResearcherUrl anonymous =
        new ResearcherUrl(new Url("http://example.com/anon"), Visibility.PUBLIC);
    urls.getResearcherUrl().add(anonymous);

    // "home page" - with strange casing
    ResearcherUrl homePage =
        new ResearcherUrl(
            new Url("http://example.com/myPage"), new UrlName("homePage"), Visibility.PUBLIC);
    urls.getResearcherUrl().add(homePage);

    ResearcherUrl foaf =
        new ResearcherUrl(
            new Url("http://example.com/foaf#me"), new UrlName("FOAF"), Visibility.PUBLIC);
    urls.getResearcherUrl().add(foaf);

    ResearcherUrl webId =
        new ResearcherUrl(
            new Url("http://example.com/webId"), new UrlName("webID"), Visibility.PUBLIC);
    urls.getResearcherUrl().add(webId);

    ResearcherUrl other =
        new ResearcherUrl(
            new Url("http://example.com/other"), new UrlName("other"), Visibility.PUBLIC);
    urls.getResearcherUrl().add(other);

    bio.setContactDetails(new ContactDetails());
    bio.getContactDetails()
        .setEmail(Arrays.asList(new Email("*****@*****.**"), new Email("*****@*****.**")));
    bio.getContactDetails().setAddress(new Address());
    bio.getContactDetails().getAddress().setCountry(new Country(Iso3166Country.GB));
    orcidMessage.setOrcidProfile(orcidProfile1);
    return orcidMessage;
  }
  @Override
  public void sendEmailAddressChangedNotification(OrcidProfile updatedProfile, Email oldEmail) {

    // build up old template
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String subject = getSubject("email.subject.email_removed", updatedProfile);
    String email = oldEmail.getValue();
    String emailFriendlyName = deriveEmailFriendlyName(updatedProfile);
    templateParams.put("emailName", emailFriendlyName);
    String verificationUrl =
        createVerificationUrl(
            updatedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue(),
            orcidUrlManager.getBaseUrl());
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("oldEmail", oldEmail.getValue());
    templateParams.put(
        "newEmail",
        updatedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue());
    templateParams.put("orcid", updatedProfile.getOrcidIdentifier().getPath());
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("subject", subject);

    addMessageParams(templateParams, updatedProfile);

    // Generate body from template
    String body = templateManager.processTemplate("email_removed.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("email_removed_html.ftl", templateParams);

    mailGunManager.sendEmail(EMAIL_CHANGED_NOTIFY_ORCID_ORG, email, subject, body, html);
  }
  @Override
  @Transactional
  public void sendNotificationToAddedDelegate(
      OrcidProfile orcidUserGrantingPermission, List<DelegationDetails> delegatesGrantedByUser) {
    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    String subject = getSubject("email.subject.added_as_delegate", orcidUserGrantingPermission);

    for (DelegationDetails newDelegation : delegatesGrantedByUser) {
      ProfileEntity delegateProfileEntity =
          profileDao.find(newDelegation.getDelegateSummary().getOrcidIdentifier().getPath());
      Boolean sendAdministrativeChangeNotifications =
          delegateProfileEntity.getSendAdministrativeChangeNotifications();
      if (sendAdministrativeChangeNotifications == null || !sendAdministrativeChangeNotifications) {
        LOGGER.debug(
            "Not sending added delegate email, because option to send administrative change notifications not set to true for delegate: {}",
            delegateProfileEntity.getId());
        return;
      }

      String grantingOrcidEmail =
          orcidUserGrantingPermission
              .getOrcidBio()
              .getContactDetails()
              .retrievePrimaryEmail()
              .getValue();
      String emailNameForDelegate = deriveEmailFriendlyName(delegateProfileEntity);
      String email = delegateProfileEntity.getPrimaryEmail().getId();

      templateParams.put("emailNameForDelegate", emailNameForDelegate);
      templateParams.put(
          "grantingOrcidValue", orcidUserGrantingPermission.getOrcidIdentifier().getPath());
      templateParams.put("grantingOrcidName", deriveEmailFriendlyName(orcidUserGrantingPermission));
      templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
      templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
      templateParams.put("grantingOrcidEmail", grantingOrcidEmail);
      templateParams.put("subject", subject);

      addMessageParams(templateParams, orcidUserGrantingPermission);

      // Generate body from template
      String body = templateManager.processTemplate("added_as_delegate_email.ftl", templateParams);
      // Generate html from template
      String html =
          templateManager.processTemplate("added_as_delegate_email_html.ftl", templateParams);

      boolean notificationsEnabled = delegateProfileEntity.getEnableNotifications();
      if (notificationsEnabled) {
        NotificationCustom notification = new NotificationCustom();
        notification.setNotificationType(NotificationType.CUSTOM);
        notification.setSubject(subject);
        notification.setBodyHtml(html);
        createNotification(
            newDelegation.getDelegateSummary().getOrcidIdentifier().getPath(), notification);
      } else {
        mailGunManager.sendEmail(DELEGATE_NOTIFY_ORCID_ORG, email, subject, body, html);
      }
    }
  }
 /**
  * Creates a minimal record
  *
  * @param orcidProfile The record to create
  * @return the new record
  */
 private OrcidProfile createMinimalProfile(OrcidProfile orcidProfile, boolean usedCaptcha) {
   OrcidProfile minimalProfile =
       orcidProfileManager.createOrcidProfile(orcidProfile, false, usedCaptcha);
   // Set source to the new email
   String sourceId = minimalProfile.getOrcidIdentifier().getPath();
   List<Email> emails = minimalProfile.getOrcidBio().getContactDetails().getEmail();
   for (Email email : emails) emailManager.addSourceToEmail(email.getValue(), sourceId);
   LOGGER.debug(
       "Created minimal orcid and assigned id of {}", orcidProfile.getOrcidIdentifier().getPath());
   return minimalProfile;
 }
  @Override
  public void sendClaimReminderEmail(OrcidProfile orcidProfile, int daysUntilActivation) {
    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(orcidProfile));
    String orcid = orcidProfile.getOrcidIdentifier().getPath();
    templateParams.put("orcid", orcid);
    templateParams.put("subject", getSubject("email.subject.claim_reminder", orcidProfile));
    Source source = orcidProfile.getOrcidHistory().getSource();
    String creatorName = "";
    if (source != null) {
      if (source.getSourceName() != null && source.getSourceName().getContent() != null) {
        creatorName = source.getSourceName().getContent();
      } else {
        creatorName = source.retrieveSourcePath();
      }
    }
    templateParams.put("creatorName", creatorName);
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("daysUntilActivation", daysUntilActivation);
    Email primaryEmail = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail();
    if (primaryEmail == null) {
      LOGGER.info("Cant send claim reminder email if primary email is null: {}", orcid);
      return;
    }
    String verificationUrl =
        createClaimVerificationUrl(primaryEmail.getValue(), orcidUrlManager.getBaseUrl());
    templateParams.put("verificationUrl", verificationUrl);

    addMessageParams(templateParams, orcidProfile);

    String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    // Generate body from template
    String body = templateManager.processTemplate("claim_reminder_email.ftl", templateParams);
    String htmlBody =
        templateManager.processTemplate("claim_reminder_email_html.ftl", templateParams);

    // Send message
    if (apiRecordCreationEmailEnabled) {
      mailGunManager.sendEmail(
          CLAIM_NOTIFY_ORCID_ORG,
          email,
          getSubject("email.subject.claim_reminder", orcidProfile),
          body,
          htmlBody);
      profileEventDao.persist(new ProfileEventEntity(orcid, ProfileEventType.CLAIM_REMINDER_SENT));
    } else {
      LOGGER.debug(
          "Not sending claim reminder email, because API record creation email option is disabled. Message would have been: {}",
          body);
    }
  }
 @Override
 public void resetUserPassword(String toEmail, OrcidProfile orcidProfile) {
   LOGGER.debug("Resetting password for Orcid: {}", orcidProfile.getOrcidIdentifier().getPath());
   if (!orcidProfile.getOrcidHistory().isClaimed()) {
     LOGGER.debug(
         "Profile is not claimed so re-sending claim email instead of password reset: {}",
         orcidProfile.getOrcidIdentifier().getPath());
     notificationManager.sendApiRecordCreationEmail(toEmail, orcidProfile);
   } else {
     notificationManager.sendPasswordResetEmail(toEmail, orcidProfile);
   }
 }
Example #11
0
 public OrcidProfile getOrcidProfile(String orcid) {
   OrcidProfile orcidProfile = new OrcidProfile();
   orcidProfile.setOrcidIdentifier(orcid);
   OrcidBio orcidBio = new OrcidBio();
   orcidProfile.setOrcidBio(orcidBio);
   Delegation delegation = new Delegation();
   orcidBio.setDelegation(delegation);
   GivenPermissionTo givenPermissionTo = new GivenPermissionTo();
   delegation.setGivenPermissionTo(givenPermissionTo);
   DelegationDetails delegationDetails = new DelegationDetails();
   givenPermissionTo.getDelegationDetails().add(delegationDetails);
   DelegateSummary delegateSummary = new DelegateSummary(new OrcidIdentifier(delegateOrcid));
   delegationDetails.setDelegateSummary(delegateSummary);
   return orcidProfile;
 }
  @Override
  public void sendPasswordResetEmail(String submittedEmail, OrcidProfile orcidProfile) {

    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(orcidProfile));
    templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
    templateParams.put("subject", getSubject("email.subject.reset", orcidProfile));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    // Generate body from template
    String resetUrl = createResetEmail(orcidProfile, orcidUrlManager.getBaseUrl());
    templateParams.put("passwordResetUrl", resetUrl);

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body = templateManager.processTemplate("reset_password_email.ftl", templateParams);
    String htmlBody =
        templateManager.processTemplate("reset_password_email_html.ftl", templateParams);
    mailGunManager.sendEmail(
        RESET_NOTIFY_ORCID_ORG,
        submittedEmail,
        getSubject("email.subject.reset", orcidProfile),
        body,
        htmlBody);
  }
 @Override
 public OrcidProfile createMinimalRegistration(OrcidProfile orcidProfile, boolean usedCaptcha) {
   String emailAddress =
       orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
   try {
     OrcidProfile profile =
         transactionTemplate.execute(
             new TransactionCallback<OrcidProfile>() {
               public OrcidProfile doInTransaction(TransactionStatus status) {
                 if (emailManager.emailExists(emailAddress)) {
                   checkAutoDeprecateIsEnabledForEmail(emailAddress);
                   String unclaimedOrcid = getOrcidIdFromEmail(emailAddress);
                   emailManager.removeEmail(unclaimedOrcid, emailAddress, true);
                   OrcidProfile minimalProfile = createMinimalProfile(orcidProfile, usedCaptcha);
                   String newUserOrcid = minimalProfile.getOrcidIdentifier().getPath();
                   ProfileDeprecationRequest result = new ProfileDeprecationRequest();
                   adminManager.deprecateProfile(result, unclaimedOrcid, newUserOrcid);
                   notificationManager.sendAutoDeprecateNotification(
                       minimalProfile, unclaimedOrcid);
                   profileEntityCacheManager.remove(unclaimedOrcid);
                   return minimalProfile;
                 } else {
                   return createMinimalProfile(orcidProfile, usedCaptcha);
                 }
               }
             });
     return profile;
   } catch (Exception e) {
     throw new InvalidRequestException(
         "Unable to register user due: " + e.getMessage(), e.getCause());
   }
 }
 @Override
 @VisibilityControl(removeAttributes = false)
 @AccessControl(requiredScope = ScopePathType.READ_PUBLIC, enableAnonymousAccess = true)
 @NonLocked
 public Response findWorksDetailsFromPublicCache(String orcid) {
   try {
     OrcidMessage orcidMessage = orcidSearchManager.findPublicProfileById(orcid);
     if (orcidMessage != null) {
       OrcidProfile orcidProfile = orcidMessage.getOrcidProfile();
       if (orcidProfile != null) {
         orcidProfile.downgradeToWorksOnly();
       }
     }
     return getOrcidMessageResponse(orcidMessage, orcid);
   } catch (OrcidSearchException e) {
     LOGGER.warn("Error searching, so falling back to DB", e);
     return findWorksDetails(orcid);
   }
 }
 private String createResetEmail(OrcidProfile orcidProfile, String baseUri) {
   String userEmail =
       orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
   XMLGregorianCalendar date =
       DateUtils.convertToXMLGregorianCalendarNoTimeZoneNoMillis(new Date());
   String resetParams =
       MessageFormat.format(
           "email={0}&issueDate={1}", new Object[] {userEmail, date.toXMLFormat()});
   return createEmailBaseUrl(resetParams, baseUri, "reset-password-email");
 }
  @Override
  public String deriveEmailFriendlyName(OrcidProfile orcidProfile) {
    if (orcidProfile.getOrcidBio() != null
        && orcidProfile.getOrcidBio().getPersonalDetails() != null) {
      PersonalDetails personalDetails = orcidProfile.getOrcidBio().getPersonalDetails();
      // all this should never be null as given names are required for
      // all...
      if (personalDetails.getGivenNames() != null) {
        String givenName = personalDetails.getGivenNames().getContent();
        String familyName =
            personalDetails.getFamilyName() != null
                    && !StringUtils.isBlank(personalDetails.getFamilyName().getContent())
                ? " " + personalDetails.getFamilyName().getContent()
                : "";
        return givenName + familyName;
      }
    }

    return LAST_RESORT_ORCID_USER_EMAIL_NAME;
  }
 public boolean sendServiceAnnouncement_1_For_2015(OrcidProfile orcidProfile) {
   String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
   String emailFriendlyName = deriveEmailFriendlyName(orcidProfile);
   Map<String, Object> templateParams = new HashMap<String, Object>();
   templateParams.put("emailName", emailFriendlyName);
   String verificationUrl = null;
   verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
   boolean needsVerification =
       !orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().isVerified()
           && orcidProfile.getType().equals(OrcidType.USER)
           && !orcidProfile.isDeactivated();
   if (needsVerification) {
     templateParams.put("verificationUrl", verificationUrl);
   }
   String emailFrequencyUrl =
       createUpdateEmailFrequencyUrl(
           orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue());
   templateParams.put("emailFrequencyUrl", emailFrequencyUrl);
   templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
   templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
   addMessageParams(templateParams, orcidProfile);
   String subject =
       getSubject("email.service_announcement.subject.imporant_information", orcidProfile);
   String text =
       templateManager.processTemplate("service_announcement_1_2015.ftl", templateParams);
   String html =
       templateManager.processTemplate("service_announcement_1_2015_html.ftl", templateParams);
   boolean sent = mailGunManager.sendEmail("*****@*****.**", email, subject, text, html);
   return sent;
 }
  /**
   * Method to perform the mundane task of checking for null and returning the response with an
   * OrcidMessage entity
   *
   * @param profile
   * @param requestedOrcid
   * @return
   */
  private Response getOrcidMessageResponse(OrcidProfile profile, String requestedOrcid) {

    if (profile == null) {
      Map<String, String> params = new HashMap<String, String>();
      params.put("orcid", requestedOrcid);
      throw new OrcidNotFoundException(params);
    }

    profile.setOrcidInternal(null);
    OrcidMessage orcidMessage = new OrcidMessage(profile);

    return Response.ok(orcidMessage).build();
  }
  // look like the following is our best best for i18n emails
  // http://stackoverflow.com/questions/9605828/email-internationalization-using-velocity-freemarker-templates
  public boolean sendPrivPolicyEmail2014_03(OrcidProfile orcidProfile) {
    String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
    Map<String, Object> templateParams = new HashMap<String, Object>();

    String emailFriendlyName = deriveEmailFriendlyName(orcidProfile);
    templateParams.put("emailName", emailFriendlyName);
    if (!orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().isVerified()) {
      String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
      templateParams.put("verificationUrl", verificationUrl);
    }
    templateParams.put("orcid", orcidProfile.getOrcidIdentifier().getPath());
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());

    addMessageParams(templateParams, orcidProfile);

    String text = templateManager.processTemplate("priv_policy_upate_2014_03.ftl", templateParams);
    String html =
        templateManager.processTemplate("priv_policy_upate_2014_03_html.ftl", templateParams);

    return mailGunManager.sendEmail(
        UPDATE_NOTIFY_ORCID_ORG, email, ORCID_PRIVACY_POLICY_UPDATES, text, html);
  }
  @Override
  public void sendWelcomeEmail(OrcidProfile orcidProfile, String email) {
    Map<String, Object> templateParams = new HashMap<String, Object>();
    String subject = getSubject("email.subject.register.thanks", orcidProfile);
    String emailName = deriveEmailFriendlyName(orcidProfile);
    String verificationUrl = createVerificationUrl(email, orcidUrlManager.getBaseUrl());
    String orcidId = orcidProfile.getOrcidIdentifier().getPath();
    String baseUri = orcidUrlManager.getBaseUrl();
    String baseUriHttp = orcidUrlManager.getBaseUriHttp();

    templateParams.put("subject", subject);
    templateParams.put("emailName", emailName);
    templateParams.put("verificationUrl", verificationUrl);
    templateParams.put("orcidId", orcidId);
    templateParams.put("baseUri", baseUri);
    templateParams.put("baseUriHttp", baseUriHttp);

    SourceEntity source = sourceManager.retrieveSourceEntity();
    if (source != null) {
      String sourceId = source.getSourceId();
      String sourceName = source.getSourceName();
      // If the source is not the user itself
      if (sourceId != null && !sourceId.equals(orcidId)) {
        if (!PojoUtil.isEmpty(sourceName)) {
          String paramValue =
              " " + localeManager.resolveMessage("common.through") + " " + sourceName + ".";
          templateParams.put("source_name_if_exists", paramValue);
        } else {
          templateParams.put("source_name_if_exists", ".");
        }
      } else {
        templateParams.put("source_name_if_exists", ".");
      }
    } else {
      templateParams.put("source_name_if_exists", ".");
    }

    addMessageParams(templateParams, orcidProfile);

    // Generate body from template
    String body = templateManager.processTemplate("welcome_email.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("welcome_email_html.ftl", templateParams);

    mailGunManager.sendEmail(SUPPORT_VERIFY_ORCID_ORG, email, subject, body, html);
  }
  @Override
  public void sendDelegationRequestEmail(OrcidProfile managed, OrcidProfile trusted, String link) {
    // Create map of template params
    String orcid = managed.getOrcidIdentifier().getPath();
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("link", link);

    String trustedOrcidValue = trusted.retrieveOrcidPath();
    String managedOrcidValue = managed.retrieveOrcidPath();
    String emailNameForDelegate = deriveEmailFriendlyName(managed);
    String trustedOrcidName = deriveEmailFriendlyName(trusted);
    templateParams.put("emailNameForDelegate", emailNameForDelegate);
    templateParams.put("trustedOrcidName", trustedOrcidName);
    templateParams.put("trustedOrcidValue", trustedOrcidValue);
    templateParams.put("managedOrcidValue", managedOrcidValue);

    Email primaryEmail = managed.getOrcidBio().getContactDetails().retrievePrimaryEmail();
    if (primaryEmail == null) {
      LOGGER.info("Cant send admin delegate email if primary email is null: {}", orcid);
      return;
    }

    addMessageParams(templateParams, managed);

    String htmlBody =
        templateManager.processTemplate("admin_delegate_request_html.ftl", templateParams);

    // Send message
    if (apiRecordCreationEmailEnabled) {
      String subject = getSubject("email.subject.admin_as_delegate", managed, trustedOrcidName);
      ProfileEntity trustedProfileEntity = profileDao.find(trusted.getOrcidIdentifier().getPath());
      boolean notificationsEnabled =
          trustedProfileEntity != null ? trustedProfileEntity.getEnableNotifications() : false;
      if (notificationsEnabled) {
        NotificationCustom notification = new NotificationCustom();
        notification.setNotificationType(NotificationType.CUSTOM);
        notification.setSubject(subject);
        notification.setBodyHtml(htmlBody);
        createNotification(managed.getOrcidIdentifier().getPath(), notification);
      } else {
        mailGunManager.sendEmail(
            DELEGATE_NOTIFY_ORCID_ORG, primaryEmail.getValue(), subject, null, htmlBody);
      }
      profileEventDao.persist(
          new ProfileEventEntity(orcid, ProfileEventType.ADMIN_PROFILE_DELEGATION_REQUEST));
    } else {
      LOGGER.debug(
          "Not sending admin delegate email, because API record creation email option is disabled. Message would have been: {}",
          htmlBody);
    }
  }
  private String extractAmenderName(OrcidProfile orcidProfile, String amenderId) {
    Delegation delegation = orcidProfile.getOrcidBio().getDelegation();
    if (delegation != null
        && delegation.getGivenPermissionTo() != null
        && !delegation.getGivenPermissionTo().getDelegationDetails().isEmpty()) {
      for (DelegationDetails delegationDetails :
          delegation.getGivenPermissionTo().getDelegationDetails()) {
        if (amenderId.equals(
            delegationDetails.getDelegateSummary().getOrcidIdentifier().getPath())) {
          return delegationDetails.getDelegateSummary().getCreditName().getContent();
        }
      }
    }

    ClientDetailsEntity clientDetailsEntity = clientDetailsEntityCacheManager.retrieve(amenderId);
    if (clientDetailsEntity != null) {
      return clientDetailsEntity.getClientName();
    }
    return "";
  }
  @Override
  public EmailMessage createDigest(
      OrcidProfile orcidProfile, Collection<Notification> notifications, Locale locale) {
    int totalMessageCount = 0;
    int orcidMessageCount = 0;
    int addActivitiesMessageCount = 0;
    int amendedMessageCount = 0;
    int activityCount = 0;
    Set<String> memberIds = new HashSet<>();
    DigestEmail digestEmail = new DigestEmail();
    for (Notification notification : notifications) {
      digestEmail.addNotification(notification);
      totalMessageCount++;
      if (notification.getSource() == null) {
        orcidMessageCount++;
      } else {
        SourceClientId clientId = notification.getSource().getSourceClientId();
        if (clientId != null) {
          memberIds.add(clientId.getPath());
        }
      }
      if (notification instanceof NotificationPermission) {
        addActivitiesMessageCount++;
        NotificationPermission permissionNotification = (NotificationPermission) notification;
        activityCount += permissionNotification.getItems().getItems().size();
        String encryptedPutCode =
            encryptionManager.encryptForExternalUse(
                String.valueOf(permissionNotification.getPutCode()));
        try {
          permissionNotification.setEncryptedPutCode(
              Base64.encodeBase64URLSafeString(encryptedPutCode.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
          throw new RuntimeException(
              "Problem base 64 encoding notification put code for notification id = "
                  + permissionNotification.getPutCode(),
              e);
        }
      }
      if (notification instanceof NotificationAmended) {
        amendedMessageCount++;
      }
    }
    String emailName = notificationManager.deriveEmailFriendlyName(orcidProfile);
    String subject =
        messages.getMessage(
            "email.subject.digest",
            new String[] {emailName, String.valueOf(totalMessageCount)},
            locale);
    Map<String, Object> params = new HashMap<>();
    params.put("locale", locale);
    params.put("messages", messages);
    params.put("messageArgs", new Object[0]);
    params.put("orcidProfile", orcidProfile);
    params.put("emailName", emailName);
    params.put("digestEmail", digestEmail);
    params.put(
        "frequency", orcidProfile.getOrcidInternal().getPreferences().getSendEmailFrequencyDays());
    params.put("totalMessageCount", String.valueOf(totalMessageCount));
    params.put("orcidMessageCount", orcidMessageCount);
    params.put("addActivitiesMessageCount", addActivitiesMessageCount);
    params.put("activityCount", activityCount);
    params.put("amendedMessageCount", amendedMessageCount);
    params.put("memberIdsCount", memberIds.size());
    params.put("baseUri", orcidUrlManager.getBaseUrl());
    params.put("subject", subject);
    String bodyText = templateManager.processTemplate("digest_email.ftl", params, locale);
    String bodyHtml = templateManager.processTemplate("digest_email_html.ftl", params, locale);
    EmailMessage emailMessage = new EmailMessage();

    emailMessage.setSubject(subject);
    emailMessage.setBodyText(bodyText);
    emailMessage.setBodyHtml(bodyHtml);
    return emailMessage;
  }
  @Override
  public void sendAmendEmail(
      OrcidProfile amendedProfile, AmendedSection amendedSection, Collection<Item> items) {
    String amenderOrcid = sourceManager.retrieveSourceOrcid();
    if (amenderOrcid == null) {
      LOGGER.debug("Not sending amend email, because amender is null: {}", amendedProfile);
      return;
    }
    if (amenderOrcid.equals(amendedProfile.getOrcidIdentifier().getPath())) {
      LOGGER.debug("Not sending amend email, because self edited: {}", amendedProfile);
      return;
    }
    SendChangeNotifications sendChangeNotifications =
        amendedProfile.getOrcidInternal().getPreferences().getSendChangeNotifications();
    if (sendChangeNotifications == null || !sendChangeNotifications.isValue()) {
      LOGGER.debug(
          "Not sending amend email, because option to send change notifications not set to true: {}",
          amendedProfile);
      return;
    }
    if (OrcidType.ADMIN.equals(profileDao.retrieveOrcidType(amenderOrcid))) {
      LOGGER.debug(
          "Not sending amend email, because modified by admin ({}): {}",
          amenderOrcid,
          amendedProfile);
      return;
    }

    String subject = getSubject("email.subject.amend", amendedProfile);

    // Create map of template params
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("emailName", deriveEmailFriendlyName(amendedProfile));
    templateParams.put("orcid", amendedProfile.getOrcidIdentifier().getPath());
    templateParams.put("amenderName", extractAmenderName(amendedProfile, amenderOrcid));
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("subject", subject);

    addMessageParams(templateParams, amendedProfile);

    // Generate body from template
    String body = templateManager.processTemplate("amend_email.ftl", templateParams);
    // Generate html from template
    String html = templateManager.processTemplate("amend_email_html.ftl", templateParams);

    boolean notificationsEnabled =
        profileDao.find(amendedProfile.getOrcidIdentifier().getPath()).getEnableNotifications();
    if (notificationsEnabled) {
      NotificationAmended notification = new NotificationAmended();
      notification.setNotificationType(NotificationType.AMENDED);
      notification.setAmendedSection(amendedSection);
      if (items != null) {
        notification.setItems(new Items(new ArrayList<>(items)));
      }
      createNotification(amendedProfile.getOrcidIdentifier().getPath(), notification);
    } else {
      String email =
          amendedProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue();
      mailGunManager.sendEmail(AMEND_NOTIFY_ORCID_ORG, email, subject, body, html);
    }
  }
  @Override
  @Transactional
  public void sendApiRecordCreationEmail(String toEmail, OrcidProfile createdProfile) {

    Source source = null;
    CustomEmailEntity customEmail = null;
    if (createdProfile.getOrcidHistory() != null
        && createdProfile.getOrcidHistory().getSource() != null) {
      if (!PojoUtil.isEmpty(createdProfile.getOrcidHistory().getSource().retrieveSourcePath())) {
        source = createdProfile.getOrcidHistory().getSource();
        customEmail =
            getCustomizedEmail(
                createdProfile.getOrcidHistory().getSource().retrieveSourcePath(), EmailType.CLAIM);
      }
    }

    String email =
        createdProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue().trim();
    String emailName = deriveEmailFriendlyName(createdProfile);
    String orcid = createdProfile.getOrcidIdentifier().getPath();
    String verificationUrl = createClaimVerificationUrl(email, orcidUrlManager.getBaseUrl());

    String creatorName = "";
    if (source != null) {
      if (source.getSourceName() != null && source.getSourceName().getContent() != null) {
        creatorName = source.getSourceName().getContent();
      } else if (!PojoUtil.isEmpty(source.retrieveSourcePath())) {
        creatorName = source.retrieveSourcePath();
      }
    }

    String subject = null;
    String body = null;
    String htmlBody = null;
    String sender = null;

    if (customEmail != null) {
      // Get the customized sender if available
      sender =
          PojoUtil.isEmpty(customEmail.getSender())
              ? CLAIM_NOTIFY_ORCID_ORG
              : customEmail.getSender();
      // Get the customized subject is available
      subject =
          PojoUtil.isEmpty(customEmail.getSubject())
              ? getSubject("email.subject.api_record_creation", createdProfile)
              : customEmail.getSubject();
      // Replace the wildcards
      subject = subject.replace(WILDCARD_USER_NAME, emailName);
      subject = subject.replace(WILDCARD_MEMBER_NAME, creatorName);
      if (customEmail.isHtml()) {
        htmlBody = customEmail.getContent();
        htmlBody = htmlBody.replace(WILDCARD_USER_NAME, emailName);
        htmlBody = htmlBody.replace(WILDCARD_MEMBER_NAME, creatorName);
        htmlBody = htmlBody.replace(EmailConstants.WILDCARD_VERIFICATION_URL, verificationUrl);
        if (htmlBody.contains(WILDCARD_WEBSITE) || htmlBody.contains(WILDCARD_DESCRIPTION)) {
          ClientDetailsEntity clientDetails = customEmail.getClientDetailsEntity();
          htmlBody = htmlBody.replace(WILDCARD_WEBSITE, clientDetails.getClientWebsite());
          htmlBody = htmlBody.replace(WILDCARD_DESCRIPTION, clientDetails.getClientDescription());
        }
      } else {
        body = customEmail.getContent();
        body = body.replace(WILDCARD_USER_NAME, emailName);
        body = body.replace(WILDCARD_MEMBER_NAME, creatorName);
        body = body.replace(EmailConstants.WILDCARD_VERIFICATION_URL, verificationUrl);
        if (body.contains(WILDCARD_WEBSITE) || body.contains(WILDCARD_DESCRIPTION)) {
          ClientDetailsEntity clientDetails = customEmail.getClientDetailsEntity();
          body = body.replace(WILDCARD_WEBSITE, clientDetails.getClientWebsite());
          body = body.replace(WILDCARD_DESCRIPTION, clientDetails.getClientDescription());
        }
      }
    } else {
      subject = getSubject("email.subject.api_record_creation", createdProfile);
      // Create map of template params
      Map<String, Object> templateParams = new HashMap<String, Object>();
      templateParams.put("emailName", emailName);
      templateParams.put("orcid", orcid);
      templateParams.put("subject", subject);
      templateParams.put("creatorName", creatorName);
      templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
      templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
      templateParams.put("verificationUrl", verificationUrl);

      addMessageParams(templateParams, createdProfile);
      // Generate body from template
      body = templateManager.processTemplate("api_record_creation_email.ftl", templateParams);
      htmlBody =
          templateManager.processTemplate("api_record_creation_email_html.ftl", templateParams);
    }

    // Send message
    if (apiRecordCreationEmailEnabled) {
      boolean isCustomEmail = customEmail != null ? true : false;
      // TODO: How to handle sender? we might have to register them on
      // mailgun
      if (isCustomEmail) {
        mailGunManager.sendEmail(sender, email, subject, body, htmlBody, isCustomEmail);
      } else {
        mailGunManager.sendEmail(CLAIM_NOTIFY_ORCID_ORG, email, subject, body, htmlBody);
      }
    } else {
      LOGGER.debug(
          "Not sending API record creation email, because option is disabled. Message would have been: {}",
          body);
    }
  }