Java Code Examples for jenkins.model.Jenkins

The following examples show how to use jenkins.model.Jenkins. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: blueocean-plugin   Source File: BranchMetadataTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() {
    Caches.BRANCH_METADATA.invalidateAll();

    jenkins = mock(Jenkins.class);

    PowerMockito.mockStatic(Jenkins.class);
    when(Jenkins.getInstance()).thenReturn(jenkins);

    when(jenkins.getFullName()).thenReturn("");

    job = mock(Job.class);
    when(job.getParent()).thenReturn(jenkins);
    when(job.getFullName()).thenReturn("BobsPipeline");
    when(jenkins.getItemByFullName("BobsPipeline", Job.class)).thenReturn(job);

    org = mock(BlueOrganization.class);
    branch = new BranchImpl(org, job, new Link("foo"));
}
 
Example 2
Source Project: acunetix-plugin   Source File: BuildScanner.java    License: MIT License 6 votes vote down vote up
public ListBoxModel doFillGApiKeyIDItems(
        @AncestorInPath Item item) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    } else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    }
    if (gApiKeyID != null) {
        result.includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.withId(gApiKeyID)));
    }
    return result
            .includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                    Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.instanceOf(StringCredentials.class)));
}
 
Example 3
Source Project: kubernetes-plugin   Source File: KubernetesTestUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void setupHost() throws Exception {
    // Agents running in Kubernetes (minikube) need to connect to this server, so localhost does not work
    URL url = new URL(JenkinsLocationConfiguration.get().getUrl());
    String hostAddress = System.getProperty("jenkins.host.address");
    if (org.apache.commons.lang3.StringUtils.isBlank(hostAddress)) {
        hostAddress = InetAddress.getLocalHost().getHostAddress();
    }
    System.err.println("Calling home to address: " + hostAddress);
    URL nonLocalhostUrl = new URL(url.getProtocol(), hostAddress, url.getPort(),
            url.getFile());
    // TODO better to set KUBERNETES_JENKINS_URL
    JenkinsLocationConfiguration.get().setUrl(nonLocalhostUrl.toString());

    Integer slaveAgentPort = Integer.getInteger("slaveAgentPort");
    if (slaveAgentPort != null) {
        Jenkins.get().setSlaveAgentPort(slaveAgentPort);
    }
}
 
Example 4
Source Project: blueocean-plugin   Source File: UserImpl.java    License: MIT License 6 votes vote down vote up
@Override
public BlueFavoriteContainer getFavorites() {

    /*
     * Get the user id using authenticated user. User.current() returns authenticated user using security realm and
     * associated IdStrategy to get a consistent id.
     *
     * @see IdStrategy#keyFor(String)
     * @see IdStrategy.CaseInsensitive#keyFor(String)
     *
     */
    User u = User.current();
    String expectedUserId = u != null ? u.getId(): Jenkins.ANONYMOUS.getName();

    if(!user.getId().equals(expectedUserId)) {
        throw new ForbiddenException("This user '" + expectedUserId + "' cannot access resource owned by '" + user.getId() + "'");
    }
    return new FavoriteContainerImpl(this, this);
}
 
Example 5
Source Project: gitea-plugin   Source File: GiteaServer.java    License: MIT License 6 votes vote down vote up
/**
 * Looks up the {@link StandardCredentials} to use for auto-management of hooks.
 *
 * @return the credentials or {@code null}.
 */
