Java 类hudson.tasks.Mailer 实例源码

项目:restricted-register-plugin    文件:ActivationCodeFormValidator.java   
@Override
public void verifyFormData(HudsonSecurityRealmRegistration securityRealmRegistration, JSONObject object)
        throws RegistrationException, InvalidSecurityRealmException {
    final String activationCode = BaseFormField.ACTIVATION_CODE.fromJSON(object);
    if (StringUtils.isEmpty(activationCode)) {
        throw new RegistrationException(Messages.RRError_Hudson_ActiviationCodeInvalid());
    }
    final User user = RRHudsonUserProperty.getUserForActivationCode(activationCode);
    final RRHudsonUserProperty hudsonUserProperty = RRHudsonUserProperty.getPropertyForUser(user);
    if (hudsonUserProperty == null) {
        throw new RegistrationException(Messages.RRError_Hudson_ActiviationCodeInvalid());
    }
    if (hudsonUserProperty.getActivated()) {
        throw new RegistrationException(Messages.RRError_Hudson_UserIsActivated());
    }
    final Mailer.UserProperty mailerProperty = user.getProperty(Mailer.UserProperty.class);
    if (mailerProperty == null) {
        throw new RegistrationException(Messages.RRError_Hudson_UserNoEmailAddress());
    }
    final String emailAddress = Utils.fixEmptyString(mailerProperty.getAddress());
    if (!EmailValidator.getInstance().isValid(emailAddress)) {
        throw new RegistrationException(Messages.RRError_Hudson_UserInvalidEmail(emailAddress));
    }
}
项目:restricted-register-plugin    文件:LocalVariablesBuilder.java   
public LocalVariables build() {
    final Map<String, String> variables = new HashMap<>();
    variables.put(VAR_USER_DISPLAY_NAME, Utils.escapeInputString(user.getFullName()));
    variables.put(VAR_USER_ID, Utils.escapeInputString(user.getId()));
    final Mailer.UserProperty mailerProperty = user.getProperty(Mailer.UserProperty.class);
    if (mailerProperty != null) {
        variables.put(VAR_USER_EMAIL, Utils.escapeInputString(Utils.fixEmptyString(mailerProperty.getAddress())));
    } else {
        variables.put(VAR_USER_EMAIL, "");
    }
    final String secret = BaseFormField.SECRET.fromJSON(payload);
    final String code = RRHudsonUserProperty.getActivationCodeForUser(user);

    variables.put(VAR_CONFIRMATION_LINK, Utils.escapeInputString(AppUrls.buildActivationUrl(code, secret)));
    variables.put(VAR_SIGN_IN_LINK, Utils.escapeInputString(AppUrls.buildSignInUrl()));

    return new LocalVariables(variables);
}
项目:jenkins-fossil-adapter    文件:FossilChangeLogEntry.java   
/**
 * Gets the user who made this change.
 * 
 * This is a mandatory part of the Change Log Architecture
 * 
 * @return the author of the checkin (aka commit)
 */
