com.github.zafarkhaja.semver.Version Java Examples

The following examples show how to use com.github.zafarkhaja.semver.Version. 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: Browser.java    From selenium-shutterbug with MIT License 6 votes vote down vote up
public BufferedImage takeScreenshotEntirePageUsingGeckoDriver() {
    // Check geckodriver version (>= 0.24.0 is requried)
    String version = (String) ((RemoteWebDriver) driver).getCapabilities().getCapability("moz:geckodriverVersion");
    if (version == null || Version.valueOf(version).satisfies("<0.24.0")) {
        return takeScreenshotEntirePageDefault();
    }
    defineCustomCommand("mozFullPageScreenshot", new CommandInfo("/session/:sessionId/moz/screenshot/full", HttpMethod.GET));
    Object result = this.executeCustomCommand("mozFullPageScreenshot");
    String base64EncodedPng;
    if (result instanceof String) {
        base64EncodedPng = (String) result;
    } else if (result instanceof byte[]) {
        base64EncodedPng = new String((byte[]) result);
    } else {
        throw new RuntimeException(String.format("Unexpected result for /moz/screenshot/full command: %s",
            result == null ? "null" : result.getClass().getName() + "instance"));
    }
    return decodeBase64EncodedPng(base64EncodedPng);
}
 
Example #2
Source File: VersionWrapper.java    From LibScout with Apache License 2.0 6 votes vote down vote up
public static SEMVER getExpectedSemver(Version v0, Version v1) {
	if (v0.getMajorVersion() < v1.getMajorVersion()) {
		return SEMVER.MAJOR;
	}

	else if (v0.getMajorVersion() == v1.getMajorVersion()) {

		if (v0.getMinorVersion() < v1.getMinorVersion()) {
			return SEMVER.MINOR;
		} else if (v0.getMinorVersion() == v1.getMinorVersion()) {

			if (v0.getPatchVersion() < v1.getPatchVersion()) {
				return SEMVER.PATCH;
			} else if (v0.getPatchVersion() == v1.getPatchVersion()) {
				if (!v1.getBuildMetadata().isEmpty())  // subpatch levels are encoded by build meta data through VersionWrapper
					return SEMVER.PATCH;
			} else
				return null;
		}
	}

	return null;
}
 
Example #3
Source File: CordovaPlugin.java    From thym with Eclipse Public License 1.0 6 votes vote down vote up
private IStatus isDefinitionSatisfied(EngineDefinition definition, HybridMobileEngine engine) {
	String reason;
	if (engine.getName().equals(definition.name)) {// Engine ids match
		Version engineVer = Version.valueOf(engine.getSpec());
		if (engineVer.satisfies(definition.version)) { // version is satisfied
			return Status.OK_STATUS;
		} else {
			reason = "engine version: " + definition.version;
		}

	} else {
		reason = "engine id: " + definition.name;
	}
	return new Status(IStatus.WARNING, HybridCore.PLUGIN_ID,
			NLS.bind("Plug-in {0} does not support {1} version {2}. Fails version requirement: {3}",
					new Object[] { getLabel(), engine.getName(), engine.getSpec(), reason }));
}
 
Example #4
Source File: LibProfile.java    From LibScout with Apache License 2.0 6 votes vote down vote up
/**
 * Given a collection of profiles, return distinct libraries with their highest version
 * @param profiles
 * @return a {@link Map} containing unique library names -> highest version
 */
public static Map<String,String> getUniqueLibraries(Collection<LibProfile> profiles) {
	HashMap<String,String> result = new HashMap<String,String>();
	for (LibProfile p: profiles) {
		if (!result.containsKey(p.description.name))
			result.put(p.description.name, p.description.version);
		else {
			try {
				Version v1 = VersionWrapper.valueOf(result.get(p.description.name));
				Version v2 = VersionWrapper.valueOf(p.description.version);

				if (v2.greaterThan(v1))
					result.put(p.description.name, p.description.version);
			} catch (Exception e) { /* if at least one version is not semver compliant */ }
		}
	}
	return result;
}
 