@CheckForNull
public StandardCredentials credentials() {
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.get(),
                    ACL.SYSTEM,
                    URIRequirementBuilder.fromUri(serverUrl).build()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(GiteaAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example 6
Source Project: blueocean-plugin   Source File: PipelineActivityStatePreloader.java    License: MIT License 6 votes vote down vote up
private BluePipeline getPipeline(BlueUrlTokenizer blueUrl) {
    if (addPipelineRuns(blueUrl)) {
        Jenkins jenkins = Jenkins.getInstance();
        String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);

        try {
            Item pipelineJob = jenkins.getItemByFullName(pipelineFullName);
            return (BluePipeline) BluePipelineFactory.resolve(pipelineJob);
        } catch (Exception e) {
            LOGGER.log(Level.FINE, String.format("Unable to find Job named '%s'.", pipelineFullName), e);
            return null;
        }
    }

    return null;
}
 
Example 7
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example 8
Source Project: configuration-as-code-plugin   Source File: TopReadmeTest.java    License: MIT License 6 votes vote down vote up
@Test
@ConfiguredWithReadme("README.md#0")
public void configure_demo_first_code_block() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
    final LDAPSecurityRealm securityRealm = (LDAPSecurityRealm) jenkins.getSecurityRealm();
    assertEquals(1, securityRealm.getConfigurations().size());
    assertEquals(50000, jenkins.getSlaveAgentPort());

    assertEquals(1, jenkins.getNodes().size());
    assertEquals("static-agent", jenkins.getNode("static-agent").getNodeName());

    final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
    assertEquals(1, gitTool.getInstallations().length);

    List<BasicSSHUserPrivateKey> sshPrivateKeys = CredentialsProvider.lookupCredentials(
        BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList()
    );
    assertThat(sshPrivateKeys, hasSize(1));

    final BasicSSHUserPrivateKey ssh_with_passphrase = sshPrivateKeys.get(0);
    assertThat(ssh_with_passphrase.getPassphrase().getPlainText(), equalTo("ABCD"));

    final DirectEntryPrivateKeySource source = (DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
    assertThat(source.getPrivateKey().getPlainText(), equalTo("s3cr3t"));
}
 
Example 9
Source Project: warnings-ng-plugin   Source File: AxivionSuite.java    License: MIT License 6 votes vote down vote up
/**
 * Shows the user all available credential id items.
 *
 * @param item
 *         jenkins configuration
 * @param credentialsId
 *         current used credentials
 *
 * @return a list view of all credential ids
 */
public ListBoxModel doFillCredentialsIdItems(
        @AncestorInPath final Item item, @QueryParameter final String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!new JenkinsFacade().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    return result.includeAs(
            ACL.SYSTEM,
            item,
            StandardUsernamePasswordCredentials.class,
            Collections.emptyList())
            .includeCurrentValue(credentialsId);
}
 
Example 10
Source Project: gitlab-branch-source-plugin   Source File: GitLabHookCreator.java    License: MIT License 6 votes vote down vote up
/**
 * @param server the {@code GitLabServer} for which the hooks URL would be created. If not {@code null} and it
 *        has a {@link GitLabServer#getHooksRootUrl()}, then the hook URL will be based on this root URL.
 *        Otherwise, the hook URL will be based on {@link Jenkins#getRootUrl()}.
 * @param isWebHook {@code true} to get the webhook URL, {@code false} for the systemhook URL
 * @return a webhook or systemhook URL
 */
public static String getHookUrl(GitLabServer server, boolean isWebHook) {
    String rootUrl = (server == null || server.getHooksRootUrl() == null)
            ? Jenkins.get().getRootUrl()
            : server.getHooksRootUrl();
    if (StringUtils.isBlank(rootUrl)) {
        return "";
    }
    checkURL(rootUrl);
    UriTemplateBuilder templateBuilder = UriTemplate.buildFromTemplate(rootUrl);
    if (isWebHook) {
        templateBuilder.literal("gitlab-webhook");
    } else {
        templateBuilder.literal("gitlab-systemhook");
    }
    return templateBuilder.literal("/post").build().expand();
}
 
Example 11
Source Project: jenkins-client-plugin   Source File: ClusterConfig.java    License: Apache License 2.0 6 votes vote down vote up
public static ListBoxModel doFillCredentialsIdItems(String credentialsId) {
    if (credentialsId == null) {
        credentialsId = "";
    }

    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
        // Important! Otherwise you expose credentials metadata to random
        // web requests.
        return new StandardListBoxModel()
                .includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeAs(ACL.SYSTEM, Jenkins.getInstance(),
                    OpenShiftTokenCredentials.class)
            // .includeAs(ACL.SYSTEM, Jenkins.getInstance(),
            // StandardUsernamePasswordCredentials.class)
            // .includeAs(ACL.SYSTEM, Jenkins.getInstance(),
            // StandardCertificateCredentials.class)
            // TODO: Make own type for token or use the existing token
            // generator auth type used by sync plugin? or kubernetes?
            .includeCurrentValue(credentialsId);
}
 
Example 12
Source Project: blueocean-plugin   Source File: OrganizationImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Give plugins chance to handle this API route.
 *
 * @param route URL path that needs handling. e.g. for requested url /rest/organizations/:id/xyz,  route param value will be 'xyz'
 * @return stapler object that can handle give route. Could be null
 */
public Object getDynamic(String route){
    //First look for OrganizationActions
    for(OrganizationRoute organizationRoute: ExtensionList.lookup(OrganizationRoute.class)){
        if(organizationRoute.getUrlName() != null && organizationRoute.getUrlName().equals(route)){
            return wrap(organizationRoute);
        }
    }

    // No OrganizationRoute found, now lookup in available actions from Jenkins instance serving root
    for(Action action:Jenkins.getInstance().getActions()) {
        String urlName = action.getUrlName();
        if (urlName != null && urlName.equals(route)) {
            return wrap(action);
        }
    }
    return null;
}
 
Example 13
private Job getParentJob() {
    Job context = null;
    List<Job> jobs = Objects.requireNonNull(Jenkins.getInstance()).getAllItems(Job.class);

    for (Job job : jobs) {
        if (!(job instanceof TopLevelItem)) continue;

        ParametersDefinitionProperty property = (ParametersDefinitionProperty) job.getProperty(ParametersDefinitionProperty.class);

        if (property != null) {
            List<ParameterDefinition> parameterDefinitions = property.getParameterDefinitions();

            if (parameterDefinitions != null) {
                for (ParameterDefinition pd : parameterDefinitions) {
                    if (pd instanceof ListGitBranchesParameterDefinition && ((ListGitBranchesParameterDefinition) pd).compareTo(this) == 0) {
                        context = job;
                        break;
                    }
                }
            }
        }
    }

    return context;
}
 
Example 14
Source Project: configuration-as-code-plugin   Source File: ConfigurationAsCode.java    License: MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doApply(StaplerRequest req, StaplerResponse res) throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    configureWith(YamlSource.of(req));
}
 
