jenkins.model.Jenkins Java Examples

The following examples show how to use jenkins.model.Jenkins. 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 File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 6 votes vote down vote up
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 #2
Source File: BuildScanner.java    From acunetix-plugin with 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 File: KubernetesTestUtil.java    From kubernetes-plugin with 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 File: BranchMetadataTest.java    From blueocean-plugin with 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 #5
Source File: UserImpl.java    From blueocean-plugin with 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 #6
Source File: GiteaServer.java    From gitea-plugin with 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 #7
Source File: PipelineActivityStatePreloader.java    From blueocean-plugin with 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 #8
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
@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 #9
Source File: TopReadmeTest.java    From configuration-as-code-plugin with 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 #10
Source File: AxivionSuite.java    From warnings-ng-plugin with 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 #11
Source File: GitLabHookCreator.java    From gitlab-branch-source-plugin with 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 #12
Source File: ClusterConfig.java    From jenkins-client-plugin with 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 #13
Source File: OrganizationImpl.java    From blueocean-plugin with 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 #14
Source File: MergeRequestBuildAction.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public void execute() {
    if (!(project instanceof Job<?, ?>)) {
        throw HttpResponses.errorWithoutStack(409, "Merge Request Hook is not supported for this project");
    }
    ACL.impersonate(ACL.SYSTEM, new TriggerNotifier(project, secretToken, Jenkins.getAuthentication()) {
        @Override
        protected void performOnPost(GitLabPushTrigger trigger) {
            trigger.onPost(mergeRequestHook);
        }
    });
    throw HttpResponses.ok();
}
 
Example #15
Source File: GithubOrgFolderPermissionsTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void canNotCreateWhenHaveNoPermissionOnDefaultOrg() throws Exception {
    MockAuthorizationStrategy authz = new MockAuthorizationStrategy();
    authz.grant(Item.READ, Jenkins.READ).everywhere().to(user);
    j.jenkins.setAuthorizationStrategy(authz);
    // refresh the JWT token otherwise all hell breaks loose.
    jwtToken = getJwtToken(j.jenkins, "vivek", "vivek");
    createGithubPipeline(false);
}
 
Example #16
Source File: DockerCloud.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public static DockerCloud getCloudByName(String name) {
    final Cloud cloud = Jenkins.getInstance().getCloud(name);
    if (cloud instanceof DockerCloud) {
        return (DockerCloud) cloud;
    }

    if (isNull(cloud)) {
        throw new RuntimeException("Cloud " + name + "not found");
    }

    return null;
}
 
Example #17
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReplace(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String newSource = request.getParameter("_.newSource");
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    File file = new File(Util.fixNull(normalizedSource));
    if (file.exists() || ConfigurationAsCode.isSupportedURI(normalizedSource)) {
        List<String> candidatePaths = Collections.singletonList(normalizedSource);
        List<YamlSource> candidates = getConfigFromSources(candidatePaths);
        if (canApplyFrom(candidates)) {
            sources = candidatePaths;
            configureWith(getConfigFromSources(getSources()));
            CasCGlobalConfig config = GlobalConfiguration.all().get(CasCGlobalConfig.class);
            if (config != null) {
                config.setConfigurationPath(normalizedSource);
                config.save();
            }
            LOGGER.log(Level.FINE, "Replace configuration with: " + normalizedSource);
        } else {
            LOGGER.log(Level.WARNING, "Provided sources could not be applied");
            // todo: show message in UI
        }
    } else {
        LOGGER.log(Level.FINE, "No such source exists, applying default");
        // May be do nothing instead?
        configure();
    }
    response.sendRedirect("");
}
 
Example #18
Source File: ExportConfigurationCommand.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected int run() throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        return -1;
    }


    ConfigurationAsCode.get().export(stdout);
    return 0;
}
 
Example #19
Source File: JenkinsConfiguratorTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("ConfigureLabels.yml")
public void shouldImportLabelAtoms() {
    LabelAtom label1 = Jenkins.get().getLabelAtom("label1");
    assertNotNull(label1);
    assertThat(label1.getProperties(), hasSize(2));
    assertEquals(2, label1.getProperties().get(TestProperty.class).value);
    assertEquals(4, label1.getProperties().get(AnotherTestProperty.class).otherProperty);

    LabelAtom label2 = Jenkins.get().getLabelAtom("label2");
    assertNotNull(label2);
    assertThat(label2.getProperties(), hasSize(1));
    assertEquals(3, label2.getProperties().get(TestProperty.class).value);
}
 
