Example usage for java.util.jar JarEntry isDirectory

List of usage examples for java.util.jar JarEntry isDirectory

Introduction

In this page you can find the example usage for java.util.jar JarEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:com.greenpepper.maven.plugin.SpecificationRunnerMojo.java

private void extractHtmlReportSummary() throws IOException, URISyntaxException {
    final String path = "html-summary-report";
    final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    forceMkdir(reportsDirectory);// ww  w . ja v a2 s  .co  m
    if (jarFile.isFile()) { // Run with JAR file
        JarFile jar = new JarFile(jarFile);
        Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            String name = jarEntry.getName();
            if (name.startsWith(path)) { //filter according to the path
                File file = getFile(reportsDirectory, substringAfter(name, path));
                if (jarEntry.isDirectory()) {
                    forceMkdir(file);
                } else {
                    forceMkdir(file.getParentFile());
                    if (!file.exists()) {
                        copyInputStreamToFile(jar.getInputStream(jarEntry), file);
                    }
                }
            }
        }
        jar.close();
    } else { // Run with IDE
        URL url = getClass().getResource("/" + path);
        if (url != null) {
            File apps = FileUtils.toFile(url);
            if (apps.isDirectory()) {
                copyDirectory(apps, reportsDirectory);
            } else {
                throw new IllegalStateException(
                        format("Internal resource '%s' should be a directory.", apps.getAbsolutePath()));
            }
        } else {
            throw new IllegalStateException(format("Internal resource '/%s' should be here.", path));
        }
    }
}

From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java

/**
 * Searches a JarFile for pom.xml entries and returns a listing of these
 * entries./*  w w w  . jav a2 s . co m*/
 *
 * @param jar the JarFile to search
 * @return a list of pom.xml entries
 * @throws IOException thrown if there is an exception reading a JarEntry
 */
private List<String> retrievePomListing(final JarFile jar) throws IOException {
    final List<String> pomEntries = new ArrayList<String>();
    final Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        final JarEntry entry = entries.nextElement();
        final String entryName = (new File(entry.getName())).getName().toLowerCase();
        if (!entry.isDirectory() && "pom.xml".equals(entryName)) {
            LOGGER.trace("POM Entry found: {}", entry.getName());
            pomEntries.add(entry.getName());
        }
    }
    return pomEntries;
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * This method returns all entries in a JarInputStream for a given search pattern within the jar as a Map
 * having the filename as the key and the file content as its respective value (String).
 * The boolean flag "isFile" marks the search pattern as a file, otherwise the pattern will be treated as
 * a path to be found in the jarStream//from   w w  w.jav  a2s .  co m
 * A successful search either returns a map of all entries for a given path or a map of all entries for a given file
 * (again, depending on the "isFile" flag).
 * Null will be returned if no occurrences of the search pattern were found.
 *
 * @param jarStream     the given JarInputStream
 * @param searchPattern the pattern to be examined as a String
 * @param isFile        if true, the searchPattern is treated as a file name, if false, the searchPattern will be treated as a path
 * @return Returns all entries found for the given search pattern as a Map<String, String>, or null if no matches were found
 * @throws IOException on I/O errors
 */
public static Map<String, String> getContentsFromJarStream(JarInputStream jarStream, String searchPattern,
        boolean isFile) throws IOException {
    Map<String, String> jarContents = new HashMap<String, String>();
    int found = 0;
    try {
        if (jarStream != null) {
            JarEntry entry;
            while ((entry = jarStream.getNextJarEntry()) != null) {
                if (isFile) {
                    if (!entry.isDirectory() && entry.getName().endsWith(searchPattern)) {
                        final String name = entry.getName().substring(entry.getName().lastIndexOf("/") + 1);
                        jarContents.put(name, readFromJarEntry(jarStream, entry));
                        found++;
                    }
                } else {
                    if (!entry.isDirectory() && entry.getName().startsWith(searchPattern)) {
                        jarContents.put(entry.getName(), readFromJarEntry(jarStream, entry));
                        found++;
                    }
                }
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found " + found + " entries in the JarInputStream for the pattern " + searchPattern);
            }
        }
    } finally {
        if (jarStream != null) {
            try {
                jarStream.close();
            } catch (IOException e) {
                LOG.warn("Failed to close stream: " + e.getMessage(), e);
            }
        } else {
            LOG.warn("JarInputStream parameter was null, no search performed");
        }
    }

    return jarContents.isEmpty() ? null : jarContents;
}

From source file:com.evolveum.midpoint.test.ldap.OpenDJController.java

