hudson.util.VersionNumber Java Examples

The following examples show how to use hudson.util.VersionNumber. 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: Plugin.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
public Plugin(String name, String version, String url, String groupId) {
    this.originalName = name;
    this.name = name;
    if (StringUtils.isEmpty(version)) {
        version = "latest";
    }
    this.version = new VersionNumber(version);
    this.url = url;
    this.dependencies = new ArrayList<>();
    this.parent = this;
    this.groupId = groupId;
    this.securityWarnings = new ArrayList<>();
    if (version.equals("latest")) {
        latest = true;
    }
    if (version.equals("experimental")) {
        experimental = true;
    }
}
 
Example #2
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
@Test
public void checkVersionSpecificUpdateCenterTest() throws Exception {
    //Test where version specific update center exists
    pm.setJenkinsVersion(new VersionNumber("2.176"));

    mockStatic(HttpClients.class);
    CloseableHttpClient httpclient = mock(CloseableHttpClient.class);

    when(HttpClients.createSystem()).thenReturn(httpclient);
    HttpHead httphead = mock(HttpHead.class);

    whenNew(HttpHead.class).withAnyArguments().thenReturn(httphead);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(httpclient.execute(httphead)).thenReturn(response);

    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);

    int statusCode = HttpStatus.SC_OK;
    when(statusLine.getStatusCode()).thenReturn(statusCode);

    pm.checkAndSetLatestUpdateCenter();

    String expected = dirName(cfg.getJenkinsUc()) + pm.getJenkinsVersion() + Settings.DEFAULT_UPDATE_CENTER_FILENAME;
    assertEquals(expected, pm.getJenkinsUCLatest());
}
 
Example #3
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
@Test
public void checkVersionSpecificUpdateCenterBadRequestTest() throws Exception {
    pm.setJenkinsVersion(new VersionNumber("2.176"));

    mockStatic(HttpClients.class);
    CloseableHttpClient httpclient = mock(CloseableHttpClient.class);

    when(HttpClients.createSystem()).thenReturn(httpclient);
    HttpHead httphead = mock(HttpHead.class);

    whenNew(HttpHead.class).withAnyArguments().thenReturn(httphead);
    CloseableHttpResponse response = mock(CloseableHttpResponse.class);
    when(httpclient.execute(httphead)).thenReturn(response);

    StatusLine statusLine = mock(StatusLine.class);
    when(response.getStatusLine()).thenReturn(statusLine);

    int statusCode = HttpStatus.SC_BAD_REQUEST;
    when(statusLine.getStatusCode()).thenReturn(statusCode);

    pm.checkAndSetLatestUpdateCenter();
    String expected = cfg.getJenkinsUc().toString();
    assertEquals(expected, pm.getJenkinsUCLatest());
}
 
Example #4
Source File: PluginManagerIntegrationTest.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
public static PluginManager initPluginManager(Configurator configurator) throws IOException {
    Config.Builder configBuilder = Config.builder()
            .withJenkinsWar(jenkinsWar.getAbsolutePath())
            .withPluginDir(pluginsDir)
            .withShowAvailableUpdates(true)
            .withIsVerbose(true)
            .withDoDownload(false);
    configurator.configure(configBuilder);
    Config config = configBuilder.build();

    PluginManager pluginManager = new PluginManager(config);
    pluginManager.setCm(new CacheManager(cacheDir.toPath(), true));
    pluginManager.setJenkinsVersion(new VersionNumber("2.222.1"));
    pluginManager.setLatestUcJson(latestUcJson);
    pluginManager.setLatestUcPlugins(latestUcJson.getJSONObject("plugins"));
    pluginManager.setPluginInfoJson(pluginManager.getJson(pluginVersionsFile.toURI().toURL(), "plugin-versions"));

    return pluginManager;
}
 
Example #5
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
/**
 * Downloads a plugin, skipping if already installed or bundled in the war. A plugin's dependencies will be
 * resolved after the plugin is downloaded.
 *
 * @param plugin   to download
 * @param location location to download plugin to. If location is set to null, will download to the plugin folder
 *                 otherwise will download to the temporary location specified.
 * @return boolean signifying if plugin was successful
 */