Example #20
Source File: GlobalConfigurationCategoryConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@CheckForNull
@Override
public CNode describe(GlobalConfigurationCategory instance, ConfigurationContext context) {

    final Mapping mapping = new Mapping();
    Jenkins.get().getExtensionList(Descriptor.class).stream()
        .filter(this::filterDescriptors)
        .forEach(d -> describe(d, mapping, context));
    return mapping;
}
 
Example #21
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * 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 #22
Source File: TestUtility.java    From gitlab-plugin with 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)));
        }
    }
}
 
Example #23
Source File: MavenReport.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
public synchronized Collection<Job> getDownstreamJobs() {
    List<String> downstreamJobFullNames = GlobalPipelineMavenConfig.get().getDao().listDownstreamJobs(run.getParent().getFullName(), run.getNumber());
    return downstreamJobFullNames.stream().map(jobFullName -> {
        if (jobFullName == null) {
            return null;
        }
        // security / authorization is checked by Jenkins#getItemByFullName
        try {
            return Jenkins.getInstance().getItemByFullName(jobFullName, Job.class);
        } catch (AccessDeniedException e) {
            return null;
        }
    }).filter(Objects::nonNull).collect(Collectors.toList());
}
 
Example #24
Source File: MavenConfigurator.java    From configuration-as-code-plugin with 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 #25
Source File: GitLabRequireOrganizationMembershipACL.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
private boolean currentUriPathEquals( String specificPath ) {
     String requestUri = requestURI();
     Jenkins jenkins = Jenkins.getInstance();
     if (jenkins != null && requestUri != null) {
String basePath = URI.create(jenkins.getRootUrl()).getPath();
         return URI.create(requestUri).getPath().equals(basePath + specificPath);
     } else {
         return false;
     }
 }
 
Example #26
Source File: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with MIT License 5 votes vote down vote up
@CheckForNull
private StandardUsernamePasswordCredentials getCredential(@Nonnull String id) {
    StandardUsernamePasswordCredentials credential = null;
    List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials(
            StandardUsernamePasswordCredentials.class, Jenkins.get(), ACL.SYSTEM, Collections.emptyList());
    IdMatcher matcher = new IdMatcher(id);
    for (StandardUsernamePasswordCredentials c : credentials) {
        if (matcher.matches(c)) {
            credential = c;
        }
    }
    return credential;
}
 
Example #27
Source File: Listener.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
    if(!set) {
        Jenkins.getActiveInstance().setSecurityRealm(new DummySecurityRealm());
        set = true;
    }

}
 
Example #28
Source File: KubernetesFolderProperty.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public AbstractFolderProperty<?> reconfigure(StaplerRequest req, JSONObject form) throws FormException {
    if (form == null) {
        return null;
    }

    // ignore modifications silently and return the unmodified object if the user
    // does not have the ADMINISTER Permission
    if (!userHasAdministerPermission()) {
        return this;
    }

    try {
        Set<String> inheritedGrants = new HashSet<>();
        collectAllowedClouds(inheritedGrants, getOwner().getParent());

        Set<String> permittedClouds = new HashSet<>();
        JSONArray names = form.names();
        if (names != null) {
            for (Object name : names) {
                String strName = (String) name;

                if (strName.startsWith(PREFIX_USAGE_PERMISSION) && form.getBoolean(strName)) {
                    String cloud = StringUtils.replaceOnce(strName, PREFIX_USAGE_PERMISSION, "");

                    if (isUsageRestrictedKubernetesCloud(Jenkins.get().getCloud(cloud))
                            && !inheritedGrants.contains(cloud)) {
                        permittedClouds.add(cloud);
                    }
                }
            }
        }
        this.permittedClouds.clear();
        this.permittedClouds.addAll(permittedClouds);
    } catch (JSONException e) {
        LOGGER.log(Level.SEVERE, e, () -> "reconfigure failed: " + e.getMessage());
    }
    return this;
}
 
Example #29
Source File: Git.java    From git-client-plugin with 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 #30
Source File: EC2FleetCloudTest.java    From ec2-spot-jenkins-plugin with 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);
}