Example #5
Source File: LibProfile.java    From LibScout with Apache License 2.0 6 votes vote down vote up
@Override
public int compare(LibProfile p0, LibProfile p1) {
	if (p0.description.name.equals(p1.description.name)) {
		try {
			// Compare by version string according to SemVer rules
			Version v0 = VersionWrapper.valueOf(p0.description.version);
			Version v1 = VersionWrapper.valueOf(p1.description.version);
	
			return v0.compareWithBuildsTo(v1);
		} catch (Exception e) {
			// if versions do not adhere to semver rules and cannot be
			// easily transformed into compliant version string,
			// do string compare as fallback
			return 	p0.description.version.compareTo(p1.description.version);
		}
	}

	return p0.description.name.compareTo(p1.description.name);
}
 
Example #6
Source File: ContainerIntegrationTests.java    From docker-compose-rule with Apache License 2.0 6 votes vote down vote up
/**
 * This test is not currently enabled in Circle as it does not provide a sufficiently recent version of docker-compose.
 *
 * @see <a href="https://github.com/palantir/docker-compose-rule/issues/156">Issue #156</a>
 */
@Test
public void testStateChanges_withHealthCheck() throws IOException, InterruptedException {
    assumeThat("docker version", Docker.version(), new GreaterOrEqual<>(Version.forIntegers(1, 12, 0)));
    assumeThat("docker-compose version", DockerCompose.version(), new GreaterOrEqual<>(Version.forIntegers(1, 10, 0)));

    DockerCompose dockerCompose = new DefaultDockerCompose(
            DockerComposeFiles.from("src/test/resources/native-healthcheck.yaml"),
            dockerMachine,
            ProjectName.random());

    // The withHealthcheck service's healthcheck checks every 100ms whether the file "healthy" exists
    Container container = new Container("withHealthcheck", docker, dockerCompose);
    assertEquals(State.DOWN, container.state());
    container.up();
    assertEquals(State.UNHEALTHY, container.state());
    dockerCompose.exec(noOptions(), "withHealthcheck", arguments("touch", "healthy"));
    wait.until(container::state, equalTo(State.HEALTHY));
    dockerCompose.exec(noOptions(), "withHealthcheck", arguments("rm", "healthy"));
    wait.until(container::state, equalTo(State.UNHEALTHY));
    container.kill();
    assertEquals(State.DOWN, container.state());
}
 
Example #7
Source File: UpgradeAPITest.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@RequestMapping(path = "/upgrade/server/static", method = RequestMethod.POST)
public List<UpgradeServerVersion> getAvailableVersions() {
    UpgradeServerVersion version1 = new UpgradeServerVersion();
    version1.version = Version.forIntegers(0, 1).toString();
    version1.title = "My Title 1";
    version1.downloadUrl = "http://www.amazingdownload.com/1";
    version1.releaseNoteUrl = "http://www.amazingrelease.com/1";

    UpgradeServerVersion version2 = new UpgradeServerVersion();
    version2.version = computeNextVersion(versionService).toString();
    version2.title = "My Title 2";
    version2.downloadUrl = "http://www.amazingdownload.com/2";
    version2.releaseNoteUrl = "http://www.amazingrelease.com/2";

    return Arrays.asList(version1, version2);
}
 
Example #8
Source File: UpgradeAPITest.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Test
public void checkStaticUpgradeServer() throws Exception {
    // Given
    // Server deliver always same response based (does *not* depend on sent content)
    upgradeAPI.setUpgradeVersionLocation("http://localhost:" + port + "/upgrade/server/static");
    final Version nextVersion = computeNextVersion(versionService);
    UpgradeServerVersion expected = new UpgradeServerVersion();
    expected.setVersion(nextVersion.toString());
    expected.setTitle("My Title 2");
    expected.setDownloadUrl("http://www.amazingdownload.com/2");
    expected.setReleaseNoteUrl("http://www.amazingrelease.com/2");

    // When
    String actual = RestAssured.when().get("/api/upgrade/check").asString();

    List<UpgradeServerVersion> actualParsed =
            mapper.readerFor(UpgradeServerVersion.class).<UpgradeServerVersion> readValues(actual).readAll();

    // Then
    Assert.assertEquals(1, actualParsed.size());
    Assert.assertEquals(expected, actualParsed.get(0));
}
 