public boolean downloadPlugin(Plugin plugin, File location) {
    String pluginName = plugin.getName();
    VersionNumber pluginVersion = plugin.getVersion();
    // location will be populated if downloading a plugin to a temp file to determine dependencies
    // even if plugin is already downloaded, still want to download the temp file to parse dependencies to ensure
    // that all dependencies are also installed
    if (location == null && installedPluginVersions.containsKey(pluginName) &&
            installedPluginVersions.get(pluginName).getVersion().isNewerThanOrEqualTo(pluginVersion)) {
        logVerbose(pluginName + " already installed, skipping");
        return true;
    }
    String pluginDownloadUrl = getPluginDownloadUrl(plugin);
    boolean successfulDownload = downloadToFile(pluginDownloadUrl, plugin, location);
    if (successfulDownload && location == null) {
        System.out.println(String.format("%s downloaded successfully", plugin.getName()));
        installedPluginVersions.put(plugin.getName(), plugin);
    }
    return successfulDownload;
}
 
Example #6
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
/**
 * Retrieves the latest available version of a specified plugin.
 *
 * @param pluginName the name of the plugin
 * @return latest version of the specified plugin
 * @throws IllegalStateException Update Center JSON has not been retrieved yet
 */
public VersionNumber getLatestPluginVersion(String pluginName) {
    if (latestPlugins == null) {
        throw new IllegalStateException("List of plugins is not available. Likely Update Center data has not been downloaded yet");
    }

    if (!latestPlugins.has(pluginName)) {
        throw new PluginNotFoundException(String.format("Unable to find plugin %s in update center %s", pluginName,
                jenkinsUcLatest));
    }

    JSONObject pluginInfo = (JSONObject) latestPlugins.get(pluginName);
    String latestPluginVersion = pluginInfo.getString("version");

    return new VersionNumber(latestPluginVersion);
}
 
Example #7
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 6 votes vote down vote up
/**
 * Gets the JSONArray containing plugin a
 *
 * @param plugin to get depedencies for
 * @param ucJson update center json from which to parse dependencies
 * @return JSONArray containing plugin dependencies
 */
public JSONArray getPluginDependencyJsonArray(Plugin plugin, JSONObject ucJson) {
    JSONObject plugins = ucJson.getJSONObject("plugins");
    if (!plugins.has(plugin.getName())) {
        return null;
    }

    JSONObject pluginInfo = (JSONObject) plugins.get(plugin.getName());

    if (ucJson.equals(pluginInfoJson)) {
        //plugin-versions.json has a slightly different structure than other update center json
        if (pluginInfo.has(plugin.getVersion().toString())) {
            JSONObject specificVersionInfo = pluginInfo.getJSONObject(plugin.getVersion().toString());
            plugin.setJenkinsVersion(specificVersionInfo.getString("requiredCore"));
            return (JSONArray) specificVersionInfo.get("dependencies");
        }
    } else {
        plugin.setJenkinsVersion(pluginInfo.getString("requiredCore"));
        //plugin version is latest or experimental
        String version = pluginInfo.getString("version");
        plugin.setVersion(new VersionNumber(version));
        return (JSONArray) pluginInfo.get("dependencies");
    }
    return null;
}
 
Example #8
Source File: CompareVersionsStep.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Override
protected Integer run() throws Exception {
    if (isEmpty(v1) && isEmpty(v2)) {
        if (failIfEmpty) {
            throw new AbortException("Both parameters are empty.");
        }
        return 0;
    }
    if (isEmpty(v1)) {
        if (failIfEmpty) {
            throw new AbortException("v1 is empty.");
        }
        return -1;
    }
    if (isEmpty(v2)) {
        if (failIfEmpty) {
            throw new AbortException("v2 is empty.");
        }
        return 1;
    }
    VersionNumber vn1 = new VersionNumber(v1);
    VersionNumber vn2 = new VersionNumber(v2);
    return vn1.compareTo(vn2);
}
 
Example #9
Source File: WithContainerStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-33510")
@Test public void cd() throws Exception {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            DockerTestUtil.assumeDocker(new VersionNumber("17.12"));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                "node {\n" +
                "  withDockerContainer('ubuntu') {\n" +
                "    sh 'mkdir subdir && echo somecontent > subdir/file'\n" +
                "    dir('subdir') {\n" +
                "      sh 'pwd; tr \"a-z\" \"A-Z\" < file'\n" +
                "    }\n" +
                "  }\n" +
                "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
            story.j.assertLogContains("SOMECONTENT", b);
        }
    });
}
 