Example 15
/**
 * Returns the {@link FolderRole}s used by the {@link FolderBasedAuthorizationStrategy}.
 *
 * @return the {@link FolderRole}s used by the {@link FolderBasedAuthorizationStrategy}
 * @throws IllegalStateException when {@link Jenkins#getAuthorizationStrategy()} is
 *                               not {@link FolderBasedAuthorizationStrategy}
 */
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<FolderRole> getFolderRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getFolderRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example 16
Source Project: gitlab-plugin   Source File: GitLabRule.java    License: GNU General Public License v2.0 5 votes vote down vote up
public GitLabConnectionProperty createGitLabConnectionProperty() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(getApiToken())));
        }
    }

    GitLabConnectionConfig config = Jenkins.getInstance().getDescriptorByType(GitLabConnectionConfig.class);
    GitLabConnection connection = new GitLabConnection("test", url, API_TOKEN_ID, new V3GitLabClientBuilder(), true,10, 10);
    config.addConnection(connection);
    config.save();
    return new GitLabConnectionProperty(connection.getName());
}
 
Example 17
Source Project: pipeline-maven-plugin   Source File: GlobalPipelineMavenConfig.java    License: MIT License 5 votes vote down vote up
public ListBoxModel doFillJdbcCredentialsIdItems() {
    // use deprecated "withMatching" because, even after 20 mins of research,
    // I didn't understand how to use the new "recommended" API
    return new StandardListBoxModel()
            .includeEmptyValue()
            .withMatching(
                    CredentialsMatchers.always(),
                    CredentialsProvider.lookupCredentials(UsernamePasswordCredentials.class,
                            Jenkins.getInstance(),
                            ACL.SYSTEM,
                            Collections.EMPTY_LIST));
}
 
