Searches ZIP archive and returns properties found in "META-INF/maven/archetype-metadata.xml" entry
430275
public Map<String, String> parseProperties() throws IOException {
        final Map<String, String> replaceProperties = new HashMap<String, String>();
        ZipFile zip = null;
        try {
            zip = new ZipFile(archetypeFile);
            ZipEntry entry = zip.getEntry("META-INF/maven/archetype-metadata.xml");
            if (entry != null) {
                try (InputStream inputStream = zip.getInputStream(entry)) {
                    parseReplaceProperties(inputStream, replaceProperties);
                }
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        } finally {
            if (zip != null) {
                zip.close();
            }
        }
        return replaceProperties;
    }
1281630
public static Map<String, Version> identify(ClassLoader classLoader) {
        if (classLoader == null) {
            classLoader = PlatformDependent.getContextClassLoader();
        }

        // Collect all properties.
        Properties props = new Properties();
        try {
            Enumeration<URL> resources = classLoader.getResources("META-INF/io.netty.versions.properties");
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                InputStream in = url.openStream();
                try {
                    props.load(in);
                } finally {
                    try {
                        in.close();
                    } catch (Exception ignore) {
                        // Ignore.
                    }
                }
            }
        } catch (Exception ignore) {
            // Not critical. Just ignore.
        }

        // Collect all artifactIds.
        Set<String> artifactIds = new HashSet<String>();
        for (Object o: props.keySet()) {
            String k = (String) o;

            int dotIndex = k.indexOf('.');
            if (dotIndex <= 0) {
                continue;
            }

            String artifactId = k.substring(0, dotIndex);

            // Skip the entries without required information.
            if (!props.containsKey(artifactId + PROP_VERSION) ||
                !props.containsKey(artifactId + PROP_BUILD_DATE) ||
                !props.containsKey(artifactId + PROP_COMMIT_DATE) ||
                !props.containsKey(artifactId + PROP_SHORT_COMMIT_HASH) ||
                !props.containsKey(artifactId + PROP_LONG_COMMIT_HASH) ||
                !props.containsKey(artifactId + PROP_REPO_STATUS)) {
                continue;
            }

            artifactIds.add(artifactId);
        }

        Map<String, Version> versions = new TreeMap<String, Version>();
        for (String artifactId: artifactIds) {
            versions.put(
                    artifactId,
                    new Version(
                            artifactId,
                            props.getProperty(artifactId + PROP_VERSION),
                            parseIso8601(props.getProperty(artifactId + PROP_BUILD_DATE)),
                            parseIso8601(props.getProperty(artifactId + PROP_COMMIT_DATE)),
                            props.getProperty(artifactId + PROP_SHORT_COMMIT_HASH),
                            props.getProperty(artifactId + PROP_LONG_COMMIT_HASH),
                            props.getProperty(artifactId + PROP_REPO_STATUS)));
        }

        return versions;
    }
1055513
private void extractFiles(ArtifactMetadata artifactMetadata) throws RepositoryArchiveIOException, RepositoryArchiveEntryNotFoundException, RepositoryArchiveException {

        _readmePayload = artifactMetadata.getFileWithExtension(".txt");
        if (_readmePayload == null) {
            throw new RepositoryArchiveEntryNotFoundException("Unable to find iFix readme .txt file in archive"
                                                              + artifactMetadata.getArchive().getAbsolutePath(), artifactMetadata.getArchive(), "*.txt");
        }

    }