Example #10
Source File: ServerInfoAdditionalAnalyticsProperties.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public Map<String, Object> properties(TrackRequest trackReq) {
    Map<String, Object> props = Maps.newHashMap();
    VersionNumber version = Jenkins.getVersion();
    if (version != null && version.toString() != null) {
        props.put("jenkinsVersion", version.toString());
    }
    Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-rest");
    if(plugin != null) {
        props.put("blueoceanVersion", plugin.getWrapper().getVersion());
    }

    return props;
}
 
Example #11
Source File: BackwardCompatibilityTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private static String agentNameToCompareAgainst() {
    VersionNumber currentVersion = Jenkins.getStoredVersion();
    if (currentVersion == null) {
        throw new IllegalArgumentException("Couldn't get jenkins version");
    }
    return currentVersion.isOlderThan(MIN_VERSION_SYMBOL) ? "dumb" : "permanent";
}
 
Example #12
Source File: ObsoleteConfigurationMonitor.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
public String getCss() {
    final VersionNumber version = Jenkins.getVersion();
    if (version == null || version.isNewerThan(new VersionNumber("2.103"))) {
        return "alert alert-warning";
    }
    return "warning";
}
 
Example #13
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void getJenkinsVersionFromWarTest() throws Exception {
    URL warURL = this.getClass().getResource("/jenkinsversiontest.war");
    File testWar = new File(warURL.getFile());

    //the only time the file for a particular war string is created is in the PluginManager constructor
    Config config = Config.builder()
            .withJenkinsWar(testWar.toString())
            .build();
    PluginManager pluginManager = new PluginManager(config);
    assertEquals(new VersionNumber("2.164.1").compareTo(pluginManager.getJenkinsVersionFromWar()), 0);
}
 
Example #14
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void getPluginDownloadUrlTest() {
    Plugin plugin = new Plugin("pluginName", "pluginVersion", "pluginURL", null);

    assertEquals("pluginURL", pm.getPluginDownloadUrl(plugin));

    // Note: As of now (2019/12/18 lmm) there is no 'latest' folder in the cloudbees update center as a sibling of the "download" folder
    //  so this is only applicable on jenkins.io
    Plugin pluginNoUrl = new Plugin("pluginName", "latest", null, null);
    String latestUcUrl = "https://updates.jenkins.io/2.176";
    pm.setJenkinsUCLatest(latestUcUrl + "/update-center.json");
    VersionNumber latestVersion = new VersionNumber("latest");
    String latestUrl = latestUcUrl + "/latest/pluginName.hpi";
    Assert.assertEquals(latestUrl, pm.getPluginDownloadUrl(pluginNoUrl));

    Plugin pluginNoVersion = new Plugin("pluginName", null, null, null);
    assertEquals(latestUrl, pm.getPluginDownloadUrl(pluginNoVersion));

    Plugin pluginExperimentalVersion = new Plugin("pluginName", "experimental", null, null);
    String experimentalUrl = dirName(cfg.getJenkinsUcExperimental()) + "latest/pluginName.hpi";
    Assert.assertEquals(experimentalUrl, pm.getPluginDownloadUrl(pluginExperimentalVersion));

    Plugin pluginIncrementalRepo = new Plugin("pluginName", "2.19-rc289.d09828a05a74", null, "org.jenkins-ci.plugins.pluginName");

    String incrementalUrl = cfg.getJenkinsIncrementalsRepoMirror() +
            "/org/jenkins-ci/plugins/pluginName/pluginName/2.19-rc289.d09828a05a74/pluginName-2.19-rc289.d09828a05a74.hpi";

    assertEquals(incrementalUrl, pm.getPluginDownloadUrl(pluginIncrementalRepo));

    Plugin pluginOtherVersion = new Plugin("pluginName", "otherversion", null, null);
    String otherURL = dirName(cfg.getJenkinsUc().toString()) +
            "download/plugins/pluginName/otherversion/pluginName.hpi";
    assertEquals(otherURL, pm.getPluginDownloadUrl(pluginOtherVersion));
}
 