/**
 * Extract template from class/*from   w ww  .jav  a2 s .  c  om*/
 */
private void extractTemplate(File dst, String templateName) throws IOException, URISyntaxException {

    LOGGER.info("Extracting OpenDJ template....");
    if (!dst.exists()) {
        LOGGER.debug("Creating target dir {}", dst.getPath());
        dst.mkdirs();
    }

    templateRoot = new File(DATA_TEMPLATE_DIR, templateName);
    String templateRootPath = DATA_TEMPLATE_DIR + "/" + templateName; // templateRoot.getPath does not work on Windows, as it puts "\" into the path name (leading to problems with getSystemResource)

    // Determing if we need to extract from JAR or directory
    if (templateRoot.isDirectory()) {
        LOGGER.trace("Need to do directory copy.");
        MiscUtil.copyDirectory(templateRoot, dst);
        return;
    }

    LOGGER.debug("Try to localize OpenDJ Template in JARs as " + templateRootPath);

    URL srcUrl = ClassLoader.getSystemResource(templateRootPath);
    LOGGER.debug("srcUrl " + srcUrl);
    // sample:
    // file:/C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar!/test-data/opendj.template
    // output:
    // /C:/.m2/repository/test-util/1.9-SNAPSHOT/test-util-1.9-SNAPSHOT.jar
    //
    // beware that in the URL there can be spaces encoded as %20, e.g.
    // file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar!/test-data/opendj.template
    //
    if (srcUrl.getPath().contains("!/")) {
        URI srcFileUri = new URI(srcUrl.getPath().split("!/")[0]); // e.g. file:/C:/Documents%20and%20Settings/user/.m2/repository/com/evolveum/midpoint/infra/test-util/2.1-SNAPSHOT/test-util-2.1-SNAPSHOT.jar
        File srcFile = new File(srcFileUri);
        JarFile jar = new JarFile(srcFile);
        LOGGER.debug("Extracting OpenDJ from JAR file {} to {}", srcFile.getPath(), dst.getPath());

        Enumeration<JarEntry> entries = jar.entries();

        JarEntry e;
        byte buf[] = new byte[655360];
        while (entries.hasMoreElements()) {
            e = entries.nextElement();

            // skip other files
            if (!e.getName().contains(templateRootPath)) {
                continue;
            }

            // prepare destination file
            String filepath = e.getName().substring(templateRootPath.length());
            File dstFile = new File(dst, filepath);

            // test if directory
            if (e.isDirectory()) {
                LOGGER.debug("Create directory: {}", dstFile.getAbsolutePath());
                dstFile.mkdirs();
                continue;
            }

            LOGGER.debug("Extract {} to {}", filepath, dstFile.getAbsolutePath());
            // Find file on classpath
            InputStream is = ClassLoader.getSystemResourceAsStream(e.getName());
            // InputStream is = jar.getInputStream(e); //old way

            // Copy content
            OutputStream out = new FileOutputStream(dstFile);
            int len;
            while ((len = is.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.close();
            is.close();
        }
        jar.close();
    } else {
        try {
            File file = new File(srcUrl.toURI());
            File[] files = file.listFiles();
            for (File subFile : files) {
                if (subFile.isDirectory()) {
                    MiscUtil.copyDirectory(subFile, new File(dst, subFile.getName()));
                } else {
                    MiscUtil.copyFile(subFile, new File(dst, subFile.getName()));
                }
            }
        } catch (Exception ex) {
            throw new IOException(ex);
        }
    }
    LOGGER.debug("OpenDJ Extracted");
}

From source file:org.jahia.tools.maven.plugins.LegalArtifactAggregator.java

private void processJarFile(InputStream inputStream, String jarFilePath, JarMetadata contextJarMetadata,
        boolean processMavenPom, int level, boolean lookForNotice, boolean lookForLicense,
        boolean processingSources) throws IOException {
    // if we don't need to find either a license or notice, don't process the jar at all
    if (!lookForLicense && !lookForNotice) {
        return;/*from   w w  w.j  av  a  2 s. c  o  m*/
    }

    final String indent = getIndent(level);
    output(indent, "Processing JAR " + jarFilePath + "...", false, true);

    // JarFile realJarFile = new JarFile(jarFile);
    JarInputStream jarInputStream = new JarInputStream(inputStream);
    String bundleLicense = null;
    Manifest manifest = jarInputStream.getManifest();
    if (manifest != null && manifest.getMainAttributes() != null) {
        bundleLicense = manifest.getMainAttributes().getValue("Bundle-License");
        if (bundleLicense != null) {
            output(indent, "Found Bundle-License attribute with value:" + bundleLicense);
            KnownLicense knownLicense = getKnowLicenseByName(bundleLicense);
            // this data is not reliable, especially on the ServiceMix repackaged bundles
        }
    }
    String pomFilePath = null;
    byte[] pomByteArray = null;

    final String jarFileName = getJarFileName(jarFilePath);
    if (contextJarMetadata == null) {
        contextJarMetadata = jarDatabase.get(jarFileName);
        if (contextJarMetadata == null) {
            // compute project name
            contextJarMetadata = new JarMetadata(jarFilePath, jarFileName);
        }
        jarDatabase.put(jarFileName, contextJarMetadata);
    }

    Notice notice;
    JarEntry curJarEntry = null;
    while ((curJarEntry = jarInputStream.getNextJarEntry()) != null) {

        if (!curJarEntry.isDirectory()) {
            final String fileName = curJarEntry.getName();
            if (lookForNotice && isNotice(fileName, jarFilePath)) {

                output(indent, "Processing notice found in " + curJarEntry + "...");

                InputStream noticeInputStream = jarInputStream;
                List<String> noticeLines = IOUtils.readLines(noticeInputStream);
                notice = new Notice(noticeLines);

                Map<String, Notice> notices = contextJarMetadata.getNoticeFiles();
                if (notices == null) {
                    notices = new TreeMap<>();
                    notices.put(fileName, notice);
                    output(indent, "Found first notice " + curJarEntry);
                } else if (!notices.containsValue(notice)) {
                    output(indent, "Found additional notice " + curJarEntry);
                    notices.put(fileName, notice);
                } else {
                    output(indent, "Duplicated notice in " + curJarEntry);
                    notices.put(fileName, notice);
                    duplicatedNotices.add(jarFilePath);
                }

                // IOUtils.closeQuietly(noticeInputStream);
            } else if (processMavenPom && fileName.endsWith("pom.xml")) {
                // remember pom file path in case we need it
                pomFilePath = curJarEntry.getName();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(jarInputStream, byteArrayOutputStream);
                pomByteArray = byteArrayOutputStream.toByteArray();

            } else if (lookForLicense && isLicense(fileName, jarFilePath)) {

                output(indent, "Processing license found in " + curJarEntry + "...");
                InputStream licenseInputStream = jarInputStream;
                List<String> licenseLines = IOUtils.readLines(licenseInputStream);

                LicenseFile licenseFile = new LicenseFile(jarFilePath, fileName, jarFilePath, licenseLines);

                resolveKnownLicensesByText(licenseFile);

                if (StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText())
                        && StringUtils.isNotBlank(licenseFile.getAdditionalLicenseText().trim())) {
                    KnownLicense knownLicense = new KnownLicense();
                    knownLicense.setId(FilenameUtils.getBaseName(jarFilePath) + "-additional-terms");
                    knownLicense
                            .setName("Additional license terms from " + FilenameUtils.getBaseName(jarFilePath));
                    List<TextVariant> textVariants = new ArrayList<>();
                    TextVariant textVariant = new TextVariant();
                    textVariant.setId("default");
                    textVariant.setDefaultVariant(true);
                    textVariant.setText(Pattern.quote(licenseFile.getAdditionalLicenseText()));
                    textVariants.add(textVariant);
                    knownLicense.setTextVariants(textVariants);
                    knownLicense.setTextToUse(licenseFile.getAdditionalLicenseText());
                    knownLicense.setViral(licenseFile.getText().toLowerCase().contains("gpl"));
                    knownLicenses.getLicenses().put(knownLicense.getId(), knownLicense);
                    licenseFile.getKnownLicenses().add(knownLicense);
                    licenseFile.getKnownLicenseKeys().add(knownLicense.getId());
                }

                for (KnownLicense knownLicense : licenseFile.getKnownLicenses()) {
                    SortedSet<LicenseFile> licenseFiles = knownLicensesFound.get(knownLicense);
                    if (licenseFiles != null) {
                        if (!licenseFiles.contains(licenseFile)) {
                            licenseFiles.add(licenseFile);
                        }
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    } else {
                        licenseFiles = new TreeSet<>();
                        licenseFiles.add(licenseFile);
                        knownLicensesFound.put(knownLicense, licenseFiles);
                    }
                }

                Map<String, LicenseFile> licenseFiles = contextJarMetadata.getLicenseFiles();
                if (licenseFiles == null) {
                    licenseFiles = new TreeMap<>();
                }
                if (licenseFiles.containsKey(fileName)) {
                    // warning we already have a license file here, what should we do ?
                    output(indent, "License file already exists for " + jarFilePath + " will override it !",
                            true, false);
                    licenseFiles.remove(fileName);
                }
                licenseFiles.put(fileName, licenseFile);

                // IOUtils.closeQuietly(licenseInputStream);

            } else if (fileName.endsWith(".jar")) {
                InputStream embeddedJarInputStream = jarInputStream;
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                IOUtils.copy(embeddedJarInputStream, byteArrayOutputStream);
                final JarMetadata embeddedJarMetadata = new JarMetadata(jarFilePath, getJarFileName(fileName));

                if (embeddedJarMetadata != null) {
                    embeddedJarMetadata.setJarContents(byteArrayOutputStream.toByteArray());
                    contextJarMetadata.getEmbeddedJars().add(embeddedJarMetadata);
                }
            } else if (fileName.endsWith(".class")) {
                String className = fileName.substring(0, fileName.length() - ".class".length()).replaceAll("/",
                        ".");
                int lastPoint = className.lastIndexOf(".");
                String packageName = null;
                if (lastPoint > 0) {
                    packageName = className.substring(0, lastPoint);
                    SortedSet<String> currentJarPackages = jarDatabase
                            .get(FilenameUtils.getBaseName(jarFilePath)).getPackages();
                    if (currentJarPackages == null) {
                        currentJarPackages = new TreeSet<>();
                    }
                    currentJarPackages.add(packageName);
                }
            }

        }
        jarInputStream.closeEntry();
    }

    jarInputStream.close();
    jarInputStream = null;

    if (!contextJarMetadata.getEmbeddedJars().isEmpty()) {
        for (JarMetadata embeddedJarMetadata : contextJarMetadata.getEmbeddedJars()) {
            if (embeddedJarMetadata.getJarContents() != null) {
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                        embeddedJarMetadata.getJarContents());
                processJarFile(byteArrayInputStream, contextJarMetadata.toString(), null, true, level, true,
                        true, processingSources);
            } else {
                output(indent, "Couldn't find dependency for embedded JAR " + contextJarMetadata, true, false);
            }
        }
    }

    if (processMavenPom) {
        if (pomFilePath == null) {
            output(indent, "No POM found in " + jarFilePath);
        } else {
            output(indent, "Processing POM found at " + pomFilePath + " in " + jarFilePath + "...");
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(pomByteArray);
            processJarPOM(byteArrayInputStream, pomFilePath, jarFilePath, contextJarMetadata, lookForNotice,
                    lookForLicense, contextJarMetadata.getEmbeddedJars(), level + 1, processingSources);
        }
    }

    if (lookForLicense || lookForNotice) {
        if (lookForLicense) {
            output(indent, "No license found in " + jarFilePath);
        }
        if (lookForNotice) {
            output(indent, "No notice found in " + jarFilePath);
        }

        if (pomFilePath == null && lookForLicense && lookForNotice) {
            if (StringUtils.isBlank(contextJarMetadata.getVersion())) {
                output(indent, "Couldn't resolve version for JAR " + contextJarMetadata
                        + ", can't query Maven Central repository without version !");
            } else {
                List<Artifact> mavenCentralArtifacts = findArtifactInMavenCentral(contextJarMetadata.getName(),
                        contextJarMetadata.getVersion(), contextJarMetadata.getClassifier());
                if (mavenCentralArtifacts != null && mavenCentralArtifacts.size() == 1) {
                    Artifact mavenCentralArtifact = mavenCentralArtifacts.get(0);
                    Artifact resolvedArtifact = resolveArtifact(mavenCentralArtifact, level);
                    if (resolvedArtifact != null) {
                        // we have a copy of the local artifact, let's request the sources for it.
                        if (!processingSources && !"sources".equals(contextJarMetadata.getClassifier())) {
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), "sources", "jar",
                                    resolvedArtifact.getVersion());
                            File sourceJar = getArtifactFile(artifact, level);
                            if (sourceJar != null && sourceJar.exists()) {
                                FileInputStream sourceJarInputStream = new FileInputStream(sourceJar);
                                processJarFile(sourceJarInputStream, sourceJar.getPath(), contextJarMetadata,
                                        false, level + 1, lookForNotice, lookForLicense, true);
                                IOUtils.closeQuietly(sourceJarInputStream);
                            }
                        } else {
                            // we are already processing a sources artifact, we need to load the pom artifact to extract information from there
                            final Artifact artifact = new DefaultArtifact(resolvedArtifact.getGroupId(),
                                    resolvedArtifact.getArtifactId(), null, "pom",
                                    resolvedArtifact.getVersion());
                            File artifactPom = getArtifactFile(artifact, level);
                            if (artifactPom != null && artifactPom.exists()) {
                                output(indent, "Processing POM for " + artifact + "...");
                                processPOM(lookForNotice, lookForLicense, jarFilePath, contextJarMetadata,
                                        contextJarMetadata.getEmbeddedJars(), level + 1,
                                        new FileInputStream(artifactPom), processingSources);
                            }
                        }
                    } else {
                        output(indent, "===>  Couldn't resolve artifact " + mavenCentralArtifact
                                + " in Maven Central. Please resolve license and notice files manually!", false,
                                true);
                    }
                } else {
                    output(indent, "===>  Couldn't find nor POM, license or notice. Please check manually!",
                            false, true);
                }
            }
        }
    }

    output(indent, "Done processing JAR " + jarFilePath + ".", false, true);

}

