Exemplo n.º 1
0
 @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());
   }
 }
 @Override
 public List<? extends ItemGroup<?>> validDestinations(Item item) {
   List<DirectlyModifiableTopLevelItemGroup> result =
       new ArrayList<DirectlyModifiableTopLevelItemGroup>();
   Jenkins instance = Jenkins.getActiveInstance();
   if (permitted(item, instance)) {
     result.add(instance);
   }
   ITEM:
   for (Item g : instance.getAllItems()) {
     if (g instanceof DirectlyModifiableTopLevelItemGroup) {
       DirectlyModifiableTopLevelItemGroup itemGroup = (DirectlyModifiableTopLevelItemGroup) g;
       if (!permitted(item, itemGroup)) {
         continue;
       }
       ItemGroup<?> p = itemGroup;
       while (p instanceof Item) {
         Item i = (Item) p;
         if (i == item) {
           // Cannot move a folder into itself or a descendant.
           continue ITEM;
         }
         p = i.getParent();
       }
       result.add(itemGroup);
     }
   }
   return result;
 }
 /**
  * Retrieves the plugin instance.
  *
  * @return {@link EnvInjectPlugin}
  * @throws IllegalStateException the plugin has not been loaded yet
  */
 public static @Nonnull EnvInjectPlugin getInstance() {
   EnvInjectPlugin plugin = Jenkins.getActiveInstance().getPlugin(EnvInjectPlugin.class);
   if (plugin == null) { // Fail horribly
     // TODO: throw a graceful error
     throw new IllegalStateException(
         "Cannot get the plugin's instance. Jenkins or the plugin have not been initialized yet");
   }
   return plugin;
 }
 // getPropertyType("delegate").getApplicableDescriptors() does not work, because extension lists
 // do not work on subtypes.
 public Collection<BuildWrapperDescriptor> getApplicableDescriptors() {
   Collection<BuildWrapperDescriptor> r = new ArrayList<BuildWrapperDescriptor>();
   for (BuildWrapperDescriptor d :
       Jenkins.getActiveInstance().getExtensionList(BuildWrapperDescriptor.class)) {
     if (SimpleBuildWrapper.class.isAssignableFrom(d.clazz)) {
       r.add(d);
     }
   }
   return r;
 }
  void provisionFailed(Exception cause) {
    if (executable instanceof Run) {
      ((Run) executable).setResult(Result.NOT_BUILT);
    }

    try {
      Jenkins.getActiveInstance().removeNode(this);
    } catch (IOException e) {
      e.printStackTrace();
    }

    throw new OneShotExecutorProvisioningException(cause);
  }
 @Override
 public Builder newInstance(StaplerRequest req, JSONObject formData) throws FormException {
   // TODO f:dropdownDescriptorSelector does not seem to work sensibly: the super method uses
   // RequestImpl.bindJSON and ignores any StepDescriptor.newInstance override.
   // Cf. Snippetizer.doGenerateSnippet, which also seems to lack a standard way of parsing
   // part of a form using databinding.
   JSONObject s = formData.getJSONObject("s");
   Jenkins j = Jenkins.getActiveInstance();
   Class<?> c;
   try {
     c = j.getPluginManager().uberClassLoader.loadClass(s.getString("stapler-class"));
   } catch (ClassNotFoundException x) {
     throw new FormException(x, "s");
   }
   Descriptor<?> descriptor = j.getDescriptor(c.asSubclass(Step.class));
   return new StepBuilder((Step) descriptor.newInstance(req, s));
 }
 /**
  * Stapler helper method.
  *
  * @param context the context.
  * @param remoteBase the remote base.
  * @return list box model.
  */
 @SuppressWarnings("unused") // by stapler
 public ListBoxModel doFillCredentialsIdItems(
     @AncestorInPath SCMSourceOwner context,
     @QueryParameter String remoteBase,
     @QueryParameter String credentialsId) {
   if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
       || context != null && !context.hasPermission(Item.EXTENDED_READ)) {
     return new StandardListBoxModel().includeCurrentValue(credentialsId);
   }
   List<DomainRequirement> domainRequirements;
   domainRequirements = URIRequirementBuilder.fromUri(remoteBase.trim()).build();
   return new StandardListBoxModel()
       // TODO JENKINS-35553 update to newer APIs
       .withEmptySelection()
       .withMatching(
           CredentialsMatchers.anyOf(
               CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
               CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
               CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)),
           CredentialsProvider.lookupCredentials(
               StandardCredentials.class, context, ACL.SYSTEM, domainRequirements));
 }
    /** 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);
      }
    }
Exemplo n.º 9
0
 public boolean hasIssueSelectors() {
   return Jenkins.getActiveInstance().getDescriptorList(AbstractIssueSelector.class).size() > 1;
 }
 /** @return the {@link HealthCheckManager}. */
 @Override
 @VisibleForTesting
 protected HealthCheckManager getDerivedPageManager() {
   return Iterables.getOnlyElement(
       Jenkins.getActiveInstance().getExtensionList(HealthCheckManager.class));
 }