Example #15
Source File: WithContainerStep.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
Decorator(String container, EnvVars envHost, String ws, String toolName, VersionNumber dockerVersion) {
    this.container = container;
    this.envHost = Util.mapToEnv(envHost);
    this.ws = ws;
    this.toolName = toolName;
    this.hasEnv = dockerVersion != null && dockerVersion.compareTo(new VersionNumber("1.13.0")) >= 0;
    this.hasWorkdir = dockerVersion != null && dockerVersion.compareTo(new VersionNumber("17.12")) >= 0;
}
 
Example #16
Source File: JenkinsMetadata.java    From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 5 votes vote down vote up
private static String getJenkinsVersion() {
    final VersionNumber jenkinsVersion = Jenkins.getVersion();
    if (jenkinsVersion != null) {
        return jenkinsVersion.toString();
    } else {
        return UNKNOWN;
    }
}
 
Example #17
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void resolveDependenciesFromManifestLatestAll() throws IOException {
    Config config = Config.builder()
            .withJenkinsWar(Settings.DEFAULT_WAR)
            .withPluginDir(Files.createTempDirectory("tmpplugins").toFile())
            .withUseLatestAll(true)
            .build();

    PluginManager pluginManager = new PluginManager(config);
    PluginManager pluginManagerSpy = spy(pluginManager);

    Plugin testPlugin = new Plugin("test", "1.1", null, null);
    doReturn(true).when(pluginManagerSpy).downloadPlugin(any(Plugin.class), any(File.class));

    mockStatic(Files.class);
    Path tempPath = mock(Path.class);
    File tempFile = mock(File.class);

    when(Files.createTempFile(any(String.class), any(String.class))).thenReturn(tempPath);
    when(tempPath.toFile()).thenReturn(tempFile);

    doReturn("workflow-scm-step:2.4,workflow-step-api:2.13")
            .when(pluginManagerSpy).getAttributeFromManifest(any(File.class), any(String.class));

    doReturn(new VersionNumber("2.4")).doReturn(new VersionNumber("2.20")).when(pluginManagerSpy).
            getLatestPluginVersion(any(String.class));

    List<Plugin> expectedPlugins = new ArrayList<>();
    expectedPlugins.add(new Plugin("workflow-scm-step", "2.4", null, null));
    expectedPlugins.add(new Plugin("workflow-step-api", "2.20", null, null));

    List<String> expectedPluginInfo = convertPluginsToStrings(expectedPlugins);

    List<Plugin> actualPlugins = pluginManagerSpy.resolveDependenciesFromManifest(testPlugin);
    List<String> actualPluginInfo = convertPluginsToStrings(actualPlugins);

    assertEquals(expectedPluginInfo, actualPluginInfo);
}
 
Example #18
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void resolveDependenciesFromManifestLatestSpecified() throws IOException {
    Config config = Config.builder()
            .withJenkinsWar(Settings.DEFAULT_WAR)
            .withPluginDir(Files.createTempDirectory("tmpplugins").toFile())
            .withUseLatestSpecified(true)
            .build();

    PluginManager pluginManager = new PluginManager(config);
    PluginManager pluginManagerSpy = spy(pluginManager);

    Plugin testPlugin = new Plugin("test", "latest", null, null);
    doReturn(true).when(pluginManagerSpy).downloadPlugin(any(Plugin.class), any(File.class));

    mockStatic(Files.class);
    Path tempPath = mock(Path.class);
    File tempFile = mock(File.class);

    when(Files.createTempFile(any(String.class), any(String.class))).thenReturn(tempPath);
    when(tempPath.toFile()).thenReturn(tempFile);

    doReturn("1.0.0").doReturn("workflow-scm-step:2.4,workflow-step-api:2.13")
            .when(pluginManagerSpy).getAttributeFromManifest(any(File.class), any(String.class));

    doReturn(new VersionNumber("2.4")).doReturn(new VersionNumber("2.20")).when(pluginManagerSpy).
            getLatestPluginVersion(any(String.class));

    List<Plugin> expectedPlugins = new ArrayList<>();
    expectedPlugins.add(new Plugin("workflow-scm-step", "2.4", null, null));
    expectedPlugins.add(new Plugin("workflow-step-api", "2.20", null, null));

    List<String> expectedPluginInfo = convertPluginsToStrings(expectedPlugins);

    List<Plugin> actualPlugins = pluginManagerSpy.resolveDependenciesFromManifest(testPlugin);
    List<String> actualPluginInfo = convertPluginsToStrings(actualPlugins);

    assertEquals(expectedPluginInfo, actualPluginInfo);
    assertEquals(testPlugin.getVersion().toString(), "1.0.0");
}
 
