/** Expect errors from {@link org.codehaus.groovy.runtime.NullObject}. */
 @Issue("kohsuke/groovy-sandbox #15")
 @Test
 public void nullPointerException() throws Exception {
   try {
     assertEvaluate(new ProxyWhitelist(), "should be rejected", "def x = null; x.member");
   } catch (NullPointerException x) {
     assertEquals(
         Functions.printThrowable(x),
         "Cannot get property 'member' on null object",
         x.getMessage());
   }
   try {
     assertEvaluate(new ProxyWhitelist(), "should be rejected", "def x = null; x.member = 42");
   } catch (NullPointerException x) {
     assertEquals(
         Functions.printThrowable(x),
         "Cannot set property 'member' on null object",
         x.getMessage());
   }
   try {
     assertEvaluate(new ProxyWhitelist(), "should be rejected", "def x = null; x.member()");
   } catch (NullPointerException x) {
     assertEquals(
         Functions.printThrowable(x),
         "Cannot invoke method member() on null object",
         x.getMessage());
   }
 }
 @Restricted(DoNotUse.class) // accessed via REST API
 public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json)
     throws Exception {
   // TODO JENKINS-31458 is there not an easier way to do this?
   JSONObject jsonO = JSONObject.fromObject(json);
   Jenkins j = Jenkins.getActiveInstance();
   Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class"));
   StepDescriptor descriptor = (StepDescriptor) j.getDescriptor(c.asSubclass(Step.class));
   Object o;
   try {
     o = descriptor.newInstance(req, jsonO);
   } catch (RuntimeException x) { // e.g. IllegalArgumentException
     return HttpResponses.plainText(Functions.printThrowable(x));
   }
   try {
     String groovy = object2Groovy(o);
     if (descriptor.isAdvanced()) {
       String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in();
       groovy = "// " + warning + "\n" + groovy;
     }
     return HttpResponses.plainText(groovy);
   } catch (UnsupportedOperationException x) {
     Logger.getLogger(CpsFlowExecution.class.getName())
         .log(Level.WARNING, "failed to render " + json, x);
     return HttpResponses.plainText(x.getMessage());
   }
 }
 private static void expectRejection(
     MatrixProject project, String combinationFilter, String signature) throws IOException {
   ScriptApproval scriptApproval = ScriptApproval.get();
   assertEquals(Collections.emptySet(), scriptApproval.getPendingSignatures());
   try {
     project.setCombinationFilter(combinationFilter);
   } catch (RejectedAccessException x) {
     assertEquals(Functions.printThrowable(x), signature, x.getSignature());
   }
   Set<ScriptApproval.PendingSignature> pendingSignatures = scriptApproval.getPendingSignatures();
   assertEquals(1, pendingSignatures.size());
   assertEquals(signature, pendingSignatures.iterator().next().signature);
   scriptApproval.approveSignature(signature);
   assertEquals(Collections.emptySet(), scriptApproval.getPendingSignatures());
 }