From source file:UnpackedJarFile.java

public NestedJarFile(JarFile jarFile, String path) throws IOException {
    super(DeploymentUtil.DUMMY_JAR_FILE);

    // verify that the jar actually contains that path
    JarEntry targetEntry = jarFile.getJarEntry(path + "/");
    if (targetEntry == null) {
        targetEntry = jarFile.getJarEntry(path);
        if (targetEntry == null) {
            throw new IOException("Jar entry does not exist: jarFile=" + jarFile.getName() + ", path=" + path);
        }//from  w ww.ja v a 2  s  .  c  o m
    }

    if (targetEntry.isDirectory()) {
        if (targetEntry instanceof UnpackedJarEntry) {
            //unpacked nested module inside unpacked ear
            File targetFile = ((UnpackedJarEntry) targetEntry).getFile();
            baseJar = new UnpackedJarFile(targetFile);
            basePath = "";
        } else {
            baseJar = jarFile;
            if (!path.endsWith("/")) {
                path += "/";
            }
            basePath = path;
        }
    } else {
        if (targetEntry instanceof UnpackedJarEntry) {
            // for unpacked jars we don't need to copy the jar file
            // out to a temp directory, since it is already available
            // as a raw file
            File targetFile = ((UnpackedJarEntry) targetEntry).getFile();
            baseJar = new JarFile(targetFile);
            basePath = "";
        } else {
            tempFile = DeploymentUtil.toFile(jarFile, targetEntry.getName());
            baseJar = new JarFile(tempFile);
            basePath = "";
        }
    }
}