Example 18
@Before
public void setup() throws IOException {
    gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab";
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
        }
    }
}
 
Example 19
Source Project: docker-plugin   Source File: DockerComputerAttachConnector.java    License: MIT License 5 votes vote down vote up
private static EnvVars calculateVariablesForVariableSubstitution(@Nonnull final String javaExe,
        @Nonnull final String jvmArgs, @Nonnull final String jarName, @Nonnull final String remoteFs,
        @Nonnull final String jenkinsUrl) throws IOException, InterruptedException {
    final EnvVars knownVariables = new EnvVars();
    final Jenkins j = Jenkins.getInstance();
    addEnvVars(knownVariables, j.getGlobalNodeProperties());
    for (final ArgumentVariables v : ArgumentVariables.values()) {
        // This switch statement MUST handle all possible
        // values of v.
        final String argValue;
        switch (v) {
            case JavaExe :
                argValue = javaExe;
                break;
            case JvmArgs :
                argValue = jvmArgs;
                break;
            case JarName :
                argValue = jarName;
                break;
            case RemoteFs :
                argValue = remoteFs;
                break;
            case JenkinsUrl :
                argValue = jenkinsUrl;
                break;
            default :
                final String msg = "Internal code error: Switch statement is missing \"case " + v.name()
                        + " : argValue = ... ; break;\" code.";
                // If this line throws an exception then it's because
                // someone has added a new variable to the enum without
                // adding code above to handle it.
                // The two have to be kept in step in order to
                // ensure that the help text stays in step.
                throw new RuntimeException(msg);
        }
        addEnvVar(knownVariables, v.getName(), argValue);
    }
    return knownVariables;
}
 
Example 20
Source Project: folder-auth-plugin   Source File: ConfigurationAsCodeTest.java    License: MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config3.yml")
public void configurationImportWithHumanReadableTest() {
    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("admin"))) {
        assertTrue(j.jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("user1"))) {
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(j.jenkins.hasPermission(Jenkins.ADMINISTER));

        assertTrue(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.CONFIGURE));
        assertFalse(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.DELETE));
    }
}
 
Example 21
@Override
public List<String> possibleValues() {
    final List<Descriptor> descriptors = Jenkins.get().getDescriptorList(type);
    return descriptors.stream()
            .map(d -> getPreferredSymbol(d, type, d.getKlass().toJavaClass()))
            .collect(Collectors.toList());
}
 
Example 22
@Before
public void setUp() {
    mockStatic(Jenkins.class);
    Jenkins jenkins = mock(Jenkins.class);
    File rootDir = new File(".");
    when(jenkins.getRootDir()).thenReturn(rootDir);
    when(Jenkins.getInstance()).thenReturn(jenkins);
}
 
Example 23
public ListBoxModel doFillCloudNameItems() {
    ListBoxModel items = new ListBoxModel();
    Jenkins.getInstance().clouds.getAll(DockerCloud.class)
        .forEach(dockerCloud ->
            items.add(dockerCloud.getDisplayName())
        );
    return items;
}
 
Example 24
Source Project: configuration-as-code-plugin   Source File: JenkinsConfigTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldExportEvenOnError() throws Exception {
    Jenkins j = Jenkins.get();
    j.setCrumbIssuer(new BrokenCrumbIssuer("bar"));
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ConfigurationAsCode.get().export(out);
    final String s = out.toString();
    assertThat(s, is(not(emptyOrNullString())));
}
 
Example 25
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIDItems(
        @AncestorInPath Jenkins context,
        @QueryParameter String remoteBase) {
    return ConduitCredentialsDescriptor.doFillCredentialsIDItems(
            context);
}
 
Example 26
Source Project: github-branch-source-plugin   Source File: EndpointTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    MockAuthorizationStrategy auth = new MockAuthorizationStrategy();
    auth.grant(Jenkins.ADMINISTER).everywhere().to("alice");
    auth.grant(Jenkins.READ).everywhere().toEveryone();
    j.jenkins.setAuthorizationStrategy(auth);
    testUrl = Util.rawEncode(j.getURL().toString() + "testroot/");
}
 
