Read version name from the manifest of the context.
@param context the context.
@return the version name.
@throws java.lang.IllegalStateException if the target package is not installed.
509707
public static String getVersionName(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionName;
        } catch (NameNotFoundException e) {
            throw new IllegalStateException("no such package installed on the device: ", e);
        }
    }
1267279
private static String getVersionFromPom() {

        final String absolutePath = new File(BuildVersion.class.getResource(BuildVersion.class
                .getSimpleName() + ".class").getPath())
                .getParentFile().getParentFile().getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile().getAbsolutePath();

        final File file = new File(absolutePath + "/pom.xml");

        try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) {

            final MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
            Model model = xpp3Reader.read(reader);
            return model.getVersion();

        } catch (NoClassDefFoundError e) {
            // if you want to get the version possibly in development add in to your pom
            // pax-url-aether.jar
            return null;
        } catch (Exception e) {
            return null;
        }
    }
307546
private static List<String> getManifestPermissions(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), PackageManager.GET_PERMISSIONS);
            String[] permissions = packageInfo.requestedPermissions;
            if (permissions == null || permissions.length == 0) {
                throw new IllegalStateException("You did not register any permissions in the manifest.xml.");
            }
            return Collections.unmodifiableList(Arrays.asList(permissions));
        } catch (PackageManager.NameNotFoundException e) {
            throw new AssertionError("Package name cannot be found.");
        }
    }
53093
@Override
  public void exitVersion_set(VersionParser.Version_setContext ctx)
  {
    Object o1 = stack.pop();
    if (strict && (o1 instanceof NamedVersion)) {
      String name = o1.toString();
      // FIXME: There needs to be a better way to identify illegal named versions. Perhaps insist it contains an alphanumeric?
      switch (name.trim()) {
        case "-":
        case "_":
          throw new InvalidRangeRuntimeException("Invalid named version: " + o1);
        default:
          break;
      }
    }
    if (stack.isEmpty()) {
      VersionSet set = new VersionSet((IVersion) o1);
      stack.push(set);
    }
    else {
      VersionSet set = (VersionSet) stack.peek();
      set.add((IVersion) o1);
    }
  }
184991
public String getContextName()
    {
        ExternalContext ctx = _MyFacesExternalContextHelper.firstInstance.get();
        
        if (ctx == null)
        {
            throw new UnsupportedOperationException();
        }
        
        return ctx.getContextName();
    }
397519
public static synchronized String getVersion() {
        // Try to get version number from pom.xml (available when running in Eclipse)
        final Class<?> cls = ClassGraph.class;
        try {
            final String className = cls.getName();
            final URL classpathResource = cls.getResource("/" + JarUtils.classNameToClassfilePath(className));
            if (classpathResource != null) {
                final Path absolutePackagePath = Paths.get(classpathResource.toURI()).getParent();
                final int packagePathSegments = className.length() - className.replace(".", "").length();
                // Remove package segments from path
                Path path = absolutePackagePath;
                for (int i = 0; i < packagePathSegments && path != null; i++) {
                    path = path.getParent();
                }
                // Remove up to two more levels for "bin" or "target/classes"
                for (int i = 0; i < 3 && path != null; i++, path = path.getParent()) {
                    final Path pom = path.resolve("pom.xml");
                    try (InputStream is = Files.newInputStream(pom)) {
                        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
                        doc.getDocumentElement().normalize();
                        String version = (String) XPathFactory.newInstance().newXPath().compile("/project/version")
                                .evaluate(doc, XPathConstants.STRING);
                        if (version != null) {
                            version = version.trim();
                            if (!version.isEmpty()) {
                                return version;
                            }
                        }
                    } catch (final IOException e) {
                        // Not found
                    }
                }
            }
        } catch (final Exception e) {
            // Ignore
        }

        // Try to get version number from maven properties in jar's META-INF directory
        try (InputStream is = cls.getResourceAsStream(
                "/META-INF/maven/" + MAVEN_PACKAGE + "/" + MAVEN_ARTIFACT + "/pom.properties")) {
            if (is != null) {
                final Properties p = new Properties();
                p.load(is);
                final String version = p.getProperty("version", "").trim();
                if (!version.isEmpty()) {
                    return version;
                }
            }
        } catch (final IOException e) {
            // Ignore
        }

        // Fallback to using Java API (version number is obtained from MANIFEST.MF)
        final Package pkg = cls.getPackage();
        if (pkg != null) {
            String version = pkg.getImplementationVersion();
            if (version == null) {
                version = "";
            }
            version = version.trim();
            if (version.isEmpty()) {
                version = pkg.getSpecificationVersion();
                if (version == null) {
                    version = "";
                }
                version = version.trim();
            }
            if (!version.isEmpty()) {
                return version;
            }
        }
        return "unknown";
    }
557789
public static int getVersionCode(Context context, int fallback) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (NameNotFoundException e) {
            Log.e(TAG, "no such package installed on the device: ", e);
        }
        return fallback;
    }
