Example usage for java.util.jar JarEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

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//w  w  w  .j  a v  a  2  s. c  o 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:org.springfield.lou.application.ApplicationManager.java

private void processUploadedWar(File warfile, String wantedname) {
    // lets first check some vitals to check what it is
    String warfilename = warfile.getName();
    if (warfilename.startsWith("smt_") && warfilename.endsWith("app.war")) {
        // ok so filename checks out is smt_[name]app.war format
        String appname = warfilename.substring(4, warfilename.length() - 7);
        if (wantedname.equals(appname)) {
            // ok found file is the wanted file
            // format "29-Aug-2013-16:55"
            System.out.println("NEW VERSION OF " + appname + " FOUND INSTALLING");
            Date now = new Date();
            SimpleDateFormat df = new SimpleDateFormat("d-MMM-yyyy-HH:mm");
            String datestring = df.format(now);
            String writedir = "/springfield/lou/apps/" + appname + "/" + datestring;

            // create the node
            Html5AvailableApplication vapp = getAvailableApplication(appname);
            String newbody = "<fsxml><properties></properties></fsxml>";

            ServiceInterface smithers = ServiceManager.getService("smithers");
            if (smithers == null)
                return;
            FsNode tnode = Fs.getNode("/domain/internal/service/lou/apps/" + appname);
            if (tnode == null) {
                smithers.put("/domain/internal/service/lou/apps/" + appname + "/properties", newbody,
                        "text/xml");
            }/*  w  ww  .  ja v  a 2s .  c o  m*/
            smithers.put(
                    "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring + "/properties",
                    newbody, "text/xml");

            // make all the dirs we need
            File md = new File(writedir);
            md.mkdirs();
            md = new File(writedir + "/war");
            md.mkdirs();
            md = new File(writedir + "/jar");
            md.mkdirs();
            md = new File(writedir + "/components");
            md.mkdirs();
            md = new File(writedir + "/css");
            md.mkdirs();
            md = new File(writedir + "/libs");
            md.mkdirs();

            try {
                JarFile war = new JarFile(warfile);

                // ok lets first find the jar file !
                JarEntry entry = war.getJarEntry("WEB-INF/lib/smt_" + appname + "app.jar");
                if (entry != null) {
                    byte[] bytes = readJarEntryToBytes(war.getInputStream(entry));
                    writeBytesToFile(bytes, writedir + "/jar/smt_" + appname + "app.jar");
                }
                // unpack all in eddie dir
                Enumeration<JarEntry> iter = war.entries();
                while (iter.hasMoreElements()) {
                    JarEntry lentry = iter.nextElement();
                    //System.out.println("LI="+lentry.getName());
                    String lname = lentry.getName();
                    if (!lname.endsWith("/")) {
                        int pos = lname.indexOf("/" + appname + "/");
                        if (pos != -1) {
                            String nname = lname.substring(pos + appname.length() + 2);
                            String dname = nname.substring(0, nname.lastIndexOf('/'));
                            File de = new File(writedir + "/" + dname);
                            de.mkdirs();
                            byte[] bytes = readJarEntryToBytes(war.getInputStream(lentry));
                            writeBytesToFile(bytes, writedir + "/" + nname);
                        }
                    }
                }
                war.close();
                File ren = new File("/springfield/lou/uploaddir/" + warfilename);
                File nen = new File(writedir + "/war/smt_" + appname + "app.war");
                //System.out.println("REN="+warfilename);
                //System.out.println("REN="+writedir+"/war/smt_"+appname+"app.war");
                ren.renameTo(nen);

                loadAvailableApps();
                // should we make in development or production based on autodeploy ?
                vapp = getAvailableApplication(appname);
                if (vapp != null) {
                    String mode = vapp.getAutoDeploy();
                    if (appname.equals("dashboard")) {
                        mode = "development/production";
                    }
                    System.out.println("APPNAME=" + appname + " mode=" + mode);
                    if (mode.equals("production")) {
                        makeProduction(appname, datestring);
                    } else if (mode.equals("development")) {
                        makeDevelopment(appname, datestring);
                    } else if (mode.equals("development/production")) {
                        makeDevelopment(appname, datestring);
                        makeProduction(appname, datestring);
                    }
                }

                /*
                Html5ApplicationInterface app = getApplication("/domain/webtv/html5application/dashboard");
                if (app!=null) {
                 DashboardApplication dapp = (DashboardApplication)app;
                 dapp.newApplicationFound(appname);
                }
                */

                // lets tell set the available variable to tell the others we have it.
                FsNode unode = Fs
                        .getNode("/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring);
                if (unode != null) {
                    String warlist = unode.getProperty("waravailableat");
                    if (warlist == null || warlist.equals("")) {
                        Fs.setProperty(
                                "/domain/internal/service/lou/apps/" + appname + "/versions/" + datestring,
                                "waravailableat", LazyHomer.myip);
                    } else {
                        System.out.println("BUG ? Already available war " + warlist + " a=" + appname);
                    }
                }
            } catch (Exception e) {
                System.out.println("VERSION NOT READY STILL UPLOADING? RETRY WILL HAPPEN SOON");
            }
        }
    }
}

From source file:com.rbmhtechnology.apidocserver.controller.ApiDocController.java

private void serveFileFromJarFile(HttpServletResponse response, File jar, String subPath) throws IOException {
    JarFile jarFile = null;/*from w  w w  .j a  v  a 2 s.  c o m*/
    try {
        jarFile = new JarFile(jar);
        JarEntry entry = jarFile.getJarEntry(subPath);

        if (entry == null) {
            response.sendError(404);
            return;
        }

        // fallback for requesting a directory without a trailing /
        // this leads to a jarentry which is not null, and not a directory and of size 0
        // this shouldn't be
        if (!entry.isDirectory() && entry.getSize() == 0) {
            if (!subPath.endsWith("/")) {
                JarEntry entryWithSlash = jarFile.getJarEntry(subPath + "/");
                if (entryWithSlash != null && entryWithSlash.isDirectory()) {
                    entry = entryWithSlash;
                }
            }
        }

        if (entry.isDirectory()) {
            for (String indexFile : DEFAULT_INDEX_FILES) {
                entry = jarFile.getJarEntry((subPath.endsWith("/") ? subPath : subPath + "/") + indexFile);
                if (entry != null) {
                    break;
                }
            }
        }

        if (entry == null) {
            response.sendError(404);
            return;
        }

        response.setContentLength((int) entry.getSize());
        String mimetype = getMimeType(entry.getName());
        response.setContentType(mimetype);
        InputStream input = jarFile.getInputStream(entry);
        try {
            ByteStreams.copy(input, response.getOutputStream());
        } finally {
            input.close();
        }
    } finally {
        if (jarFile != null) {
            jarFile.close();
        }
    }
}

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

private File createOutputResources(URI outputFileUri)
        throws SaltParameterException, SecurityException, FileNotFoundException, IOException {
    File outputFolder = null;//from   ww w.  j  a v  a2  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.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  ww .j a v a 2  s.  com*/
    }

    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:com.flexive.shared.FxSharedUtils.java

/**
 * Reads the content of a given entry in a Jar file (JarInputStream) and returns it as a String
 *
 * @param jarStream the given JarInputStream
 * @param entry     the given entry in the jar file
 * @return the entry's content as a String
 * @throws java.io.IOException on errors
 *//*w w  w  .  ja  v  a  2s . com*/
public static String readFromJarEntry(JarInputStream jarStream, JarEntry entry) throws IOException {
    final String fileContent;
    if (entry.getSize() >= 0) {
        // allocate buffer for the entire (uncompressed) script code
        final byte[] buffer = new byte[(int) entry.getSize()];
        // decompress JAR entry
        int offset = 0;
        int readBytes;
        while ((readBytes = jarStream.read(buffer, offset, (int) entry.getSize() - offset)) > 0) {
            offset += readBytes;
        }
        if (offset != entry.getSize()) {
            throw new IOException("Failed to read complete script code for script: " + entry.getName());
        }
        fileContent = new String(buffer, "UTF-8").trim();
    } else {
        // use this method if the file size cannot be determined
        //(might be the case with jar files created with some jar tools)
        final StringBuilder out = new StringBuilder();
        final byte[] buf = new byte[1024];
        int readBytes;
        while ((readBytes = jarStream.read(buf, 0, buf.length)) > 0) {
            out.append(new String(buf, 0, readBytes, "UTF-8"));
        }
        fileContent = out.toString();
    }
    return fileContent;
}

From source file:ca.weblite.xmlvm.XMLVM.java

/**
 * Finds all of the classes from a given collection of class names that reside in a 
 * given path.  It also copies the found classes into a specified destination directory.
 * @param p The path to search.//  w ww .  j  a  v a2s  .  c  o  m
 * @param classNames The class names to search for.
 * @param found The class names that were found in that path.
 * @param destDir The directory where found classes will be copied to.
 * @throws IOException 
 */
public void findClassesInPath(Path p, Collection<String> classNames, Set<String> found, File destDir)
        throws IOException {
    for (String part : p.list()) {
        File f = new File(part);
        if (f.isDirectory()) {
            // We have a directory
            findClassesInPath(f, f, classNames, found, destDir);
        } else if (f.getName().endsWith(".jar")) {
            // We have a jar file
            JarFile jf = new JarFile(f);
            Enumeration<JarEntry> entries = jf.entries();

            Expand expand = (Expand) getProject().createTask("unzip");
            expand.setSrc(f);
            expand.setDest(destDir);
            boolean emptySet = true;

            while (entries.hasMoreElements()) {
                JarEntry nex = entries.nextElement();
                if (nex.getName().endsWith(".class")) {
                    String foundClassName = nex.getName().replaceAll("/", ".").replaceAll("\\.class$", "");
                    if (classNames.contains(foundClassName) && !found.contains(foundClassName)) {
                        found.add(foundClassName);
                        FilenameSelector sel = new FilenameSelector();
                        sel.setName(nex.getName());
                        ZipFileSet fs = new ZipFileSet();
                        fs.setFullpath(nex.getName());
                        expand.addFileset(fs);
                        emptySet = false;
                    }
                }
            }

            if (!emptySet) {
                expand.execute();
            }

        }
    }
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Searches within a jar file for available languages.
 * //from w  w  w .  ja v  a 2 s .  co  m
 * @param jarFile
 * @param checkForExecutables true: check if jar contains java or class files
 *          and return an empty set if such executable files are found; false
 *          don't check or care
 * @return Set of language keys, can be empty but never null
 */
public Set<String> sarchForAvailableLanguagesInJarFile(File jarFile, boolean checkForExecutables) {
    Set<String> foundLanguages = new TreeSet<String>();
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
        Enumeration<JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            // check for executables
            if (checkForExecutables && (jarEntryName.endsWith("java") || jarEntryName.endsWith("class"))) {
                return new TreeSet<String>();
            }
            // search for core util in jar
            if (jarEntryName
                    .indexOf(I18nModule.getCoreFallbackBundle().replace(".", "/") + "/" + I18N_DIRNAME) != -1) {
                // don't add overlayLocales as selectable
                // availableLanguages
                if (jarEntryName.indexOf("__") == -1
                        && jarEntryName.indexOf(I18nModule.LOCAL_STRINGS_FILE_PREFIX) != -1) {
                    String lang = jarEntryName.substring(
                            jarEntryName.indexOf(I18nModule.LOCAL_STRINGS_FILE_PREFIX)
                                    + I18nModule.LOCAL_STRINGS_FILE_PREFIX.length(),
                            jarEntryName.lastIndexOf("."));
                    foundLanguages.add(lang);
                    if (isLogDebugEnabled())
                        logDebug("Adding lang::" + lang + " from filename::" + jarEntryName + " in jar::"
                                + jar.getName(), null);
                }
            }
        }
    } catch (IOException e) {
        throw new OLATRuntimeException("Error when looking up i18n files in jar::" + jarFile.getAbsolutePath(),
                e);
    } finally {
        IOUtils.closeQuietly(jar);
    }
    return foundLanguages;
}