@Exported
public User getAuthor() {
    User user = User.get(author, false);

    if (user == null) {
        user = User.get(author, true);

        // set email address for user
        if (fixEmpty(authorEmail) != null) {
            try {
                user.addProperty(new Mailer.UserProperty(authorEmail));
            } catch (IOException e) {
                // ignore error
            }
        }
    }

    return user;
}
项目:flaky-test-handler-plugin    文件:TestGitRepo.java   
public TestGitRepo(String name, File tmpDir, TaskListener listener) throws IOException, InterruptedException {
  this.name = name;
  this.listener = listener;

  envVars = new EnvVars();

  gitDir = tmpDir;
  User john = User.get(johnDoe.getName(), true);
  UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
  john.addProperty(johnsMailerProperty);

  User jane = User.get(janeDoe.getName(), true);
  UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
  jane.addProperty(janesMailerProperty);

  // initialize the git interface.
  gitDirPath = new FilePath(gitDir);
  git = Git.with(listener, envVars).in(gitDir).getClient();

  // finally: initialize the repo
  git.init();
}
项目:yaml-project-plugin    文件:YamlToJsonTest.java   
@Test
public void testTagTranslations() throws Exception {
  YamlToJson underTest = new YamlToJson.Default(
      ImmutableList.<YamlTransform>of(
          new HelperTransform("!freestyle", FreeStyleProject.class),
          new HelperTransform("!maven", Maven.class),
          new HelperTransform("!git", GitSCM.class) {
            @Override
            public String construct(String value) {
              assertEquals("scm", value);
              return clazz.getName();
            }
          },
          new HelperTransform("!shell", Shell.class),
          new HelperTransform("!trigger", BuildTrigger.class),
          new HelperTransform("!mailer", Mailer.class)));
  for (String test : TAG_TESTS) {
    testOneTranslation(underTest, test);
  }
}
项目:yaml-project-plugin    文件:JsonToYamlTest.java   
@Test
public void testTagTranslations() throws Exception {
  JsonToYaml underTest = new JsonToYaml.Default(
      ImmutableList.<YamlTransform>of(
          new HelperTransform("!freestyle", FreeStyleProject.class),
          new HelperTransform("!maven", Maven.class),
          new HelperTransform("!git", GitSCM.class) {
            @Override
            public String represent(Class clazz) {
              assertEquals(this.clazz, clazz);
              return "scm";
            }
            @Override
            public String construct(String value) {
              assertEquals("scm", value);
              return this.clazz.getName();
            }
          },
          new HelperTransform("!shell", Shell.class),
          new HelperTransform("!trigger", BuildTrigger.class),
          new HelperTransform("!mailer", Mailer.class)));
  for (String test : TAG_TESTS) {
    testOneTranslation(underTest, test);
  }
}
项目:quarantine    文件:MailNotifier.java   
public String getEmailAddress(String username) {
   String address = null;
   User u = User.get(username);
   if (u == null) {
      println("failed obtaining user for name " + username);
      return address;
   }
   Mailer.UserProperty p = u.getProperty(Mailer.UserProperty.class);
   if (p == null) {
      println("failed obtaining email address for user " + username);
      return address;
   }

   if (p.getAddress() == null) {
      println("failed obtaining email address (is null) for user " + username);
      return address;
   }

   return p.getAddress();
}
项目:quarantine    文件:QuarantineCoreTest.java   
@Override
protected void setUp() throws Exception {
   super.setUp();
   java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.SEVERE);

   project = createFreeStyleProject(projectName);
   DescribableList<TestDataPublisher, Descriptor<TestDataPublisher>> publishers = new DescribableList<TestDataPublisher, Descriptor<TestDataPublisher>>(
         project);
   publishers.add(new QuarantineTestDataPublisher());
   QuarantinableJUnitResultArchiver archiver = new QuarantinableJUnitResultArchiver("*.xml");
   archiver.setTestDataPublishers(publishers);
   project.getPublishersList().add(archiver);

   hudson.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
   hudson.setSecurityRealm(createDummySecurityRealm());

   User u = User.get("user1");
   u.addProperty(new Mailer.UserProperty(user1Mail));
}
项目:restricted-register-plugin    文件:Mail.java   
private String getReplyToAddress() {
    String ret = Utils.fixEmptyString(replyTo);
    if (StringUtils.isEmpty(ret)) {
        ret = Utils.fixEmptyString(Mailer.descriptor().getReplyToAddress());
    }
    return ret;
}
项目:yaml-project-plugin    文件:YamlProjectFactoryTest.java   
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);

  underTest = new YamlProjectFactory(YAML_PATH, RESTRICTION,
      ImmutableList.<Publisher>of(new Mailer()));
}
项目:quarantine    文件:MailNotifier.java   
public void sendEmail(String username, List<ResultActionPair> results) {
   String address = getEmailAddress(username);
   if (address == null) {
      return;
   }

   MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
   try {

      msg.setFrom(new InternetAddress(JenkinsLocationConfiguration.get().getAdminAddress()));
      msg.setSentDate(new Date());
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject("Failure of quarantined tests");

      String message = renderEmail(username, results);
      if (message == null) {
         println("[Quarantine]: unable to render message");
         return;
      }
      msg.setContent(message, "text/html");

      Transport.send(msg);

      println("[Quarantine]: sent email to " + address);
   } catch (MessagingException e) {
      println("[Quarantine]: failed sending email: " + e.toString());
   }
}
项目:coverity-plugin    文件:CoverityMailSender.java   
protected MimeMessage getMail(CoverityBuildAction action, BuildListener listener) throws MessagingException, InterruptedException, IOException, CovRemoteServiceException_Exception {
    MimeMessage msg = createEmptyMail(action, listener);

    List<MergedDefectDataObj> defects = action.getDefects();
    msg.setSubject(String.format("Build failed due to %d Coverity defects: ", defects.size(), action.getBuild().getFullDisplayName()), charset);

    StringBuilder buf = new StringBuilder();

    buf.append("<html>");

    buf.append("<body>");

    buf.append(String.format(
            "<p style=\"font-family: Verdana, Helvetica, sans serif; font-size: 12px;\">" +
                    "<a href=\"%s%s\">%s</a> failed because " + (defects.size() > 1 ? "%d Coverity defects were" : "%d Coverity defect was") + " found.</p>",
            Mailer.descriptor().getUrl(),
            action.getBuild().getUrl(),
            action.getBuild().getFullDisplayName(),
            defects.size()));

    buf.append("<table style='width: 100%; border-collapse: collapse; border: 1px #BBB solid; font-family: Verdana, Helvetica, sans serif; font-size: 12px;'>\n");
    buf.append("<tr style='border: 1px #BBB solid; border-right: none; border-left: none; background-color: #F0F0F0; font-weight: bold;'>").append("<td colspan=\"3\" class=\"pane-header\">Coverity Defects</td></tr>");
    buf.append("<tr style='text-align: left;'><th>CID</th><th>Checker</th><th>Function</th></tr>\n");
    for(MergedDefectDataObj defect : defects) {
        buf.append("<tr>\n");
        buf.append("<td align='left'><a href=\"").append(action.getURL(defect)).append("\">").append(Long.toString(defect.getCid())).append("</a></td>\n");
        buf.append("<td align='left'>").append(Util.escape(defect.getCheckerName())).append("</td>\n");
        buf.append("<td align='left'>").append(Util.escape(defect.getFunctionDisplayName())).append("</td>\n");
        buf.append("</tr>\n");
    }
    buf.append("</table>");
    buf.append("</body>");
    buf.append("</html>");

    msg.setText(buf.toString(), charset, "html");

    return msg;
}
项目:coverity-plugin    文件:CoverityMailSender.java   
private MimeMessage createEmptyMail(CoverityBuildAction action, BuildListener listener) throws MessagingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    msg.setContent("", "text/html");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();

    if(recipients != null) {
        StringTokenizer tokens = new StringTokenizer(recipients);
        while(tokens.hasMoreTokens()) {
            String address = tokens.nextToken();
            try {
                rcp.add(new InternetAddress(address));
            } catch(AddressException e) {
                // report bad address, but try to send to other addresses
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    Set<User> culprits = action.getBuild().getCulprits();

    rcp.addAll(buildCulpritList(listener, culprits));
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    return msg;
}
项目:coverity-plugin    文件:CoverityMailSender.java   
private Set<InternetAddress> buildCulpritList(BuildListener listener, Set<User> culprits) throws AddressException {
    Set<InternetAddress> r = new HashSet<InternetAddress>();
    for(User a : culprits) {
        String adrs = Util.fixEmpty(a.getProperty(Mailer.UserProperty.class).getAddress());
        if(adrs != null)
            r.add(new InternetAddress(adrs));
    }
    return r;
}
项目:jenkins-keycloak-plugin    文件:KeycloakSecurityRealm.java   
/**
 * This is where the user comes back to at the end of the OpenID redirect
 * ping-pong.
 * 
 * @throws HttpFailure
 * @throws VerificationException
 */
public HttpResponse doFinishLogin(StaplerRequest request) {

    String redirect = redirectUrl(request);

    try {

        AccessTokenResponse tokenResponse = ServerRequest.invokeAccessCodeToToken(getKeycloakDeployment(),
                request.getParameter("code"), redirect, null);

        String tokenString = tokenResponse.getToken();
        String idTokenString = tokenResponse.getIdToken();
        String refreashToken = tokenResponse.getRefreshToken();

        AccessToken token = AdapterRSATokenVerifier.verifyToken(tokenString, getKeycloakDeployment());
        if (idTokenString != null) {
            JWSInput input = new JWSInput(idTokenString);

            IDToken idToken = input.readJsonContent(IDToken.class);
            SecurityContextHolder.getContext()
                    .setAuthentication(new KeycloakAuthentication(idToken, token, refreashToken));

            User currentUser = User.current();
            if (currentUser != null) {
                currentUser.setFullName(idToken.getPreferredUsername());

                if (!currentUser.getProperty(Mailer.UserProperty.class).hasExplicitlyConfiguredAddress()) {
                    currentUser.addProperty(new Mailer.UserProperty(idToken.getEmail()));
                }
            }
        }

    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Authentication Exception ", e);
    }

    String referer = (String) request.getSession().getAttribute(REFERER_ATTRIBUTE);
    if (referer != null) {
        return HttpResponses.redirectTo(referer);
    }
    return HttpResponses.redirectToContextRoot();
}
项目:youtrack-jenkins    文件:YouTrackSCMListener.java   
private void findIssueId(YouTrackSite youTrackSite, YouTrackServer youTrackServer, User user, List<Issue> fixedIssues, ChangeLogSet.Entry next, String comment, String issueStart, Project p, BuildListener listener) {
    if(p != null) {
        Pattern projectPattern = Pattern.compile("(" + p.getShortName() + "-" + "(\\d+)" + ") (.*)");

        Matcher matcher = projectPattern.matcher(issueStart);
        while (matcher.find()) {
            if (matcher.groupCount() >= 1) {
                String issueId = p.getShortName() + "-" + matcher.group(2);
                if (!youTrackSite.isRunAsEnabled()) {
                    youTrackServer.applyCommand(user, new Issue(issueId), matcher.group(3), comment, null);
                } else {
                    String address = next.getAuthor().getProperty(Mailer.UserProperty.class).getAddress();
                    User userByEmail = youTrackServer.getUserByEmail(user, address);
                    if (userByEmail == null) {
                        listener.getLogger().println("Failed to find user with e-mail: " + address);
                    }

                    //Get the issue state, then apply command, and get the issue state again.
                    //to know whether the command has been marked as fixed, instead of trying to
                    //interpret the command. This means however that there is a possibility for
                    //the user to change state between the before and the after call, so the after
                    //state can be affected by something else than the command.
                    Issue before = youTrackServer.getIssue(user, issueId);
                    String command = matcher.group(3);
                    boolean applied = youTrackServer.applyCommand(user, new Issue(issueId), command, comment, userByEmail);
                    if(applied) {
                        listener.getLogger().println("Applied command: " + command + " to issue: " + issueId);
                    } else {
                        listener.getLogger().println("FAILED: Applying command: " + command + " to issue: " + issueId);
                    }
                    Issue after = youTrackServer.getIssue(user, issueId);

                    if(!before.getState().equals("Fixed") && after.getState().equals("Fixed")) {
                        fixedIssues.add(after);
                    }

                }
            }
        }

    }
}