448576
private Map<String, Object> getEntityAsMap(
      Entity entity,
      EntityType meta,
      Set<String> attributesSet,
      Map<String, Set<String>> attributeExpandsSet) {
    if (null == entity) throw new IllegalArgumentException("entity is null");

    if (null == meta) throw new IllegalArgumentException("meta is null");

    Map<String, Object> entityMap = new LinkedHashMap<>();
    entityMap.put("href", UriUtils.createEntityUriPath(meta.getId(), entity.getIdValue()));

    for (Attribute attr : meta.getAtomicAttributes()) {
      // filter fields
      if (attributesSet != null && !attributesSet.contains(attr.getName().toLowerCase())) continue;

      String attrName = attr.getName();
      AttributeType attrType = attr.getDataType();

      if (attrType == COMPOUND) {
        if (attributeExpandsSet != null
            && attributeExpandsSet.containsKey(attrName.toLowerCase())) {
          Set<String> subAttributesSet = attributeExpandsSet.get(attrName.toLowerCase());
          entityMap.put(
              attrName,
              new AttributeResponse(
                  meta.getId(),
                  meta,
                  attr,
                  subAttributesSet,
                  null,
                  permissionService,
                  dataService));
        } else {
          entityMap.put(
              attrName,
              Collections.singletonMap(
                  "href",
                  UriUtils.createEntityAttributeUriPath(
                      meta.getId(), entity.getIdValue(), attrName)));
        }
      } else if (attrType == DATE) {
        LocalDate date = entity.getLocalDate(attrName);
        entityMap.put(attrName, date != null ? date.toString() : null);
      } else if (attrType == DATE_TIME) {
        Instant date = entity.getInstant(attrName);
        entityMap.put(attrName, date != null ? date.toString() : null);
      } else if (attrType != XREF
          && attrType != CATEGORICAL
          && attrType != MREF
          && attrType != CATEGORICAL_MREF
          && attrType != ONE_TO_MANY
          && attrType != FILE) {
        entityMap.put(attrName, entity.get(attr.getName()));
      } else if ((attrType == XREF || attrType == CATEGORICAL || attrType == FILE)
          && attributeExpandsSet != null
          && attributeExpandsSet.containsKey(attrName.toLowerCase())) {
        Entity refEntity = entity.getEntity(attr.getName());
        if (refEntity != null) {
          Set<String> subAttributesSet = attributeExpandsSet.get(attrName.toLowerCase());
          EntityType refEntityType = dataService.getEntityType(attr.getRefEntity().getId());
          Map<String, Object> refEntityMap =
              getEntityAsMap(refEntity, refEntityType, subAttributesSet, null);
          entityMap.put(attrName, refEntityMap);
        }
      } else if ((attrType == MREF || attrType == CATEGORICAL_MREF || attrType == ONE_TO_MANY)
          && attributeExpandsSet != null
          && attributeExpandsSet.containsKey(attrName.toLowerCase())) {
        EntityType refEntityType = dataService.getEntityType(attr.getRefEntity().getId());
        Iterable<Entity> mrefEntities = entity.getEntities(attr.getName());

        Set<String> subAttributesSet = attributeExpandsSet.get(attrName.toLowerCase());
        List<Map<String, Object>> refEntityMaps = new ArrayList<>();
        for (Entity refEntity : mrefEntities) {
          Map<String, Object> refEntityMap =
              getEntityAsMap(refEntity, refEntityType, subAttributesSet, null);
          refEntityMaps.add(refEntityMap);
        }

        EntityPager pager =
            new EntityPager(
                0,
                new EntityCollectionRequest().getNum(),
                (long) refEntityMaps.size(),
                mrefEntities);

        EntityCollectionResponse ecr =
            new EntityCollectionResponse(
                pager,
                refEntityMaps,
                UriUtils.createEntityAttributeUriPath(meta.getId(), entity.getIdValue(), attrName),
                null,
                permissionService,
                dataService);

        entityMap.put(attrName, ecr);
      } else if ((attrType == XREF && entity.get(attr.getName()) != null)
          || (attrType == CATEGORICAL && entity.get(attr.getName()) != null)
          || (attrType == FILE && entity.get(attr.getName()) != null)
          || attrType == MREF
          || attrType == CATEGORICAL_MREF
          || attrType == ONE_TO_MANY) {
        // Add href to ref field
        Map<String, String> ref = new LinkedHashMap<>();
        ref.put(
            "href",
            UriUtils.createEntityAttributeUriPath(meta.getId(), entity.getIdValue(), attrName));
        entityMap.put(attrName, ref);
      }
    }

    return entityMap;
  }
19191
def _archive_extensions():
        
        if six.PY3:
            ext_map = {}
            fmt_map = {}
            for key, exts, desc in shutil.get_unpack_formats():
                fmt_map[key] = exts[0]
                for ext in exts:
                    ext_map[ext] = key
        else:
            ext_map = {'.tar': 'tar',
                       '.tar.bz2': 'bztar',
                       '.tar.gz': 'gztar',
                       '.tar.xz': 'xztar',
                       '.tbz2': 'bztar',
                       '.tgz': 'gztar',
                       '.txz': 'xztar',
                       '.zip': 'zip'}
            fmt_map = {'bztar': '.tar.bz2',
                       'gztar': '.tar.gz',
                       'tar': '.tar',
                       'xztar': '.tar.xz',
                       'zip': '.zip'}
        return ext_map, fmt_map