Example #19
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void getLatestPluginTest() {
    setTestUcJson();
    VersionNumber antLatestVersion = pm.getLatestPluginVersion("ant");
    assertEquals("1.9", antLatestVersion.toString());

    VersionNumber amazonEcsLatestVersion = pm.getLatestPluginVersion("amazon-ecs");
    assertEquals("1.20", amazonEcsLatestVersion.toString());
}
 
Example #20
Source File: DockerClient.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
/**
 * Get the docker version.
 *
 * @return The {@link VersionNumber} instance if the version string matches the expected format,
 * otherwise {@code null}.
 */
public @CheckForNull VersionNumber version() throws IOException, InterruptedException {
    LaunchResult result = launch(new EnvVars(), true, "-v");
    if (result.getStatus() == 0) {
        return parseVersionNumber(result.getOut());
    } else {
        return null;
    }
}
 
Example #21
Source File: DockerClient.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
/**
 * Parse a Docker version string (e.g. "Docker version 1.5.0, build a8a31ef").
 * @param versionString The version string to parse.
 * @return The {@link VersionNumber} instance if the version string matched the
 * expected format, otherwise {@code null}.
 */
protected static VersionNumber parseVersionNumber(@Nonnull String versionString) {
    Matcher matcher = pattern.matcher(versionString.trim());
    if (matcher.matches()) {
        String major = matcher.group(2);
        String minor = matcher.group(3);
        String maint = matcher.group(4);
        return new VersionNumber(String.format("%s.%s.%s", major, minor, maint));
    } else {
        return null;
    }        
}
 
Example #22
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void showAvailableUpdates() throws IOException {
    Config config = Config.builder()
            .withJenkinsWar(Settings.DEFAULT_WAR)
            .withPluginDir(Files.createTempDirectory("tmpplugins").toFile())
            .withShowAvailableUpdates(true)
            .build();

    PluginManager pluginManager = new PluginManager(config);
    PluginManager pluginManagerSpy = spy(pluginManager);

    List<Plugin> plugins = new ArrayList<>();
    plugins.add(new Plugin("ant", "1.8", null, null));
    plugins.add(new Plugin("amazon-ecs", "1.15", null, null));
    plugins.add(new Plugin("maven-invoker-plugin", "2.4", null, null ));

    doReturn(new VersionNumber("1.9")).when(pluginManagerSpy).getLatestPluginVersion("ant");
    doReturn(new VersionNumber("1.20")).when(pluginManagerSpy).getLatestPluginVersion("amazon-ecs");
    doReturn(new VersionNumber("2.4")).when(pluginManagerSpy).getLatestPluginVersion("maven-invoker-plugin");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    System.setOut(new PrintStream(output));

    pluginManagerSpy.showAvailableUpdates(plugins);

    String expectedOutput = "\nAvailable updates:\n" +
            "ant (1.8) has an available update: 1.9\n" +
            "amazon-ecs (1.15) has an available update: 1.20\n";

    assertEquals(expectedOutput, output.toString().replaceAll("\\r\\n?", "\n"));
}
 
Example #23
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void checkVersionCompatibilityPassTest() {
    pm.setJenkinsVersion(new VersionNumber("2.121.2"));

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    System.setOut(new PrintStream(output));

    Plugin plugin1 = new Plugin("plugin1", "1.0", null, null);
    plugin1.setJenkinsVersion("2.121.2");

    Plugin plugin2 = new Plugin("plugin2", "2.1.1", null, null);
    plugin2.setJenkinsVersion("1.609.3");

    assertEquals("", output.toString());
}
 
Example #24
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test(expected = VersionCompatibilityException.class)
public void checkVersionCompatibilityFailTest() throws IOException {
    pm.setJenkinsVersion(new VersionNumber("1.609.3"));

    Plugin plugin1 = new Plugin("plugin1", "1.0", null, null);
    plugin1.setJenkinsVersion("2.121.2");

    Plugin plugin2 = new Plugin("plugin2", "2.1.1", null, null);
    plugin2.setJenkinsVersion("1.609.3");

    List<Plugin> pluginsToDownload = new ArrayList<>(Arrays.asList(plugin1, plugin2));
    pm.checkVersionCompatibility(pluginsToDownload);
}
 