Beispiel #4
0
    /**
     * Send an email to the admin address
     *
     * @throws IOException
     * @throws ServletException
     * @throws InterruptedException
     */
    public FormValidation doSendTestMail(
        @QueryParameter String smtpServer,
        @QueryParameter String adminAddress,
        @QueryParameter boolean useSMTPAuth,
        @QueryParameter String smtpAuthUserName,
        @QueryParameter String smtpAuthPassword,
        @QueryParameter boolean useSsl,
        @QueryParameter String smtpPort)
        throws IOException, ServletException, InterruptedException {
      try {
        if (!useSMTPAuth) smtpAuthUserName = smtpAuthPassword = null;

        MimeMessage msg =
            new MimeMessage(
                createSession(
                    smtpServer,
                    smtpPort,
                    useSsl,
                    smtpAuthUserName,
                    Secret.fromString(smtpAuthPassword)));
        msg.setSubject("Test email #" + ++testEmailCount);
        msg.setContent(
            "This is test email #"
                + testEmailCount
                + " sent from Hudson Continuous Integration server.",
            "text/plain");
        msg.setFrom(new InternetAddress(adminAddress));
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(adminAddress));

        Transport.send(msg);

        return FormValidation.ok("Email was successfully sent");
      } catch (MessagingException e) {
        return FormValidation.errorWithMarkup(
            "<p>Failed to send out e-mail</p><pre>"
                + Util.escape(Functions.printThrowable(e))
                + "</pre>");
      }
    }
    /** validate the value for a remote (repository) location. */
    public FormValidation doCheckCredentialsId(
        StaplerRequest req,
        @AncestorInPath SCMSourceOwner context,
        @QueryParameter String remoteBase,
        @QueryParameter String value) {
      // TODO suspiciously similar to
      // SubversionSCM.ModuleLocation.DescriptorImpl.checkCredentialsId; refactor into shared
      // method?
      // Test the connection only if we may use the credentials
      if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
          || context != null && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
        return FormValidation.ok();
      }

      // if check remote is reporting an issue then we don't need to
      String url = Util.fixEmptyAndTrim(remoteBase);
      if (url == null) return FormValidation.ok();

      if (!URL_PATTERN.matcher(url).matches()) return FormValidation.ok();

      try {
        String urlWithoutRevision = SvnHelper.getUrlWithoutRevision(url);

        SVNURL repoURL = SVNURL.parseURIDecoded(urlWithoutRevision);

        StandardCredentials credentials =
            value == null
                ? null
                : CredentialsMatchers.firstOrNull(
                    CredentialsProvider.lookupCredentials(
                        StandardCredentials.class,
                        context,
                        ACL.SYSTEM,
                        URIRequirementBuilder.fromUri(repoURL.toString()).build()),
                    CredentialsMatchers.withId(value));
        if (checkRepositoryPath(context, repoURL, credentials) != SVNNodeKind.NONE) {
          // something exists; now check revision if any

          SVNRevision revision = getRevisionFromRemoteUrl(url);
          if (revision != null && !revision.isValid()) {
            return FormValidation.errorWithMarkup(
                hudson.scm.subversion.Messages.SubversionSCM_doCheckRemote_invalidRevision());
          }

          return FormValidation.ok();
        }

        SVNRepository repository = null;
        try {
          repository =
              getRepository(
                  context, repoURL, credentials, Collections.<String, Credentials>emptyMap(), null);
          long rev = repository.getLatestRevision();
          // now go back the tree and find if there's anything that exists
          String repoPath = getRelativePath(repoURL, repository);
          String p = repoPath;
          while (p.length() > 0) {
            p = SVNPathUtil.removeTail(p);
            if (repository.checkPath(p, rev) == SVNNodeKind.DIR) {
              // found a matching path
              List<SVNDirEntry> entries = new ArrayList<SVNDirEntry>();
              repository.getDir(p, rev, false, entries);

              // build up the name list
              List<String> paths = new ArrayList<String>();
              for (SVNDirEntry e : entries)
                if (e.getKind() == SVNNodeKind.DIR) paths.add(e.getName());

              String head = SVNPathUtil.head(repoPath.substring(p.length() + 1));
              String candidate = EditDistance.findNearest(head, paths);

              return FormValidation.error(
                  hudson.scm.subversion.Messages.SubversionSCM_doCheckRemote_badPathSuggest(
                      p, head, candidate != null ? "/" + candidate : ""));
            }
          }

          return FormValidation.error(
              hudson.scm.subversion.Messages.SubversionSCM_doCheckRemote_badPath(repoPath));
        } finally {
          if (repository != null) repository.closeSession();
        }
      } catch (SVNException e) {
        LOGGER.log(Level.INFO, "Failed to access subversion repository " + url, e);
        String message =
            hudson.scm.subversion.Messages.SubversionSCM_doCheckRemote_exceptionMsg1(
                    Util.escape(url),
                    Util.escape(e.getErrorMessage().getFullMessage()),
                    "javascript:document.getElementById('svnerror').style.display='block';"
                        + "document.getElementById('svnerrorlink').style.display='none';"
                        + "return false;")
                + "<br/><pre id=\"svnerror\" style=\"display:none\">"
                + Functions.printThrowable(e)
                + "</pre>";
        return FormValidation.errorWithMarkup(message);
      }
    }
Beispiel #6
0
 public String getExceptionString() {
   return Functions.printThrowable(cause);
 }