Example #9
Source File: LibApiComparator.java    From LibScout with Apache License 2.0 6 votes vote down vote up
void inferAlternativeAPIs(Map<Version, Set<IMethod>> version2Api) {
    for (Version v: version2ApiDiff.keySet()) {
        ApiDiff diff = version2ApiDiff.get(v);

        if (diff.actualSemver != null && diff.actualSemver.equals(VersionWrapper.SEMVER.MAJOR)) {
            for (IMethod m: diff.removed) {
                Set<IMethod> alternatives = version2Api.get(v).parallelStream()
                   .filter(api -> !diff.removed.contains(api))  // exclude removed apis
                   .filter(api -> isAlternativeApi(m, api))
                   .collect(Collectors.toSet());

                // if we have three or more alternatives (e.g. renamed methods with one argument)
                // the suggestions will probably be wrong -> do not store any alternatives
                if (alternatives.size() <= 2)
                    diff.alternatives.put(m, alternatives);
            }
        }
    }
}
 
Example #10
Source File: LibApiComparator.java    From LibScout with Apache License 2.0 6 votes vote down vote up
void inferActualSemver(Map<Version, Set<IMethod>> version2Api) {
    Iterator<Version> it = version2ApiDiff.keySet().iterator();
    Version v0 = it.next();

    while (it.hasNext()) {
        Version v1 = it.next();
        VersionWrapper.SEMVER sem = compareApis(version2Api.get(v0), version2Api.get(v1));
        version2ApiDiff.get(v1).actualSemver = sem;

        // determine added/removed APIs
        if (!sem.equals(VersionWrapper.SEMVER.PATCH)) {
            Set<IMethod> removed = new HashSet<IMethod>(version2Api.get(v0));
            removed.removeAll(version2Api.get(v1));
            version2ApiDiff.get(v1).removed = removed;

            Set<IMethod> added = new HashSet<IMethod>(version2Api.get(v1));
            added.removeAll(version2Api.get(v0));
            version2ApiDiff.get(v1).added = added;
        }

        logger.debug(Utils.INDENT2 + "Actual SemVer:: " + v0.toString() + " : " + v1.toString() + "  ->  " + sem.name());
        v0 = v1;
    }
}
 
Example #11
Source File: LibApiComparator.java    From LibScout with Apache License 2.0 6 votes vote down vote up
Map<Version, Set<IMethod>> generatePerVersionApiSet(LibApiStats stats) {
    Map<Version, Set<IMethod>> version2Api = new TreeMap<Version, Set<IMethod>>();

    for (Version v: stats.getVersions()) {
        Set<IMethod> apis = new HashSet<IMethod>();

        for (IMethod api: stats.api2Versions.keySet()) {
            if (stats.api2Versions.get(api).contains(v))
                apis.add(api);
        }

        version2Api.put(v, apis);
    }

    return version2Api;
}
 
Example #12
Source File: AnnotationProcessor.java    From papercut with Apache License 2.0 6 votes vote down vote up
private boolean versionNameConditionMet(final String versionName, final Element element) {
    // Drop out quickly if there's no versionName set otherwise the try/catch below is doomed to fail.
    if (versionName.isEmpty()) return false;

    int comparison;

    try {
        final Version conditionVersion = Version.valueOf(versionName);
        final Version currentVersion = Version.valueOf(this.versionName);

        comparison = Version.BUILD_AWARE_ORDER.compare(conditionVersion, currentVersion);
    } catch (final IllegalArgumentException | com.github.zafarkhaja.semver.ParseException e) {
        messager.printMessage(Diagnostic.Kind.ERROR, String.format("Failed to parse versionName: %1$s. " +
                "Please use a versionName that matches the specification on http://semver.org/", versionName),
                element);

        // Assume the break condition is met if the versionName is invalid.
        return true;
    }

    return !versionName.isEmpty() && comparison <= 0;
}
 
