Java Code Examples for com.github.zafarkhaja.semver.Version#valueOf()

The following examples show how to use com.github.zafarkhaja.semver.Version#valueOf() . 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: 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 2
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 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: 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 5
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 6
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 7
Source File: HybridMobileEngine.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns version or null of spec is not a sem version
 * @return
 */
public Version getVersionSpec() {
	String exactVersion = EngineUtils.getExactVersion(spec);
	Version version;
	try {
		version = Version.valueOf(exactVersion);
	} catch (Exception e) {
		return null;
	}
	return version;
}
 
Example 8
Source File: AvailableCordovaEnginesSection.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public int compare(HybridMobileEngine o1, HybridMobileEngine o2) {
	try {
		Version version1 = Version.valueOf(o1.getSpec());
		Version version2 = Version.valueOf(o2.getSpec());
		if (descending) {
			return version2.compareTo(version1);
		}
		return version1.compareTo(version2);
	} catch (Exception e) {
		return 1;
	}
}
 
Example 9
Source File: EngineAddDialog.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public int compare(DownloadableCordovaEngine o1, DownloadableCordovaEngine o2) {
	Version v1 = Version.valueOf(o1.getVersion());
	Version v2 = Version.valueOf(o2.getVersion());
	//Make it descending switch v1 to v2
	return v2.compareTo(v1);
}
 
Example 10
Source File: ShouldDisplayBadgesWithGroovyPostbuildPlugin.java    From jenkins-build-monitor-plugin with MIT License 5 votes vote down vote up
@BeforeClass
public static void ensureJenkinsVersion() {
    String jenkinsVersionString = System.getenv("JENKINS_VERSION");
    if (jenkinsVersionString == null) {
        Assert.fail("Jenkins version needs to be set as env JENKINS_VERSION");
    }
    Version jenkinsVersion = Version.valueOf(jenkinsVersionString);
    Assume.assumeTrue("Jenkins version too new", jenkinsVersion.lessThanOrEqualTo(Version.valueOf("2.46.3")));
}
 
Example 11
Source File: AddonSpecification.java    From Sandbox with GNU Lesser General Public License v3.0 4 votes vote down vote up
public AddonSpecification(Config config) {
    this(config.get("id"), config.get("name"), config.get("description"), Version.valueOf(config.get("version")));
}
 
Example 12
Source File: VersionWrapper.java    From LibScout with Apache License 2.0 4 votes vote down vote up
/**
 * {@link Version.valueOf} requires a valid x.y.z scheme. This version parser further allows x and x.y schemes
 * and initializes the missing values with zero. 
 * @param versionStr
 * @return
 */
public static Version valueOf(String versionStr) {
	if (versionStr.isEmpty()) {
		logger.warn("Empty version string!");
		return null;
	}
	
	String[] version = versionStr.split("\\.");
	
	if (version.length == 1)  { // like 12  is transformed into 12.0.0
		logger.debug("Invalid semVer (minor+patch level missing): " + versionStr);
		return Version.forIntegers(Integer.parseInt(version[0]));
	}
	
	if (version.length == 2)  { // like 7.2  is transformed into 7.2.0
		logger.debug("Invalid semVer (patch level missing): " + versionStr);
		
		// 11.1-rc1 is transformed into 11.1.0-rc1
		if (version[1].indexOf('-') != -1) {
			String[] frag = version[1].split("-");
			
			String ext = "";
			for (int i = 1; i < frag.length; i++)
				ext += "-" + frag[i];
				
			return Version.valueOf(version[0] + "." + frag[0] + ".0" + ext);
		}
					
		return Version.forIntegers(Integer.parseInt(version[0]),Integer.parseInt(version[1]));
	}
	
	if (version.length == 3)   //  like 3.2.1
		return Version.valueOf(versionStr);
	
	if (version.length >= 3) {   // like 5.2.1.3  is transformed into 5.2.1-build3
		logger.debug("Invalid semVer (sub-patch level): " + versionStr);
		Version.Builder builder = new Version.Builder(version[0] + "." + version[1] + "." + version[2]);
		builder.setBuildMetadata("build." + version[3]);
		return builder.build();
	}

	logger.debug("Invalid semVer: " + versionStr);
	return null;
}
 