928957
def archive(path = nil, configuration_suffix: nil)
      path ||= epub_name(configuration_suffix)

      epub_path = File.expand_path(path)

      Dir.chdir(@file_resolver.destination_path) do
        new_paths = @file_resolver.package_files.map(&:pkg_destination_path)

        if ::File.exists?(epub_path)
          Zip::File.open(epub_path, true) do |zip_file|
            old_paths = zip_file.instance_eval { @entry_set.entries.map(&:name) }
            diff = old_paths - new_paths
            diff.each do |file_to_remove|
              puts "DEBUG: removing file from result EPUB: #{file_to_remove}" if compilation_context.verbose?
              zip_file.remove(file_to_remove)
            end
          end
        end

        run_command(%(zip -q0X "#{epub_path}" mimetype))
        run_command(%(zip -qXr9D "#{epub_path}" "#{new_paths.join('" "')}" --exclude \\*.DS_Store))
      end

      path
    end
925216
def find_resource_paths(schema_dir):
    
    def not_api_doc_file(filename):
        return not filename.endswith(API_DOCS_FILENAME)

    def not_swagger_dot_json(filename):
        # Exclude a Swagger 2.0 schema file if it happens to exist.
        return not os.path.basename(filename) == 'swagger.json'

    def filename_to_path(filename):
        filename, _ext = os.path.splitext(os.path.basename(filename))
        return '/' + filename

    filenames = glob.glob('{0}/*.json'.format(schema_dir))
    return map(filename_to_path,
               filter(not_swagger_dot_json,
                      filter(not_api_doc_file, sorted(filenames))))
1102038
public void searchConfigurationFiles(final String wildcard, final String extension) {

        // Store parameters
        this.configurationFileWildcard = wildcard;
        this.configurationFileExtension = extension;

        // Search and analyze all properties files available
        readPropertiesFiles();
    }
1171298
private String extractPrefix(ApplicationContext context,
			ConfigurationBeanFactoryMetadata beanFactoryMetaData, String beanName) {
		ConfigurationProperties annotation = context.findAnnotationOnBean(beanName,
				ConfigurationProperties.class);
		if (beanFactoryMetaData != null) {
			ConfigurationProperties override = beanFactoryMetaData
					.findFactoryAnnotation(beanName, ConfigurationProperties.class);
			if (override != null) {
				// The @Bean-level @ConfigurationProperties overrides the one at type
				// level when binding. Arguably we should render them both, but this one
				// might be the most relevant for a starting point.
				annotation = override;
			}
		}
		return annotation.prefix();
	}