From source file:org.olat.core.util.i18n.I18nManager.java

/**
 * Copy the given set of languages from the given jar to the configured i18n
 * source directories. This method can only be called in a translation
 * server environment./*  w w  w  .ja  v  a 2s  .  c o  m*/
 * 
 * @param jarFile
 * @param toCopyI18nKeys
 */
public void copyLanguagesFromJar(File jarFile, Collection<String> toCopyI18nKeys) {
    if (!I18nModule.isTransToolEnabled()) {
        throw new AssertException(
                "Programming error - can only copy i18n files from a language pack to the source when in translation mode");
    }
    JarFile jar = null;
    try {
        jar = new JarFile(jarFile);
        Enumeration<JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            // Check if this entry is a language file
            for (String i18nKey : toCopyI18nKeys) {
                if (jarEntryName.endsWith(I18N_DIRNAME + "/" + I18nModule.LOCAL_STRINGS_FILE_PREFIX + i18nKey
                        + I18nModule.LOCAL_STRINGS_FILE_POSTFIX)) {
                    File targetBaseDir;
                    if (i18nKey.equals("de") || i18nKey.equals("en")) {
                        targetBaseDir = I18nModule.getTransToolApplicationLanguagesSrcDir();
                    } else {
                        targetBaseDir = I18nModule.getTransToolApplicationOptLanguagesSrcDir();
                    }
                    // Copy file
                    File targetFile = new File(targetBaseDir, jarEntryName);
                    targetFile.getParentFile().mkdirs();
                    FileUtils.save(jar.getInputStream(jarEntry), targetFile);
                    // Check that saved properties file is empty, if so remove it 
                    Properties props = new Properties();
                    props.load(new FileInputStream(targetFile));
                    if (props.size() == 0) {
                        targetFile.delete();
                        // Delete empty parent dirs recursively
                        File parent = targetFile.getParentFile();
                        while (parent != null && parent.list() != null && parent.list().length == 0) {
                            parent.delete();
                            parent = parent.getParentFile();
                        }
                    }
                    // Continue with next jar entry
                    break;
                }
            }
        }
    } catch (IOException e) {
        throw new OLATRuntimeException(
                "Error when copying up i18n files from a jar::" + jarFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(jar);
    }
}

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  .com*/
    }

    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 = "";
        }
    }
}