Example 13
Source File: ConfigUtil.java    From DiscordSRV with GNU General Public License v3.0 4 votes vote down vote up
public static void migrate() {
    String configVersionRaw = DiscordSRV.config().getString("ConfigVersion");
    String pluginVersionRaw = DiscordSRV.getPlugin().getDescription().getVersion();
    if (configVersionRaw.equals(pluginVersionRaw)) return;

    Version configVersion = configVersionRaw.split("\\.").length == 3
            ? Version.valueOf(configVersionRaw.replace("-SNAPSHOT", ""))
            : Version.valueOf("1." + configVersionRaw.replace("-SNAPSHOT", ""));
    Version pluginVersion = Version.valueOf(pluginVersionRaw.replace("-SNAPSHOT", ""));

    if (configVersion.equals(pluginVersion)) return; // no migration necessary
    if (configVersion.greaterThan(pluginVersion)) {
        DiscordSRV.warning("You're attempting to use a higher config version than the plugin. Things probably won't work correctly.");
        return;
    }

    String oldVersionName = configVersion.toString();
    DiscordSRV.info("Your DiscordSRV config file was outdated; attempting migration...");

    try {
        Provider configProvider = DiscordSRV.config().getProvider("config");
        Provider messageProvider = DiscordSRV.config().getProvider("messages");
        Provider voiceProvider = DiscordSRV.config().getProvider("voice");
        Provider linkingProvider = DiscordSRV.config().getProvider("linking");
        Provider synchronizationProvider = DiscordSRV.config().getProvider("synchronization");

        if (configVersion.greaterThanOrEqualTo(Version.forIntegers(1, 13, 0))) {
            migrate("messages.yml-build." + oldVersionName + ".old", DiscordSRV.getPlugin().getMessagesFile(), messageProvider);
            migrate("config.yml-build." + oldVersionName + ".old", DiscordSRV.getPlugin().getConfigFile(), configProvider, false);
            migrate("voice.yml-build." + oldVersionName + ".old", DiscordSRV.getPlugin().getVoiceFile(), voiceProvider);
            migrate("linking.yml-build." + oldVersionName + ".old", DiscordSRV.getPlugin().getLinkingFile(), linkingProvider, true);
            migrate("synchronization.yml-build." + oldVersionName + ".old", DiscordSRV.getPlugin().getSynchronizationFile(), synchronizationProvider);
        } else {
            // legacy migration <1.13.0
            // messages
            File messagesFrom = new File(DiscordSRV.getPlugin().getDataFolder(), "config.yml");
            File messagesTo = DiscordSRV.getPlugin().getMessagesFile();
            messageProvider.saveDefaults();
            copyYmlValues(messagesFrom, messagesTo, false);
            messageProvider.load();

            // config
            File configFrom = new File(DiscordSRV.getPlugin().getDataFolder(), "config.yml-build." + oldVersionName + ".old");
            File configTo = DiscordSRV.getPlugin().getConfigFile();
            FileUtils.moveFile(configTo, configFrom);
            configProvider.saveDefaults();
            copyYmlValues(configFrom, configTo, false);
            configProvider.load();

            // channels
            File channelsFile = new File(DiscordSRV.getPlugin().getDataFolder(), "channels.json");
            if (channelsFile.exists()) {
                List<Map<String, String>> channels = new ArrayList<>();
                JsonArray jsonElements = DiscordSRV.getPlugin().getGson().fromJson(FileUtils.readFileToString(channelsFile, StandardCharsets.UTF_8), JsonArray.class);
                for (JsonElement jsonElement : jsonElements) {
                    channels.add(new HashMap<String, String>() {{
                        put(jsonElement.getAsJsonObject().get("channelname").getAsString(), jsonElement.getAsJsonObject().get("channelid").getAsString());
                    }});
                }
                String channelsString = "{" + channels.stream()
                        .map(stringStringMap -> "\"" + stringStringMap.keySet().iterator().next() + "\": \"" + stringStringMap.values().iterator().next() + "\"")
                        .collect(Collectors.joining(", ")) + "}";
                FileUtils.writeStringToFile(channelsFile, "Channels: " + channelsString, StandardCharsets.UTF_8);
                copyYmlValues(channelsFile, configTo, false);
                channelsFile.delete();
            }

            // colors
            File colorsFile = new File(DiscordSRV.getPlugin().getDataFolder(), "colors.json");
            FileUtils.moveFile(colorsFile, new File(colorsFile.getParent(), "colors.json.old"));
        }
        DiscordSRV.info("Successfully migrated configuration files to version " + configVersionRaw);
    } catch (Exception e) {
        DiscordSRV.error("Failed migrating configs: " + e.getMessage());
        DiscordSRV.debug(ExceptionUtils.getStackTrace(e));
    }
}
 