Example #13
Source File: CloudFoundryDeployerAutoConfiguration.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 6 votes vote down vote up
private RuntimeEnvironmentInfo runtimeEnvironmentInfo(Class spiClass, Class implementationClass) {
	CloudFoundryClient client = connectionConfiguration.cloudFoundryClient(
		connectionConfiguration.connectionContext(connectionConfiguration.cloudFoundryConnectionProperties()),
		connectionConfiguration.tokenProvider(connectionConfiguration.cloudFoundryConnectionProperties()));
	Version version = connectionConfiguration.version(client);

	return new CloudFoundryPlatformSpecificInfo(new RuntimeEnvironmentInfo.Builder())
		.apiEndpoint(connectionConfiguration.cloudFoundryConnectionProperties().getUrl().toString())
		.org(connectionConfiguration.cloudFoundryConnectionProperties().getOrg())
		.space(connectionConfiguration.cloudFoundryConnectionProperties().getSpace())
		.builder()
			.implementationName(implementationClass.getSimpleName())
			.spiClass(spiClass)
			.implementationVersion(RuntimeVersionUtils.getVersion(CloudFoundryAppDeployer.class))
			.platformType("Cloud Foundry")
			.platformClientVersion(RuntimeVersionUtils.getVersion(client.getClass()))
			.platformApiVersion(version.toString())
			.platformHostVersion("unknown")
			.build();
}
 
Example #14
Source File: LibApiComparator.java    From LibScout with Apache License 2.0 6 votes vote down vote up
protected Map<Version, ApiDiff> run(LibApiStats stats) {

        version2ApiDiff = new TreeMap<Version, ApiDiff>();
        Map<Version, Set<IMethod>> version2Api =  generatePerVersionApiSet(stats);

        for (Version v: version2Api.keySet()) {
            version2ApiDiff.put(v, new ApiDiff(v, version2Api.get(v).size()));
        }

        // infer expected/actual semver
        inferExpectedSemver();
        inferActualSemver(version2Api);
        inferAlternativeAPIs(version2Api);

//        if (logger.isDebugEnabled()) {
        logger.info("======================================");
        logger.info("==  Library: " + stats.libName + "  ==");
        logger.info("======================================");
        printStats();
  //      }

        return version2ApiDiff;
    }
 
Example #15
Source File: DockerComposeExecutable.java    From docker-compose-rule with Apache License 2.0 6 votes vote down vote up
static Version version() throws IOException, InterruptedException {
    Command dockerCompose = new Command(new Executable() {
        @Override
        public String commandName() {
            return "docker-compose";
        }

        @Override
        public Process execute(String... commands) throws IOException {
            List<String> args = ImmutableList.<String>builder()
                    .add(defaultDockerComposePath())
                    .add(commands)
                    .build();
            return new ProcessBuilder(args).redirectErrorStream(true).start();
        }
    }, log::trace);

    String versionOutput = dockerCompose.execute(Command.throwingOnError(), "-v");
    return DockerComposeVersion.parseFromDockerComposeVersion(versionOutput);
}
 
Example #16
Source File: PackageService.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
private void validateUploadRequest(UploadRequest uploadRequest) {
	Assert.notNull(uploadRequest.getRepoName(), "Repo name can not be null");
	Assert.notNull(uploadRequest.getName(), "Name of package can not be null");
	Assert.notNull(uploadRequest.getVersion(), "Version can not be null");
	try {
		Version.valueOf(uploadRequest.getVersion().trim());
	}
	catch (ParseException e) {
		throw new SkipperException("UploadRequest doesn't have a valid semantic version.  Version = " +
				uploadRequest.getVersion().trim());
	}
	Assert.notNull(uploadRequest.getExtension(), "Extension can not be null");
	Assert.isTrue(uploadRequest.getExtension().equals("zip"), "Extension must be 'zip', not "
			+ uploadRequest.getExtension());
	Assert.notNull(uploadRequest.getPackageFileAsBytes(), "Package file as bytes must not be null");
	Assert.isTrue(uploadRequest.getPackageFileAsBytes().length != 0, "Package file as bytes must not be empty");
	PackageMetadata existingPackageMetadata = this.packageMetadataRepository.findByRepositoryNameAndNameAndVersion(
			uploadRequest.getRepoName().trim(), uploadRequest.getName().trim(), uploadRequest.getVersion().trim());
	if (existingPackageMetadata != null) {
		throw new SkipperException(String.format("Failed to upload the package. " + "" +
						"Package [%s:%s] in Repository [%s] already exists.",
				uploadRequest.getName(), uploadRequest.getVersion(), uploadRequest.getRepoName().trim()));
	}
}
 