1081339
void findMavenArtifacts(Enumeration<URL> mavenDirs) throws IOException, SAXException, XPathExpressionException, ParserConfigurationException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        // don't allow external entity refs in the poms.
        builderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        while (mavenDirs.hasMoreElements()) {
            URL u = mavenDirs.nextElement();
            // jar:file:/home/username/.m2/repository/org/slf4j/slf4j-jdk14/1.5.0/slf4j-jdk14-1.5.0.jar!/META-INF/MANIFEST.MF
            // we're not interested if it's not a jar, although how you'd have a MANIFEST.MF which wasn't in a jar?
            if (u.getProtocol().equals("jar")) {
                // file:/home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar!/META-INF/MANIFEST.MF
                String file = u.getFile();
                // file:/home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar
                file = file.substring(0, file.indexOf("!"));
                // /home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar
                file = file.substring(5);
                // remove %20 etc
                file = URLDecoder.decode(file, "UTF-8");
                try (JarFile jarFile = new JarFile(file)) {
                    Enumeration<JarEntry> entries = jarFile.entries();
                    while (entries.hasMoreElements()) {
                        JarEntry entry = entries.nextElement();
                        try {
                            if (entry.getName().endsWith("pom.xml")) {
                                try (InputStream is = jarFile.getInputStream(entry)) {
                                    Document doc = builder.parse(is);
                                    String groupId = xpath.evaluate("/project/groupId", doc);
                                    if (groupId == null || "".equals(groupId)) {
                                        groupId = xpath.evaluate("/project/parent/groupId", doc);
                                        if (groupId == null || "".equals(groupId)) {
                                            logger.warn("Can't work out groupId for pom: "+file+"!"+entry);
                                            break;
                                        }
                                    }
                                    String artifactId = xpath.evaluate("/project/artifactId", doc);
                                    if (artifactId == null || "".equals(artifactId)) {
                                        artifactId = xpath.evaluate("/project/parent/artifactId", doc);
                                        if (artifactId == null || "".equals(artifactId)) {
                                            logger.warn("Can't work out artifactId for pom: "+file+"!"+entry);
                                            break;
                                        }
                                    }
                                    String version = xpath.evaluate("/project/version", doc);
                                    if (version == null || "".equals(version)) {
                                        version = xpath.evaluate("/project/parent/version", doc);
                                        if (version == null || "".equals(version)) {
                                            logger.warn("Can't work out version for pom: "+file+"!"+entry);
                                            break;
                                        }
                                    }
                                    artifacts.put(groupId + ":" + artifactId, version);
                                }
                            }
                        }
                        catch (IOException e) {
                            logger.error("Can't resolve "+entry.getName());
                            throw e;
                        }
                    }
                }
            }
            else {
                logger.info("Can't examine maven artifact in non jar location: "+u);
            }
        }
    }
278393
def metadata_path(self):
        """"""
        xml_name = _granule_identifier_to_xml_name(self.granule_identifier)
        metadata_path = os.path.join(self.granule_path, xml_name)
        try:
            assert os.path.isfile(metadata_path) or \
                metadata_path in self.dataset._zipfile.namelist()
        except AssertionError:
            raise S2ReaderIOError(
                "Granule metadata XML does not exist:", metadata_path)
        return metadata_path
252751
@Override
    public MetaProperty<?> findMetaProperty(Class<?> beanType, MetaBean metaBean, String propertyName) {
        // dynamic beans force code by exception
        try {
            return metaBean.metaProperty(propertyName);
        } catch (NoSuchElementException ex) {
            return null;
        }
    }
1350486
private void processEJBModulePersistenceXml(JPAApplInfo applInfo, ContainerInfo module, ClassLoader appClassloader) {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "processEJBModulePersistenceXml : " + applInfo.getApplName() +
                         "#" + module.getName());

        String archiveName = module.getName();
        Container ejbContainer = module.getContainer();
        ClassLoader ejbClassLoader = appClassloader;

        // ------------------------------------------------------------------------
        // JPA 2.0 Specification - 8.2 Persistence Unit Packaging
        //
        // A persistence unit is defined by a persistence.xml file. The jar file or
        // directory whose META-INF directory contains the persistence.xml file is
        // termed the root of the persistence unit. In Java EE environments, the
        // root of a persistence unit may be one of the following:
        //
        // -> an EJB-JAR file
        // ------------------------------------------------------------------------

        // Obtain persistence.xml in META-INF
        Entry pxml = ejbContainer.getEntry("META-INF/persistence.xml");
        if (pxml != null) {
            String appName = applInfo.getApplName();
            URL puRoot = getPXmlRootURL(appName, archiveName, pxml);
            applInfo.addPersistenceUnits(new OSGiJPAPXml(applInfo, archiveName, JPAPuScope.EJB_Scope, puRoot, ejbClassLoader, pxml));
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "processEJBModulePersistenceXml : " + applInfo.getApplName() +
                        "#" + module.getName());
    }
931153
private List<Archive> getClassPathArchives(String cpaths, List<Path> initialArchives)
            throws IOException
    {
        List<Archive> result = new ArrayList<>();
        if (cpaths.isEmpty()) {
            return result;
        }

        List<Path> paths = new ArrayList<>();
        for (String p : cpaths.split(File.pathSeparator)) {
            if (p.length() > 0) {
                // wildcard to parse all JAR files e.g. -classpath dir/*
                int i = p.lastIndexOf(".*");
                if (i > 0) {
                    Path dir = Paths.get(p.substring(0, i));
                    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.jar")) {
                        for (Path entry : stream) {
                            paths.add(entry);
                        }
                    }
                } else {
                    paths.add(Paths.get(p));
                }
            }
        }
        for (Path p : paths) {
            if (Files.exists(p) && !hasSameFile(initialArchives, p)) {
                result.add(Archive.getInstance(p));
            }
        }
        return result;
    }