Example 14
Source File: BrokerVersionFilter.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/**
 * Get the most recent broker version number from the load reports of all the running brokers. The version
 * number is from the build artifact in the pom and got added to the package when it was built by Maven
 *
 * @param brokers
 *            The brokers to choose the latest version string from.
 * @param loadData
 *            The load data from the leader broker (contains the load reports which in turn contain the version string).
 * @return The most recent broker version
 * @throws BrokerFilterBadVersionException
 *            If the most recent version is undefined (e.g., a bad broker version was encountered or a broker
 *            does not have a version string in its load report.
 */
public Version getLatestVersionNumber(Set<String> brokers, LoadData loadData) throws BrokerFilterBadVersionException {
    if ( null == brokers ) {
        throw new BrokerFilterBadVersionException("Unable to determine latest version since broker set was null");
    }
    if ( brokers.size() == 0 ) {
        throw new BrokerFilterBadVersionException("Unable to determine latest version since broker set was empty");
    }
    if ( null == loadData ) {
        throw new BrokerFilterBadVersionException("Unable to determine latest version since loadData was null");
    }

    Version latestVersion = null;
    for ( String broker : brokers ) {
        BrokerData data = loadData.getBrokerData().get(broker);
        if (null == data) {
            LOG.warn("No broker data for broker [{}]; disabling PreferLaterVersions feature", broker);
            // trigger the ModularLoadManager to reset all the brokers to the original set
            throw new BrokerFilterBadVersionException("No broker data for broker \"" + broker + "\"");
        }

        String brokerVersion = data.getLocalData().getBrokerVersionString();
        if (null == brokerVersion || brokerVersion.length() == 0) {
            LOG.warn("No version string in load report for broker [{}]; disabling PreferLaterVersions feature", broker);
            // trigger the ModularLoadManager to reset all the brokers to the original set
            throw new BrokerFilterBadVersionException("No version string in load report for broker \"" + broker + "\"");
        }

        Version brokerVersionVersion = null;
        try {
            brokerVersionVersion = Version.valueOf(brokerVersion);
        } catch (Exception x) {
            LOG.warn("Invalid version string in load report for broker [{}]: [{}]; disabling PreferLaterVersions feature", broker, brokerVersion);
            // trigger the ModularLoadManager to reset all the brokers to the original set
            throw new BrokerFilterBadVersionException("Invalid version string in load report for broker \"" + broker + "\": \"" + brokerVersion + "\")");
        }

        if ( null == latestVersion ) {
            latestVersion = brokerVersionVersion;
        } else if (Version.BUILD_AWARE_ORDER.compare(latestVersion, brokerVersionVersion) < 0) {
            latestVersion = brokerVersionVersion;
        }
    }

    if ( null == latestVersion ) {
        throw new BrokerFilterBadVersionException("Unable to determine latest broker version");
    }

    return latestVersion;
}
 
Example 15
Source File: CordovaEngineProvider.java    From thym with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public int compare(DownloadableCordovaEngine o1, DownloadableCordovaEngine o2) {
	Version v1 = Version.valueOf(o1.getVersion());
	Version v2 = Version.valueOf(o2.getVersion());
	return v2.compareTo(v1);
}