From source file:UnpackedJarFile.java

public InputStream getInputStream(ZipEntry zipEntry) throws IOException {
    if (isClosed) {
        throw new IllegalStateException("NestedJarFile is closed");
    }/*w ww.  ja  va2 s.  com*/

    JarEntry baseEntry;
    if (zipEntry instanceof NestedJarEntry) {
        baseEntry = ((NestedJarEntry) zipEntry).getBaseEntry();
    } else {
        baseEntry = getBaseEntry(zipEntry.getName());
    }

    if (baseEntry == null) {
        throw new IOException("Entry not found: name=" + zipEntry.getName());
    } else if (baseEntry.isDirectory()) {
        return new DeploymentUtil.EmptyInputStream();
    }
    return baseJar.getInputStream(baseEntry);
}

From source file:org.corpus_tools.salt.util.VisJsVisualizer.java

private File createOutputResources(URI outputFileUri)
        throws SaltParameterException, SecurityException, FileNotFoundException, IOException {
    File outputFolder = null;//from w w  w . j av  a  2 s. c o m
    if (outputFileUri == null) {
        throw new SaltParameterException("Cannot store salt-vis, because the passed output uri is empty. ");
    }
    outputFolder = new File(outputFileUri.path());
    if (!outputFolder.exists()) {
        if (!outputFolder.mkdirs()) {
            throw new SaltException("Can't create folder " + outputFolder.getAbsolutePath());
        }
    }

    File cssFolderOut = new File(outputFolder, CSS_FOLDER_OUT);
    if (!cssFolderOut.exists()) {
        if (!cssFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + cssFolderOut.getAbsolutePath());
        }
    }

    File jsFolderOut = new File(outputFolder, JS_FOLDER_OUT);
    if (!jsFolderOut.exists()) {
        if (!jsFolderOut.mkdir()) {
            throw new SaltException("Can't create folder " + jsFolderOut.getAbsolutePath());
        }
    }

    File imgFolderOut = new File(outputFolder, IMG_FOLDER_OUT);
    if (!imgFolderOut.exists()) {
        if (!imgFolderOut.mkdirs()) {
            throw new SaltException("Can't create folder " + imgFolderOut.getAbsolutePath());
        }
    }

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + CSS_FILE),
            outputFolder.getPath(), CSS_FOLDER_OUT, CSS_FILE);

    copyResourceFile(
            getClass().getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JS_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JS_FILE);

    copyResourceFile(
            getClass()
                    .getResourceAsStream(RESOURCE_FOLDER + System.getProperty("file.separator") + JQUERY_FILE),
            outputFolder.getPath(), JS_FOLDER_OUT, JQUERY_FILE);

    ClassLoader classLoader = getClass().getClassLoader();
    CodeSource srcCode = VisJsVisualizer.class.getProtectionDomain().getCodeSource();
    URL codeSourceUrl = srcCode.getLocation();
    File codeSourseFile = new File(codeSourceUrl.getPath());

    if (codeSourseFile.isDirectory()) {
        File imgFolder = new File(classLoader.getResource(RESOURCE_FOLDER_IMG_NETWORK).getFile());
        File[] imgFiles = imgFolder.listFiles();
        if (imgFiles != null) {
            for (File imgFile : imgFiles) {
                InputStream inputStream = getClass()
                        .getResourceAsStream(System.getProperty("file.separator") + RESOURCE_FOLDER_IMG_NETWORK
                                + System.getProperty("file.separator") + imgFile.getName());
                copyResourceFile(inputStream, outputFolder.getPath(), IMG_FOLDER_OUT, imgFile.getName());
            }
        }
    } else if (codeSourseFile.getName().endsWith("jar")) {
        JarFile jarFile = new JarFile(codeSourseFile);
        Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.getName().startsWith(RESOURCE_FOLDER_IMG_NETWORK) && !entry.isDirectory()) {

                copyResourceFile(jarFile.getInputStream(entry), outputFolder.getPath(), IMG_FOLDER_OUT,
                        entry.getName().replaceFirst(RESOURCE_FOLDER_IMG_NETWORK, ""));
            }

        }
        jarFile.close();

    }

    return outputFolder;
}