633045
@SuppressWarnings("unchecked")
    protected static void logMetaInf()
    {
        if (!log.isLoggable(Level.WARNING))
        {
          return;
        }

        try
        {
            Map<String, List<JarInfo>> libs = new HashMap<String, List<JarInfo>>(30);

            Iterator<URL> it = ClassUtils.getResources("META-INF/MANIFEST.MF", LogMetaInfUtils.class);
            while (it.hasNext())
            {
                URL url = it.next();
                addJarInfo(libs, url);
            }

            final List<String> keys = new ArrayList(libs.keySet());
            Collections.sort(keys);

            if (log.isLoggable(Level.WARNING))
            {
                for (String artifactId : keys)
                {
                    List<JarInfo> versions = libs.get(artifactId);
                    if (versions != null && versions.size() > 1)
                    {
                        StringBuilder builder = new StringBuilder(1024);
                        builder.append("You are using the library: ");
                        builder.append(artifactId);
                        builder.append(" in different versions; first (and probably used) version is: ");
                        builder.append(versions.get(0).getVersion());
                        builder.append(" loaded from: ");
                        builder.append(versions.get(0).getUrl());
                        builder.append(", but also found the following versions: ");

                        boolean needComma = false;
                        for (int i = 1; i < versions.size(); i++)
                        {
                            JarInfo info = versions.get(i);
                            if (needComma)
                            {
                                builder.append(", ");
                            }

                            builder.append(info.getVersion());
                            builder.append(" loaded from: ");
                            builder.append(info.getUrl());

                            needComma = true;
                        }

                        log.warning(builder.toString());
                    }
                }
            }

            if (log.isLoggable(Level.INFO))
            {
                for (String artifactId : keys)
                {
                    logArtifact(artifactId, libs);
                }
            }
        }
        catch (Throwable e)
        {
            throw new FacesException(e);
        }
    }
531367
List<File> findNonJdkJars() throws IOException, SAXException, XPathExpressionException, ParserConfigurationException {
        Enumeration<URL> manifests = LibraryVersions.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
        String javaHome = System.getProperty("java.home");
        List<File> ret = new LinkedList<File>();
        while (manifests.hasMoreElements()) {
            URL u = manifests.nextElement();
            // jar:file:/home/username/.m2/repository/org/slf4j/slf4j-jdk14/1.5.0/slf4j-jdk14-1.5.0.jar!/META-INF/MANIFEST.MF
            // we're not interested if it's not a jar, although how you'd have a MANIFEST.MF which wasn't in a jar?
            if (u.getProtocol().equals("jar")) {
                // file:/home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar!/META-INF/MANIFEST.MF
                String file = u.getFile();
                // file:/home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar
                file = file.substring(0, file.indexOf("!"));
                // /home/username/.m2/repository/com/betfair/tornjak/kpi/3.0-SNAPSHOT/kpi-3.0-SNAPSHOT.jar
                file = file.substring(5);
                // remove %20 etc
                file = URLDecoder.decode(file, "UTF-8");
                File f = new File(file);
                String canonicalPath = f.getCanonicalPath();
                if (!canonicalPath.startsWith(javaHome)) {
                    ret.add(f);
                }
            } else {
                logger.info("Can't include code in checksum which isn't in a JAR: " + u);
            }
        }
        return ret;
    }
547778
def get_build_logs_zip(self, project, build_id, **kwargs):
        
        route_values = {}
        if project is not None:
            route_values['project'] = self._serialize.url('project', project, 'str')
        if build_id is not None:
            route_values['buildId'] = self._serialize.url('build_id', build_id, 'int')
        response = self._send(http_method='GET',
                              location_id='35a80daf-7f30-45fc-86e8-6b813d9c90df',
                              version='5.0',
                              route_values=route_values,
                              accept_media_type='application/zip')
        if "callback" in kwargs:
            callback = kwargs["callback"]
        else:
            callback = None
        return self._client.stream_download(response, callback=callback)