532260
public static String getTopActivityPackageName(Context context) {
		ComponentName activity = getTopActivity(context);
		if (activity == null) {
			return null;
		}
		return activity.getPackageName();
	}
890887
public void checkVersion(String version) throws ConnectionException {
        MetaModel meta = createMetaModel();
        meta.getAssetType("Member");

        if ((version != null) && (version.length() > 0)
                && ((meta.getVersion() == null) || (meta.getVersion()
                .compareTo(new Version(version)) < 0))) {
            throw new ConnectionException(MessageFormat.format(
                    "VersionOne Release {0} or above is required (found {1}).",
                    version, meta.getVersion()));
        }
    }
745170
private static Version extractVersion() {
		VersionInfo versionInfo = VersionInfo.getVersionInfo();
		String versionString = versionInfo.getVersion();
		String[] splits = versionString.split("\\.");
		int major = 0;
		int minor = 0;
		int patch = 0;
		int build = 0;
		try {
			major = Integer.parseInt(splits[0]);
			minor = Integer.parseInt(splits[1]);
			patch = Integer.parseInt(splits[2]);
			build = Integer.parseInt(splits[3]);
		} catch (Exception ignored) {

		}
		return new Version(major, minor, patch, build);
	}
1135453
public static ManifestVersion get(final Class<?> clazz)
	{
		final String manifestUrl = ClassExtensions.getManifestUrl(clazz);
		try
		{
			return of(manifestUrl != null ? new URL(manifestUrl) : null);
		}
		catch (final MalformedURLException ignore)
		{
			return of(null);
		}
	}
811483
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean hasTelevisionFeature(Context context) {
        return hasTelevisionFeature(context.getPackageManager());
    }
1234853
String packageName() {
    for (Object context : contextStack) {
      if (context instanceof ProtoFile) return ((ProtoFile) context).packageName();
    }
    return null;
  }
1338451
static int getMajorJavaVersion(String javaVersion) {
    int version = parseDotted(javaVersion);
    if (version == -1) {
      version = extractBeginningInt(javaVersion);
    }
    if (version == -1) {
      return 6;  // Choose minimum supported JDK version as default
    }
    return version;
  }
300218
static int getMajorVersion(String javaSpecVersion) {
        try {
            if (javaSpecVersion.contains(".")) { //before jdk 9
                return Integer.parseInt(javaSpecVersion.split("\\.")[1]);
            } else {
                return Integer.parseInt(javaSpecVersion);
            }
        } catch (NumberFormatException e ){
            throw getUnableToParseVersionException(javaSpecVersion);
        }
    }
50637
public static String getImplementationVersion(Class<?> clazz) {
        /*
         * We don't use Package.getImplementationVersion() due to
         * a duplicate package would override the origin package info.
         * https://stackoverflow.com/questions/1272648/reading-my-own-jars-manifest
         */
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();
        if (!classPath.startsWith("jar:file:")) {
          // Class not from JAR
          return null;
        }
        // Get manifest
        int offset = classPath.lastIndexOf("!");
        assert offset > 0;
        String manifestPath = classPath.substring(0, offset + 1) +
                              "/META-INF/MANIFEST.MF";
        Manifest manifest = null;
        try {
            manifest = new Manifest(new URL(manifestPath).openStream());
        } catch (IOException ignored) {
            return null;
        }
        return manifest.getMainAttributes()
                       .getValue(Attributes.Name.IMPLEMENTATION_VERSION);
    }
628244
public static Version parseMavenVersion(String version) {
		if (Strings.isNullOrEmpty(version)) {
			return new Version(0, 0, 0);
		}

		// Detect the snapshot
		final boolean isSnapshot;
		final String coreVersion;
		Matcher matcher = Artifact.VERSION_FILE_PATTERN.matcher(version);
		if (matcher.matches()) {
			coreVersion = matcher.group(1);
			isSnapshot = true;
		} else {
			matcher = SNAPSHOT_VERSION_PATTERN.matcher(version);
			if (matcher.matches()) {
				coreVersion = matcher.group(1);
				isSnapshot = true;
			} else {
				coreVersion = version;
				isSnapshot = false;
			}
		}

		// Parse the numbers
		final String[] parts = coreVersion.split("[.]"); //$NON-NLS-1$
		final int[] numbers = new int[] {0, 0, 0};
		int i = 0;
		while (i < numbers.length && i < parts.length) {
			try {
				numbers[i] = Integer.parseInt(parts[i]);
				++i;
			} catch (Exception exception) {
				// Force the exit of the loop since a number cannot be find.
				i = numbers.length;
			}
		}
		// Reply
		if (isSnapshot) {
			return new Version(numbers[0], numbers[1], numbers[2], SNAPSHOT_QUALIFIER);
		}
		return new Version(numbers[0], numbers[1], numbers[2]);
	}