Example #17
Source File: UpgradeAPI.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private List<UpgradeServerVersion> fetchServerUpgradeVersions(org.talend.dataprep.info.Version version)
        throws IOException {
    final HttpPost post = new HttpPost(upgradeVersionLocation);
    final String response;
    final StringWriter content = new StringWriter();
    try (final JsonGenerator generator = mapper.getFactory().createGenerator(content)) {
        generator.writeStartObject();
        generator.writeStringField("version", version.getVersionId());
        generator.writeStringField("id", token);
        generator.writeEndObject();
        generator.flush();

        post.setEntity(new StringEntity(content.toString(), ContentType.APPLICATION_JSON.withCharset(UTF_8)));
        response = IOUtils.toString(httpClient.execute(post).getEntity().getContent(), UTF_8);
    } finally {
        post.releaseConnection();
    }

    // Read upgrade server response
    return mapper.readerFor(new TypeReference<List<UpgradeServerVersion>>() {
    }).readValue(response);
}
 
Example #18
Source File: DockerShould.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
@Test
public void understand_new_version_format() throws IOException, InterruptedException {
    when(executedProcess.getInputStream()).thenReturn(toInputStream("Docker version 17.03.1-ce"));

    Version version = docker.configuredVersion();
    assertThat(version, is(Version.valueOf("17.3.1")));
}
 
Example #19
Source File: DockerComposeVersion.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
public static Version parseFromDockerComposeVersion(String versionOutput) {
    List<String> splitOnSeparator = Splitter.on(' ').splitToList(versionOutput);
    String version = splitOnSeparator.get(2);
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < version.length(); i++) {
        if ((version.charAt(i) >= '0' && version.charAt(i) <= '9') || version.charAt(i) == '.') {
            builder.append(version.charAt(i));
        } else {
            return Version.valueOf(builder.toString());
        }
    }
    return Version.valueOf(builder.toString());
}
 
Example #20
Source File: KibanaUtils.java    From openshift-elasticsearch-plugin with Apache License 2.0 5 votes vote down vote up
public KibanaUtils(final PluginSettings settings, final PluginClient pluginClient) {
    this.pluginClient = pluginClient;
    this.projectPrefix = StringUtils.isNotBlank(settings.getCdmProjectPrefix()) ? settings.getCdmProjectPrefix() : "";
    this.reIndexPattern = Pattern.compile("^" + projectPrefix + "\\.(?<name>[a-zA-Z0-9-]*)\\.(?<uid>.*)\\.\\*$");
    this.reProjectFromIndex = Pattern.compile("^(" + projectPrefix + ")?\\.(?<name>[a-zA-Z0-9-]*)(\\.(?<uid>.*))?\\.\\d{4}\\.\\d{2}\\.\\d{2}$");
    this.defaultVersion = Version.valueOf(ConfigurationSettings.DEFAULT_KIBANA_VERSION);
}
 
Example #21
Source File: DockerComposeManagerNativeHealthcheckIntegrationTest.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
/**
 * This test is not currently enabled in Circle as it does not provide a sufficiently recent version of docker-compose.
 *
 * @see <a href="https://github.com/palantir/docker-compose-rule/issues/156">Issue #156</a>
 */
@Test
public void dockerComposeManagerWaitsUntilHealthcheckPasses()
        throws ExecutionException, IOException, InterruptedException, TimeoutException {
    assumeThat("docker version", Docker.version(), new GreaterOrEqual<>(Version.forIntegers(1, 12, 0)));
    assumeThat("docker-compose version", DockerCompose.version(), new GreaterOrEqual<>(Version.forIntegers(1, 10, 0)));

    docker = new DockerComposeManager.Builder()
            .file("src/test/resources/native-healthcheck.yaml")
            .build();
    Future<?> beforeFuture = pool.submit(() -> {
        docker.before();
        return null;
    });

    Container container = docker.containers().container("withHealthcheck");
    await().until(container::state, Matchers.equalTo(State.UNHEALTHY));

    // The "withHealthCheck" container should not initially pass its healthcheck
    try {
        getUninterruptibly(beforeFuture, 1, TimeUnit.SECONDS);
        fail("Expected before() to wait");
    } catch (TimeoutException e) {
        // Expected
    }

    // Touching the "healthy" file in the "withHealthCheck" container should make its healthcheck pass
    docker.dockerCompose().exec(noOptions(), "withHealthcheck", arguments("touch", "healthy"));
    await().until(container::state, Matchers.equalTo(State.HEALTHY));
    getUninterruptibly(beforeFuture, 1, TimeUnit.SECONDS);
}
 