Example 27
Source Project: ec2-spot-jenkins-plugin   Source File: EC2FleetCloudTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    spotFleetRequestConfig1 = new SpotFleetRequestConfig();
    spotFleetRequestConfig1.setSpotFleetRequestState(BatchState.Active);
    spotFleetRequestConfig1.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig2 = new SpotFleetRequestConfig();
    spotFleetRequestConfig2.setSpotFleetRequestState(BatchState.Submitted);
    spotFleetRequestConfig2.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig3 = new SpotFleetRequestConfig();
    spotFleetRequestConfig3.setSpotFleetRequestState(BatchState.Modifying);
    spotFleetRequestConfig3.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig4 = new SpotFleetRequestConfig();
    spotFleetRequestConfig4.setSpotFleetRequestState(BatchState.Cancelled);
    spotFleetRequestConfig4.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig5 = new SpotFleetRequestConfig();
    spotFleetRequestConfig5.setSpotFleetRequestState(BatchState.Cancelled_running);
    spotFleetRequestConfig5.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig6 = new SpotFleetRequestConfig();
    spotFleetRequestConfig6.setSpotFleetRequestState(BatchState.Cancelled_terminating);
    spotFleetRequestConfig6.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig7 = new SpotFleetRequestConfig();
    spotFleetRequestConfig7.setSpotFleetRequestState(BatchState.Failed);
    spotFleetRequestConfig7.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Maintain));
    spotFleetRequestConfig8 = new SpotFleetRequestConfig();
    spotFleetRequestConfig8.setSpotFleetRequestState(BatchState.Active);
    spotFleetRequestConfig8.setSpotFleetRequestConfig(new SpotFleetRequestConfigData().withType(FleetType.Request));

    Registry.setEc2Api(ec2Api);

    PowerMockito.mockStatic(LabelFinder.class);

    PowerMockito.mockStatic(FleetStateStats.class);

    PowerMockito.mockStatic(Jenkins.class);
    PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins);
}
 
Example 28
Source Project: git-client-plugin   Source File: Git.java    License: MIT License 5 votes vote down vote up
/**
 * {@link org.jenkinsci.plugins.gitclient.GitClient} implementation. The {@link org.jenkinsci.plugins.gitclient.GitClient} interface
 * provides the key operations which can be performed on a git repository.
 *
 * @return a {@link org.jenkinsci.plugins.gitclient.GitClient} for git operations on the repository
 * @throws java.io.IOException if any IO failure
 * @throws java.lang.InterruptedException if interrupted.
 */
public GitClient getClient() throws IOException, InterruptedException {
    jenkins.MasterToSlaveFileCallable<GitClient> callable = new GitAPIMasterToSlaveFileCallable();
    GitClient git = (repository!=null ? repository.act(callable) : callable.invoke(null,null));
    Jenkins jenkinsInstance = Jenkins.getInstance();
    if (jenkinsInstance != null && git != null)
        git.setProxy(jenkinsInstance.proxy);
    return git;
}
 
Example 29
Source Project: configuration-as-code-plugin   Source File: MavenConfigurator.java    License: MIT License 5 votes vote down vote up
@NonNull
@Override
public Set<Attribute<GlobalMavenConfig,?>> describe() {
    final Set<Attribute<GlobalMavenConfig,?>> attributes = super.describe();
    final Descriptor descriptor = Jenkins.get().getDescriptorOrDie(Maven.class);
    final Configurator<Descriptor> task = new DescriptorConfigurator(descriptor);

    for (Attribute attribute : task.describe()) {
        attributes.add(new Attribute<GlobalMavenConfig,Object>(attribute.getName(), attribute.getType())
            .multiple(attribute.isMultiple())
            .getter(g -> attribute.getValue(descriptor))
            .setter((g,v) -> attribute.setValue(descriptor,v)));
    }
    return attributes;
}
 
Example 30
Source Project: gitlab-plugin   Source File: TestUtility.java    License: GNU General Public License v2.0 5 votes vote down vote up
static void addGitLabApiToken() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
        }
    }
}