From source file:org.apache.archiva.rest.services.DefaultBrowseService.java

protected List<ArtifactContentEntry> readFileEntries(File file, String filterPath, String repoId)
        throws IOException {
    Map<String, ArtifactContentEntry> artifactContentEntryMap = new HashMap<>();
    int filterDepth = StringUtils.countMatches(filterPath, "/");
    /*if ( filterDepth == 0 )
    {/*from   w  ww  .j av a 2 s .c o  m*/
    filterDepth = 1;
    }*/
    JarFile jarFile = new JarFile(file);
    try {
        Enumeration<JarEntry> jarEntryEnumeration = jarFile.entries();
        while (jarEntryEnumeration.hasMoreElements()) {
            JarEntry currentEntry = jarEntryEnumeration.nextElement();
            String cleanedEntryName = StringUtils.endsWith(currentEntry.getName(), "/") ? //
                    StringUtils.substringBeforeLast(currentEntry.getName(), "/") : currentEntry.getName();
            String entryRootPath = getRootPath(cleanedEntryName);
            int depth = StringUtils.countMatches(cleanedEntryName, "/");
            if (StringUtils.isEmpty(filterPath) //
                    && !artifactContentEntryMap.containsKey(entryRootPath) //
                    && depth == filterDepth) {

                artifactContentEntryMap.put(entryRootPath,
                        new ArtifactContentEntry(entryRootPath, !currentEntry.isDirectory(), depth, repoId));
            } else {
                if (StringUtils.startsWith(cleanedEntryName, filterPath) //
                        && (depth == filterDepth || (!currentEntry.isDirectory() && depth == filterDepth))) {
                    artifactContentEntryMap.put(cleanedEntryName, new ArtifactContentEntry(cleanedEntryName,
                            !currentEntry.isDirectory(), depth, repoId));
                }
            }
        }

        if (StringUtils.isNotEmpty(filterPath)) {
            Map<String, ArtifactContentEntry> filteredArtifactContentEntryMap = new HashMap<>();

            for (Map.Entry<String, ArtifactContentEntry> entry : artifactContentEntryMap.entrySet()) {
                filteredArtifactContentEntryMap.put(entry.getKey(), entry.getValue());
            }

            List<ArtifactContentEntry> sorted = getSmallerDepthEntries(filteredArtifactContentEntryMap);
            if (sorted == null) {
                return Collections.emptyList();
            }
            Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
            return sorted;
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
    List<ArtifactContentEntry> sorted = new ArrayList<>(artifactContentEntryMap.values());
    Collections.sort(sorted, ArtifactContentEntryComparator.INSTANCE);
    return sorted;
}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * Performs the webapp specific startup needs for modules Normal startup is done in
 * {@link ModuleFactory#startModule(Module)} If delayContextRefresh is true, the spring context
 * is not rerun. This will save a lot of time, but it also means that the calling method is
 * responsible for restarting the context if necessary (the calling method will also have to
 * call {@link #loadServlets(Module, ServletContext)} and
 * {@link #loadFilters(Module, ServletContext)}).<br>
 * <br>/*from   www .jav a 2  s .  c  o  m*/
 * If delayContextRefresh is true and this module should have caused a context refresh, a true
 * value is returned. Otherwise, false is returned
 *
 * @param mod Module to start
 * @param servletContext the current ServletContext
 * @param delayContextRefresh true/false whether or not to do the context refresh
 * @return boolean whether or not the spring context need to be refreshed
 */
public static boolean startModule(Module mod, ServletContext servletContext, boolean delayContextRefresh) {

    if (log.isDebugEnabled()) {
        log.debug("trying to start module " + mod);
    }

    // only try and start this module if the api started it without a
    // problem.
    if (ModuleFactory.isModuleStarted(mod) && !mod.hasStartupError()) {

        String realPath = getRealPath(servletContext);

        if (realPath == null) {
            realPath = System.getProperty("user.dir");
        }

        File webInf = new File(realPath + "/WEB-INF".replace("/", File.separator));
        if (!webInf.exists()) {
            webInf.mkdir();
        }

        copyModuleMessagesIntoWebapp(mod, realPath);
        log.debug("Done copying messages");

        // flag to tell whether we added any xml/dwr/etc changes that necessitate a refresh
        // of the web application context
        boolean moduleNeedsContextRefresh = false;

        // copy the html files into the webapp (from /web/module/ in the module)
        // also looks for a spring context file. If found, schedules spring to be restarted
        JarFile jarFile = null;
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            File modFile = mod.getFile();
            jarFile = new JarFile(modFile);
            Enumeration<JarEntry> entries = jarFile.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                log.debug("Entry name: " + name);
                if (name.startsWith("web/module/")) {
                    // trim out the starting path of "web/module/"
                    String filepath = name.substring(11);

                    StringBuffer absPath = new StringBuffer(realPath + "/WEB-INF");

                    // If this is within the tag file directory, copy it into /WEB-INF/tags/module/moduleId/...
                    if (filepath.startsWith("tags/")) {
                        filepath = filepath.substring(5);
                        absPath.append("/tags/module/");
                    }
                    // Otherwise, copy it into /WEB-INF/view/module/moduleId/...
                    else {
                        absPath.append("/view/module/");
                    }

                    // if a module id has a . in it, we should treat that as a /, i.e. files in the module
                    // ui.springmvc should go in folder names like .../ui/springmvc/...
                    absPath.append(mod.getModuleIdAsPath() + "/" + filepath);
                    if (log.isDebugEnabled()) {
                        log.debug("Moving file from: " + name + " to " + absPath);
                    }

                    // get the output file
                    File outFile = new File(absPath.toString().replace("/", File.separator));
                    if (entry.isDirectory()) {
                        if (!outFile.exists()) {
                            outFile.mkdirs();
                        }
                    } else {
                        // make the parent directories in case it doesn't exist
                        File parentDir = outFile.getParentFile();
                        if (!parentDir.exists()) {
                            parentDir.mkdirs();
                        }

                        //if (outFile.getName().endsWith(".jsp") == false)
                        //   outFile = new File(absPath.replace("/", File.separator) + MODULE_NON_JSP_EXTENSION);

                        // copy the contents over to the webapp for non directories
                        outStream = new FileOutputStream(outFile, false);
                        inStream = jarFile.getInputStream(entry);
                        OpenmrsUtil.copyFile(inStream, outStream);
                    }
                } else if (name.equals("moduleApplicationContext.xml")
                        || name.equals("webModuleApplicationContext.xml")) {
                    moduleNeedsContextRefresh = true;
                } else if (name.equals(mod.getModuleId() + "Context.xml")) {
                    String msg = "DEPRECATED: '" + name
                            + "' should be named 'moduleApplicationContext.xml' now. Please update/upgrade. ";
                    throw new ModuleException(msg, mod.getModuleId());
                }
            }
        } catch (IOException io) {
            log.warn("Unable to copy files from module " + mod.getModuleId() + " to the web layer", io);
        } finally {
            if (jarFile != null) {
                try {
                    jarFile.close();
                } catch (IOException io) {
                    log.warn("Couldn't close jar file: " + jarFile.getName(), io);
                }
            }
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close InputStream: " + io);
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException io) {
                    log.warn("Couldn't close OutputStream: " + io);
                }
            }
        }

        // find and add the dwr code to the dwr-modules.xml file (if defined)
        InputStream inputStream = null;
        try {
            Document config = mod.getConfig();
            Element root = config.getDocumentElement();
            if (root.getElementsByTagName("dwr").getLength() > 0) {

                // get the dwr-module.xml file that we're appending our code to
                File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator));

                // testing if file exists
                if (!f.exists()) {
                    // if it does not -> needs to be created
                    createDwrModulesXml(realPath);
                }

                inputStream = new FileInputStream(f);
                Document dwrmodulexml = getDWRModuleXML(inputStream, realPath);
                Element outputRoot = dwrmodulexml.getDocumentElement();

                // loop over all of the children of the "dwr" tag
                Node node = root.getElementsByTagName("dwr").item(0);
                Node current = node.getFirstChild();

                while (current != null) {
                    if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName())
                            || "init".equals(current.getNodeName())) {
                        ((Element) current).setAttribute("moduleId", mod.getModuleId());
                        outputRoot.appendChild(dwrmodulexml.importNode(current, true));
                    }

                    current = current.getNextSibling();
                }

                moduleNeedsContextRefresh = true;

                // save the dwr-modules.xml file.
                OpenmrsUtil.saveDocument(dwrmodulexml, f);
            }
        } catch (FileNotFoundException e) {
            throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException io) {
                    log.error("Error while closing input stream", io);
                }
            }
        }

        // mark to delete the entire module web directory on exit
        // this will usually only be used when an improper shutdown has occurred.
        String folderPath = realPath + "/WEB-INF/view/module/" + mod.getModuleIdAsPath();
        File outFile = new File(folderPath.replace("/", File.separator));
        outFile.deleteOnExit();

        // additional checks on module needing a context refresh
        if (moduleNeedsContextRefresh == false && mod.getAdvicePoints() != null
                && mod.getAdvicePoints().size() > 0) {

            // AOP advice points are only loaded during the context refresh now.
            // if the context hasn't been marked to be refreshed yet, mark it
            // now if this module defines some advice
            moduleNeedsContextRefresh = true;

        }

        // refresh the spring web context to get the just-created xml
        // files into it (if we copied an xml file)
        if (moduleNeedsContextRefresh && delayContextRefresh == false) {
            if (log.isDebugEnabled()) {
                log.debug("Refreshing context for module" + mod);
            }

            try {
                refreshWAC(servletContext, false, mod);
                log.debug("Done Refreshing WAC");
            } catch (Exception e) {
                String msg = "Unable to refresh the WebApplicationContext";
                mod.setStartupErrorMessage(msg, e);

                if (log.isWarnEnabled()) {
                    log.warn(msg + " for module: " + mod.getModuleId(), e);
                }

                try {
                    stopModule(mod, servletContext, true);
                    ModuleFactory.stopModule(mod, true, true); //remove jar from classloader play
                } catch (Exception e2) {
                    // exception expected with most modules here
                    if (log.isWarnEnabled()) {
                        log.warn("Error while stopping a module that had an error on refreshWAC", e2);
                    }
                }

                // try starting the application context again
                refreshWAC(servletContext, false, mod);

                notifySuperUsersAboutModuleFailure(mod);
            }

        }

        if (!delayContextRefresh && ModuleFactory.isModuleStarted(mod)) {
            // only loading the servlets/filters if spring is refreshed because one
            // might depend on files being available in spring
            // if the caller wanted to delay the refresh then they are responsible for
            // calling these two methods on the module

            // find and cache the module's servlets
            //(only if the module started successfully previously)
            log.debug("Loading servlets and filters for module: " + mod);
            loadServlets(mod, servletContext);
            loadFilters(mod, servletContext);
        }

        // return true if the module needs a context refresh and we didn't do it here
        return (moduleNeedsContextRefresh && delayContextRefresh == true);

    }

    // we aren't processing this module, so a context refresh is not necessary
    return false;
}