Example #22
Source File: DockerShould.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
@Test
public void understand_old_version_format() throws IOException, InterruptedException {
    when(executedProcess.getInputStream()).thenReturn(toInputStream("Docker version 1.7.2"));

    Version version = docker.configuredVersion();
    assertThat(version, is(Version.valueOf("1.7.2")));
}
 
Example #23
Source File: VersionWrapper.java    From LibScout with Apache License 2.0 5 votes vote down vote up
public static String getTruncatedVersion(Version v) {
	String vStr = "" + v.getMajorVersion();
	if (v.getMinorVersion() > 0  || (v.getMinorVersion() == 0 && v.getPatchVersion() > 0)) {
		vStr += "." + v.getMinorVersion();

		if (v.getPatchVersion() > 0)
			vStr += "." + v.getPatchVersion();

		if (v.getBuildMetadata().length() > 1)
			vStr += "-" + v.getBuildMetadata();
	}
	return vStr;
}
 
Example #24
Source File: CloudFoundryTaskPlatformFactory.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
private Version version(CloudFoundryClient cloudFoundryClient, String account) {
	return cloudFoundryClient.info()
			.get(GetInfoRequest.builder().build())
			.map(response -> Version.valueOf(response.getApiVersion()))
			.doOnNext(versionInfo -> logger.info(
					"Connecting to Cloud Foundry with API Version {}",
					versionInfo))
			.timeout(Duration.ofSeconds(deploymentProperties(account).getApiTimeout()))
			.block();
}
 
Example #25
Source File: BrokerVersionFilter.java    From pulsar with Apache License 2.0 5 votes vote down vote up
/**
 * From the given set of available broker candidates, filter those using the version numbers.
 *
 * @param brokers
 *            The currently available brokers that have not already been filtered.
 * @param bundleToAssign
 *            The data for the bundle to assign.
 * @param loadData
 *            The load data from the leader broker.
 * @param conf
 *            The service configuration.
 */
public void filter(Set<String> brokers, BundleData bundleToAssign, LoadData loadData, ServiceConfiguration conf)
        throws BrokerFilterBadVersionException {

    if ( !conf.isPreferLaterVersions()) {
        return;
    }

    com.github.zafarkhaja.semver.Version latestVersion = null;
    try {
        latestVersion = getLatestVersionNumber(brokers, loadData);
        LOG.info("Latest broker version found was [{}]", latestVersion);
    } catch ( Exception x ) {
        LOG.warn("Disabling PreferLaterVersions feature; reason: " + x.getMessage());
        throw new BrokerFilterBadVersionException("Cannot determine newest broker version: " + x.getMessage());
    }

    int numBrokersLatestVersion=0;
    int numBrokersOlderVersion=0;
    Iterator<String> brokerIterator = brokers.iterator();
    while ( brokerIterator.hasNext() ) {
        String broker = brokerIterator.next();
        BrokerData data = loadData.getBrokerData().get(broker);
        String brokerVersion = data.getLocalData().getBrokerVersionString();
        com.github.zafarkhaja.semver.Version brokerVersionVersion = Version.valueOf(brokerVersion);

        if ( brokerVersionVersion.equals(latestVersion) ) {
            LOG.debug("Broker [{}] is running the latest version ([{}])", broker, brokerVersion);
            ++numBrokersLatestVersion;
        } else {
            LOG.info("Broker [{}] is running an older version ([{}]); latest version is [{}]", broker, brokerVersion, latestVersion);
            ++numBrokersOlderVersion;
            brokerIterator.remove();
        }
    }
    if ( numBrokersOlderVersion == 0 ) {
        LOG.info("All {} brokers are running the latest version [{}]", numBrokersLatestVersion, latestVersion);
    }
}
 
