Search in sources :

Example 11 with Restricted

use of org.kohsuke.accmod.Restricted in project configuration-as-code-plugin by jenkinsci.

the class BaseConfigurator method describe.

public Set<Attribute> describe() {
    Set<Attribute> attributes = new HashSet<>();
    final Class<T> target = getTarget();
    final PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(target);
    LOGGER.log(Level.FINE, "Found {0} properties for {1}", new Object[] { properties.length, target });
    for (PropertyDescriptor p : properties) {
        final String name = p.getName();
        LOGGER.log(Level.FINER, "Processing {0} property", name);
        final Method setter = p.getWriteMethod();
        if (setter == null) {
            LOGGER.log(Level.FINE, "Ignored {0} property: read only", name);
            // read only
            continue;
        }
        if (setter.getAnnotation(Deprecated.class) != null) {
            LOGGER.log(Level.FINE, "Ignored {0} property: deprecated", name);
            // not actually public
            continue;
        }
        if (setter.getAnnotation(Restricted.class) != null) {
            LOGGER.log(Level.FINE, "Ignored {0} property: restricted", name);
            // not actually public     - require access-modifier 1.12
            continue;
        }
        // FIXME move this all into cleaner logic to discover property type
        Type type = setter.getGenericParameterTypes()[0];
        Attribute attribute = detectActualType(name, type);
        if (attribute == null)
            continue;
        attributes.add(attribute);
        final Method getter = p.getReadMethod();
        if (getter != null) {
            final Exported annotation = getter.getAnnotation(Exported.class);
            if (annotation != null && isNotBlank(annotation.name())) {
                attribute.preferredName(annotation.name());
            }
        }
        // See https://github.com/jenkinsci/structs-plugin/pull/18
        final Symbol s = setter.getAnnotation(Symbol.class);
        if (s != null) {
            attribute.preferredName(s.value()[0]);
        }
    }
    return attributes;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) Restricted(org.kohsuke.accmod.Restricted) Symbol(org.jenkinsci.Symbol) Method(java.lang.reflect.Method) GenericArrayType(java.lang.reflect.GenericArrayType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Exported(org.kohsuke.stapler.export.Exported) HashSet(java.util.HashSet)

Example 12 with Restricted

use of org.kohsuke.accmod.Restricted in project htmlpublisher-plugin by jenkinsci.

the class HtmlPublisherTarget method sanitizeReportName.

@Restricted(NoExternalUse.class)
public static String sanitizeReportName(String reportName, boolean escapeUnderscores) {
    Pattern p;
    if (escapeUnderscores) {
        p = Pattern.compile("[^a-zA-Z0-9-]");
    } else {
        p = Pattern.compile("[^a-zA-Z0-9-_]");
    }
    Matcher m = p.matcher(reportName);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String match = m.group();
        m.appendReplacement(sb, "_" + Hex.encodeHexString(match.getBytes(StandardCharsets.UTF_8)));
    }
    m.appendTail(sb);
    return sb.toString();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Restricted(org.kohsuke.accmod.Restricted)

Example 13 with Restricted

use of org.kohsuke.accmod.Restricted in project promoted-builds-plugin by jenkinsci.

the class ItemPathResolver method getByPath.

/**
 * Gets an {@link Item} of the specified type by absolute or relative path.
 * <p>
 * The implementation retains the original behavior in {@link PromotedBuildParameterDefinition},
 * but this method also provides a support of multi-level addressing including special markups
 * for the relative addressing.
 * </p>
 * Effectively, the resolution order is following:
 * <ul>
 *   <li><b>Optional</b> Legacy behavior, which can be enabled by {@link #ENABLE_LEGACY_RESOLUTION_AGAINST_ROOT}.
 *       If an item for the name exists on the top Jenkins level, it will be returned</li>
 *   <li>If the path starts with &quot;/&quot;, a global addressing will be used</li>
 *   <li>If the path starts with &quot;./&quot; or &quot;../&quot;, a relative addressing will be used</li>
 *   <li>If there is no prefix, a relative addressing will be tried. If it
 *       fails, the method falls back to a global one</li>
 * </ul>
 * For the relative and absolute addressing the engine supports &quot;.&quot; and
 * &quot;..&quot; markers within the path.
 * The first one points to the current element, the second one - to the upper element.
 * If the search cannot get a new top element (e.g. reached the root), the method returns {@code null}.
 *
 * @param <T> Type of the {@link Item} to be retrieved
 * @param path Path string to the item.
 * @param baseItem Base {@link Item} for the relative addressing. If null,
 *      this addressing approach will be skipped
 * @param type Type of the {@link Item} to be retrieved
 * @return Found {@link Item}. Null if it has not been found by all addressing modes
 *  or the type differs.
 */
@CheckForNull
@SuppressWarnings("unchecked")
@Restricted(NoExternalUse.class)
public static <T extends Item> T getByPath(@Nonnull String path, @CheckForNull Item baseItem, @Nonnull Class<T> type) {
    final Jenkins jenkins = Jenkins.getInstanceOrNull();
    if (jenkins == null) {
        return null;
    }
    // Legacy behavior
    if (isEnableLegacyResolutionAgainstRoot()) {
        TopLevelItem topLevelItem = jenkins.getItem(path);
        if (topLevelItem != null && type.isAssignableFrom(topLevelItem.getClass())) {
            return (T) topLevelItem;
        }
    }
    // Explicit global addressing
    if (path.startsWith("/")) {
        return findPath(jenkins, path.substring(1), type);
    }
    // Try the relative addressing if possible
    if (baseItem != null) {
        final ItemGroup<?> relativeRoot = baseItem instanceof ItemGroup<?> ? (ItemGroup<?>) baseItem : baseItem.getParent();
        final T item = findPath(relativeRoot, path, type);
        if (item != null) {
            return item;
        }
    }
    // Fallback to the default behavior (addressing from the Jenkins root)
    return findPath(jenkins, path, type);
}
Also used : Jenkins(jenkins.model.Jenkins) TopLevelItem(hudson.model.TopLevelItem) Restricted(org.kohsuke.accmod.Restricted) CheckForNull(javax.annotation.CheckForNull)

Example 14 with Restricted

use of org.kohsuke.accmod.Restricted in project workflow-cps-plugin by jenkinsci.

the class ReplayAction method doRun.

@Restricted(DoNotUse.class)
@RequirePOST
public void doRun(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
    if (!isEnabled() || !(isReplayableSandboxTest())) {
        // AccessDeniedException2 requires us to look up the specific Permission
        throw new AccessDeniedException("not allowed to replay");
    }
    JSONObject form = req.getSubmittedForm();
    // Copy originalLoadedScripts, replacing values with those from the form wherever defined.
    Map<String, String> replacementLoadedScripts = new HashMap<>();
    for (Map.Entry<String, String> entry : getOriginalLoadedScripts().entrySet()) {
        // optString since you might be replaying a running build, which might have loaded a script after the page load but before submission.
        replacementLoadedScripts.put(entry.getKey(), form.optString(entry.getKey().replace('.', '_'), entry.getValue()));
    }
    if (run(form.getString("mainScript"), replacementLoadedScripts) == null) {
        throw HttpResponses.error(SC_CONFLICT, new IOException(run.getParent().getFullName() + " is not buildable"));
    }
    // back to WorkflowJob; new build might not start instantly so cannot redirect to it
    rsp.sendRedirect("../..");
}
Also used : AccessDeniedException(org.acegisecurity.AccessDeniedException) JSONObject(net.sf.json.JSONObject) HashMap(java.util.HashMap) IOException(java.io.IOException) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) RequirePOST(org.kohsuke.stapler.interceptor.RequirePOST) Restricted(org.kohsuke.accmod.Restricted)