Example #25
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void startTest() throws IOException {
    File refDir = mock(File.class);

    Config config = mock(Config.class);

    when(config.getPluginDir()).thenReturn(refDir);
    when(config.getJenkinsWar()).thenReturn(Settings.DEFAULT_WAR);
    when(config.getJenkinsUc()).thenReturn(Settings.DEFAULT_UPDATE_CENTER);
    when(config.getPlugins()).thenReturn(new ArrayList<Plugin>());
    when(config.doDownload()).thenReturn(true);
    when(config.getJenkinsUcExperimental()).thenReturn(Settings.DEFAULT_EXPERIMENTAL_UPDATE_CENTER);

    PluginManager pluginManager = new PluginManager(config);

    when(refDir.exists()).thenReturn(false);

    PluginManager pluginManagerSpy = spy(pluginManager);

    doNothing().when(pluginManagerSpy).createRefDir();
    doReturn(new VersionNumber("2.182")).when(pluginManagerSpy).getJenkinsVersionFromWar();
    doNothing().when(pluginManagerSpy).checkAndSetLatestUpdateCenter();
    doNothing().when(pluginManagerSpy).getUCJson();
    doReturn(new HashMap<>()).when(pluginManagerSpy).getSecurityWarnings();
    doNothing().when(pluginManagerSpy).showAllSecurityWarnings();

    doReturn(new HashMap<>()).when(pluginManagerSpy).bundledPlugins();
    doReturn(new HashMap<>()).when(pluginManagerSpy).installedPlugins();
    doReturn(new HashMap<>()).when(pluginManagerSpy).findPluginsAndDependencies(anyList());
    doReturn(new ArrayList<>()).when(pluginManagerSpy).findPluginsToDownload(anyMap());
    doReturn(new HashMap<>()).when(pluginManagerSpy).findEffectivePlugins(anyList());
    doNothing().when(pluginManagerSpy).listPlugins();
    doNothing().when(pluginManagerSpy).showSpecificSecurityWarnings(anyList());
    doNothing().when(pluginManagerSpy).showAvailableUpdates(anyList());
    doNothing().when(pluginManagerSpy).checkVersionCompatibility(anyList());
    doNothing().when(pluginManagerSpy).downloadPlugins(anyList());

    pluginManagerSpy.start();
}
 
Example #26
Source File: DockerDSLTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test public void buildWithMultiStage() {
        story.addStep(new Statement() {
            @Override public void evaluate() throws Throwable {
                assumeDocker(new VersionNumber("17.05"));
                WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
                p.setDefinition(new CpsFlowDefinition(
                        "node {\n" +
                                "  sh 'mkdir -p child'\n" +
                                "  writeFile file: 'child/stuff1', text: 'hello'\n" +
                                "  writeFile file: 'child/stuff2', text: 'world'\n" +
                                "  writeFile file: 'child/stuff3', text: env.BUILD_NUMBER\n" +
                                "  writeFile file: 'child/Dockerfile.other', " +
                                     "text: '# This is a test.\\n" +
                                            "\\n" +
                                            "FROM hello-world AS one\\n" +
                                            "ARG stuff4=4\\n" +
                                            "ARG stuff5=5\\n" +
                                            "COPY stuff1 /\\n" +
                                            "FROM scratch\\n" +
                                            "COPY --from=one /stuff1 /\\n" +
                                            "COPY stuff2 /\\nCOPY stuff3 /\\n'\n" +
                                "  def built = docker.build 'hello-world-stuff-arguments', '-f child/Dockerfile.other --build-arg stuff4=build4 --build-arg stuff5=build5 child'\n" +
                                "  echo \"built ${built.id}\"\n" +
                                "}", true));

// Note the absence '--pull' in the above docker build ags as compared to other tests.
// This is due to a Docker bug: https://github.com/docker/for-mac/issues/1751
// It can be re-added when that is fixed

                WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0));
                DockerClient client = new DockerClient(new Launcher.LocalLauncher(StreamTaskListener.NULL), null, null);
                String descendantImageId1 = client.inspect(new EnvVars(), "hello-world-stuff-arguments", ".Id");
                story.j.assertLogContains("built hello-world-stuff-arguments", b);
                story.j.assertLogNotContains(" --no-cache ", b);
                story.j.assertLogContains(descendantImageId1.replaceFirst("^sha256:", "").substring(0, 12), b);
                story.j.assertLogContains(" --build-arg stuff4=build4 ", b);
                story.j.assertLogContains(" --build-arg stuff5=build5 ", b);
            }
        });
    }
 