Example #26
Source File: CloudFoundryDeployerAutoConfiguration.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public Version version(CloudFoundryClient client) {
	return client.info()
		.get(GetInfoRequest.builder()
			.build())
		.map(response -> Version.valueOf(response.getApiVersion()))
		.doOnError(e -> {
			throw new RuntimeException("Bad credentials connecting to Cloud Foundry.", e);
		})
		.doOnNext(version -> logger.info("Connecting to Cloud Foundry with API Version {}", version))
		.block(Duration.ofSeconds(appDeploymentProperties().getApiTimeout()));
}
 
Example #27
Source File: CloudFoundryTaskLauncherIntegrationTests.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	Assume.assumeTrue("Skipping TaskLauncher ITs on PCF<1.9 (2.65.0). Actual API version is " + cloudControllerAPIVersion,
		cloudControllerAPIVersion.greaterThanOrEqualTo(Version.forIntegers(2, 65, 0)));

	String multiplier = System.getenv("CF_DEPLOYER_TIMEOUT_MULTIPLIER");
	if (multiplier != null) {
		timeoutMultiplier = Double.parseDouble(multiplier);
	}
}
 
Example #28
Source File: UpgradeAPI.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/api/upgrade/check", method = GET)
@ApiOperation(value = "Checks if a newer versions are available and returns them as JSON.",
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@PublicAPI
public Stream<UpgradeServerVersion> check() {

    // defensive programming
    if (StringUtils.isBlank(upgradeVersionLocation)) {
        return Stream.empty();
    }

    try {
        // Get current version
        final Version parsedCurrentVersion = fromInternal(service.version());

        // POST to URL that serves a JSON Version object
        LOGGER.debug("Contacting upgrade server @ '{}'", upgradeVersionLocation);
        List<UpgradeServerVersion> versions = fetchServerUpgradeVersions(service.version());
        LOGGER.debug("{} available version(s) returned by update server: {}", versions.size(), toString(versions));

        // Compare current version with available and filter new versions
        return versions.stream().filter(v -> Version.valueOf(v.getVersion()).greaterThan(parsedCurrentVersion));
    } catch (Exception e) {
        LOGGER.error("Unable to check for new version (message: {}).", e.getMessage());
        LOGGER.debug("Exception occurred during new version check. ", e);
        return Stream.empty();
    }
}
 
Example #29
Source File: Docker.java    From docker-compose-rule with Apache License 2.0 5 votes vote down vote up
public Version configuredVersion() throws IOException, InterruptedException {
    String versionString = command.execute(Command.throwingOnError(), "-v");
    Matcher matcher = VERSION_PATTERN.matcher(versionString);
    checkState(matcher.matches(), "Unexpected output of docker -v: %s", versionString);
    return Version.forIntegers(Integer.parseInt(matcher.group(1)),
                               Integer.parseInt(matcher.group(2)),
                               Integer.parseInt(matcher.group(3)));
}
 
Example #30
Source File: VersionWrapper.java    From LibScout with Apache License 2.0 5 votes vote down vote up
/**
 * Determines change between two versions  
 * @param versionStr0  first version string
 * @param versionStr1  second version string
 * @return  version change, one of ["major", "minor", "patch"] or null if some error occurs
 */

// TODO TODO rewrite
public static String determineVersionChange(String versionStr0, String versionStr1) {
	Version v0 = VersionWrapper.valueOf(versionStr0);
	Version v1 = VersionWrapper.valueOf(versionStr1);
	
	if (v0.getMajorVersion() < v1.getMajorVersion()) {
		return SEMVER.MAJOR.toString();
	} 
	
	else if (v0.getMajorVersion() == v1.getMajorVersion()) {
		
		if (v0.getMinorVersion() < v1.getMinorVersion()) {
			return SEMVER.MINOR.toString();
		} else if (v0.getMinorVersion() == v1.getMinorVersion()) {
			
			if (v0.getPatchVersion() < v1.getPatchVersion()) {
				return SEMVER.PATCH.toString();
			} else if (v0.getPatchVersion() == v1.getPatchVersion()) {
				if (!v1.getBuildMetadata().isEmpty())  // subpatch levels are encoded by build meta data through VersionWrapper
					return SEMVER.PATCH.toString();
			} else
				return null;
		}
	} 

	return null;
}