Example 15 with Restricted

use of org.kohsuke.accmod.Restricted in project workflow-cps-plugin by jenkinsci.

the class Snippetizer method doGenerateSnippet.

// accessed via REST API
@Restricted(DoNotUse.class)
public HttpResponse doGenerateSnippet(StaplerRequest req, @QueryParameter String json) throws Exception {
    // TODO is there not an easier way to do this? Maybe Descriptor.newInstancesFromHeteroList on a one-element JSONArray?
    JSONObject jsonO = JSONObject.fromObject(json);
    Jenkins j = Jenkins.get();
    Class<?> c = j.getPluginManager().uberClassLoader.loadClass(jsonO.getString("stapler-class"));
    Descriptor descriptor = j.getDescriptor(c.asSubclass(Describable.class));
    if (descriptor == null) {
        return HttpResponses.text("<could not find " + c.getName() + ">");
    }
    Object o;
    try {
        o = descriptor.newInstance(req, jsonO);
    } catch (RuntimeException x) {
        // e.g. IllegalArgumentException
        return HttpResponses.text(Functions.printThrowable(x));
    }
    try {
        Step step = null;
        if (o instanceof Step) {
            step = (Step) o;
        } else {
            // Look for a metastep which could take this as its delegate.
            for (StepDescriptor d : StepDescriptor.allMeta()) {
                if (d.getMetaStepArgumentType().isInstance(o)) {
                    DescribableModel<?> m = DescribableModel.of(d.clazz);
                    DescribableParameter soleRequiredParameter = m.getSoleRequiredParameter();
                    if (soleRequiredParameter != null) {
                        step = d.newInstance(Collections.singletonMap(soleRequiredParameter.getName(), o));
                        break;
                    }
                }
            }
        }
        if (step == null) {
            return HttpResponses.text("Cannot find a step corresponding to " + o.getClass().getName());
        }
        String groovy = step2Groovy(step);
        if (descriptor instanceof StepDescriptor && ((StepDescriptor) descriptor).isAdvanced()) {
            String warning = Messages.Snippetizer_this_step_should_not_normally_be_used_in();
            groovy = "// " + warning + "\n" + groovy;
        }
        return HttpResponses.text(groovy);
    } catch (UnsupportedOperationException x) {
        Logger.getLogger(CpsFlowExecution.class.getName()).log(Level.WARNING, "failed to render " + json, x);
        return HttpResponses.text(x.getMessage());
    }
}
Also used : DescribableParameter(org.jenkinsci.plugins.structs.describable.DescribableParameter) UninstantiatedDescribable(org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable) Describable(hudson.model.Describable) Step(org.jenkinsci.plugins.workflow.steps.Step) SimpleBuildStep(jenkins.tasks.SimpleBuildStep) Jenkins(jenkins.model.Jenkins) JSONObject(net.sf.json.JSONObject) BuildStepDescriptor(hudson.tasks.BuildStepDescriptor) Descriptor(hudson.model.Descriptor) StepDescriptor(org.jenkinsci.plugins.workflow.steps.StepDescriptor) BuildStepDescriptor(hudson.tasks.BuildStepDescriptor) StepDescriptor(org.jenkinsci.plugins.workflow.steps.StepDescriptor) JSONObject(net.sf.json.JSONObject) Restricted(org.kohsuke.accmod.Restricted)

Aggregations

Restricted (org.kohsuke.accmod.Restricted)22 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 File (java.io.File)5 HashMap (java.util.HashMap)4 RequirePOST (org.kohsuke.stapler.interceptor.RequirePOST)4 YamlSource (io.jenkins.plugins.casc.yaml.YamlSource)3 Method (java.lang.reflect.Method)3 URL (java.net.URL)3 PathMatcher (java.nio.file.PathMatcher)3 Map (java.util.Map)3 Jenkins (jenkins.model.Jenkins)3 JSONArray (net.sf.json.JSONArray)3 JSONObject (net.sf.json.JSONObject)3 CheckForNull (edu.umd.cs.findbugs.annotations.CheckForNull)2 NonNull (edu.umd.cs.findbugs.annotations.NonNull)2 Describable (hudson.model.Describable)2 BuildStepDescriptor (hudson.tasks.BuildStepDescriptor)2 CNode (io.jenkins.plugins.casc.model.CNode)2 Source (io.jenkins.plugins.casc.model.Source)2