Example #27
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
/**
 * Gets the Jenkins version from the manifest in the Jenkins war specified in the Config class
 *
 * @return Jenkins version
 */
public VersionNumber getJenkinsVersionFromWar() {
    String version = getAttributeFromManifest(jenkinsWarFile, "Jenkins-Version");
    if (StringUtils.isEmpty(version)) {
        System.out.println("Unable to get version from war file");
        return null;
    }
    logVerbose("Jenkins version: " + version);
    return new VersionNumber(version);
}
 
Example #28
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
/**
 * Given a plugin and json that contains plugin information, determines the dependencies and returns the list of
 * dependencies. Optional dependencies will be excluded.
 *
 * @param plugin     for which to find dependencies
 * @param pluginJson json that will be parsed to find requested plugin's dependencies
 * @return list of plugin's dependencies, or null if dependencies are unable to be determined
 */
public List<Plugin> resolveDependenciesFromJson(Plugin plugin, JSONObject pluginJson) {
    JSONArray dependencies = getPluginDependencyJsonArray(plugin, pluginJson);
    List<Plugin> dependentPlugins = new ArrayList<>();

    if (dependencies == null) {
        return null;
    }

    for (int i = 0; i < dependencies.length(); i++) {
        JSONObject dependency = dependencies.getJSONObject(i);
        boolean isPluginOptional = dependency.getBoolean("optional");
        if (!isPluginOptional) {
            String pluginName = dependency.getString("name");
            String pluginVersion = dependency.getString("version");
            Plugin dependentPlugin = new Plugin(pluginName, pluginVersion, null, null);
            if (useLatestSpecified && plugin.isLatest() || useLatestAll) {
                VersionNumber latestPluginVersion = getLatestPluginVersion(pluginName);
                dependentPlugin.setVersion(latestPluginVersion);
                dependentPlugin.setLatest(true);
            }
            dependentPlugins.add(dependentPlugin);
            dependentPlugin.setParent(plugin);
        }
    }

    logVerbose(dependentPlugins.isEmpty() ? String.format("%n%s has no dependencies", plugin.getName()) :
            String.format("%n%s depends on: %n", plugin.getName()) +
                    dependentPlugins.stream()
                            .map(p -> p.getName() + " " + p.getVersion())
                            .collect(Collectors.joining("\n")));

    return dependentPlugins;
}
 
Example #29
Source File: DockerTestUtil.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
public static void assumeDocker(VersionNumber minimumVersion) throws Exception {
    Launcher.LocalLauncher localLauncher = new Launcher.LocalLauncher(StreamTaskListener.NULL);
    try {
        int status = localLauncher
            .launch()
            .cmds(DockerTool.getExecutable(null, null, null, null), "ps")
            .start()
            .joinWithTimeout(DockerClient.CLIENT_TIMEOUT, TimeUnit.SECONDS, localLauncher.getListener());
        Assume.assumeTrue("Docker working", status == 0);
    } catch (IOException x) {
        Assume.assumeNoException("have Docker installed", x);
    }
    DockerClient dockerClient = new DockerClient(localLauncher, null, null);
    Assume.assumeFalse("Docker version not < " + minimumVersion.toString(), dockerClient.version().isOlderThan(minimumVersion));
}
 
Example #30
Source File: PluginManager.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
/**
 * Prints out if any plugins of a given list have available updates in the latest update center
 *
 * @param plugins List of plugins to check versions against latest versions in update center
 */
public void showAvailableUpdates(List<Plugin> plugins) {
    if (cfg.isShowAvailableUpdates()) {
        System.out.println("\nAvailable updates:");
        for (Plugin plugin : plugins) {
            VersionNumber latestVersion = getLatestPluginVersion(plugin.getName());
            if (plugin.getVersion().isOlderThan(latestVersion)) {
                System.out.println(String.format("%s (%s) has an available update: %s", plugin.getName(),
                        plugin.getVersion(), latestVersion));
            }
        }
    }
}